Question

Solve the code below:

session.py Provides an interface to session data. The database has a table sessions that stores user session data. Each sessiget_or_create_session(db) This fction is called to either retrieve the current session key from a cookie or create a new sess

CODE:

"""
Code for handling sessions in our web application
"""

from bottle import request, response
import uuid
import json

import model
import dbschema

COOKIE_NAME = 'session'


def get_or_create_session(db):
    """Get the current sessionid either from a
    cookie in the current request or by creating a
    new session if none are present.

    If a new session is created, a cookie is set in the response.

    Returns the session key (string)
    """


def add_to_cart(db, itemid, quantity):
    """Add an item to the shopping cart"""


def get_cart_contents(db):
    """Return the contents of the shopping cart as
    a list of dictionaries:
    [{'id': , 'quantity': , 'name': , 'cost': }, ...]
    """

************************* test_session.py ********************************

import unittest
from bottle import request, response
from http.cookies import SimpleCookie

import session
import dbschema


class SessionTests(unittest.TestCase):

    def setUp(self):

        # init an in-memory database
        self.db = dbschema.connect(':memory:')
        dbschema.create_tables(self.db)
        self.products = dbschema.sample_data(self.db)

    def tearDown(self):

        # must remove our fake cookie from the global request
        if session.COOKIE_NAME in request.cookies:
            del request.cookies[session.COOKIE_NAME]

    @staticmethod
    def get_cookie_value(cookiename):
        """Get the value of a cookie from the bottle response headers"""

        headers = response.headerlist
        for h,v in headers:
            if h == 'Set-Cookie':
                cookie = SimpleCookie(v)
                if cookiename in cookie:
                    return cookie[cookiename].value

        return None

    def test_get_or_create_session(self):
        """The get_or_create_session procedure creates a new
        session if none is present or returns an existing one"""

        sessionid = session.get_or_create_session(self.db)

        self.assertIsNotNone(sessionid)

        # set sessionid cookie in request
        request.cookies[session.COOKIE_NAME] = sessionid
        # second call, should get session info from request cookie
        sessionid1 = session.get_or_create_session(self.db)

        self.assertEqual(sessionid, sessionid1)

        cookieval = self.get_cookie_value(session.COOKIE_NAME)
        self.assertEqual(sessionid, cookieval)

    def test_session_bad_cookie(self):
        """If the cookie we receive is not a valid session key, it
        should be ignored and a new session created"""

        # set sessionid cookie in request
        invalidkey = "InvalidSessionKey"
        request.cookies[session.COOKIE_NAME] = invalidkey

        sessionid = session.get_or_create_session(self.db)

        self.assertNotEqual(invalidkey, sessionid)

        cookieval = self.get_cookie_value(session.COOKIE_NAME)
        self.assertEqual(sessionid, cookieval)

    def test_cart(self):
        """We can add items to the shopping cart
        and retrieve them"""

        # first need to force the creation of a session and
        # add the cookie to the request
        sessionid = session.get_or_create_session(self.db)
        self.assertIsNotNone(sessionid)
        request.cookies[session.COOKIE_NAME] = sessionid

        # initial cart should be empty
        cart = session.get_cart_contents(self.db)
        self.assertEqual([], cart)

        # now add something to the cart
        for pname in ['Yellow Wool Jumper', 'Ocean Blue Shirt']:
            product =  self.products[pname]
            session.add_to_cart(self.db, product['id'], 1 )

        cart = session.get_cart_contents(self.db)
        self.assertEqual(2, len(cart))

        # check that all required fields are in the every cart entry
        for entry in cart:
            self.assertIn('id', entry)
            self.assertIn('name', entry)
            self.assertIn('quantity', entry)
            self.assertIn('cost', entry)



if __name__=='__main__':
    unittest.main()


0 0
Add a comment Improve this question Transcribed image text
Answer #1
from bottle import request, response
import uuid
import json
import model
from uuid import UUID

import dbschema

COOKIE_NAME = 'session'

def is_valid_uuid(new_str):
    """
    Check if uuid_to_test is a valid UUID.
    """
    try:
        new_value = uuid.UUID(new_str, version=4)
    except ValueError:
        return False

    return new_value.hex == new_str.replace('-', '')



def get_or_create_session(db):
    """Get the current sessionid either from a
    cookie in the current request or by creating a
    new session if none are present.

    If a new session is created, a cookie is set in the response.

    Returns the session key (string)
    """
    sessionid = ""

    sessionid = request.get_cookie(COOKIE_NAME)

    cur = db.cursor()
    row = cur.fetchone()
    if not sessionid or is_valid_uuid(sessionid) == False:
        sessionid = str(uuid.uuid4())
        cur = db.cursor()
        cur.execute("INSERT INTO sessions (sessionid) VALUES(?)", (sessionid,))
        db.commit()

        response.set_cookie(COOKIE_NAME, sessionid)
    return sessionid

listitem = []

def add_to_cart(db, itemid, quantity):
    """Add an item to the shopping cart"""
    #look for the product

    #Make JSon object as a dictionary

    session_key =  get_or_create_session(db)
    cur = db.cursor()
    cur.execute("SELECT sessionid FROM sessions WHERE sessionid=?", (session_key,))
    item = model.product_get(db, itemid)

    listitem.append({
        'id': itemid,
        'quantity': quantity,
        'name': item[1],
        'cost': item[5] * quantity
    })
    j_data = json.dumps(listitem)
    cur.execute("UPDATE sessions set data = ? WHERE sessionid = ?",(j_data, session_key))
    db.commit()


def get_cart_contents(db):
    """Return the contents of the shopping cart as
    a list of dictionaries:
    [{'id': <id>, 'quantity': <qty>, 'name': <name>, 'cost': <cost>}, ...]
    """
    key = get_or_create_session(db)
    cursor = db.cursor()
    cursor.execute("SELECT data FROM sessions WHERE sessionid = ?", (get_or_create_session(db),))
    result = cursor.fetchone()
    if result['data'] is None:
        return []


    return json.loads(result['data'])
Add a comment
Know the answer?
Add Answer to:
Solve the code below: CODE: """ Code for handling sessions in our web application """ from bottle import request, response import uuid import json import model import dbsche...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT