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 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()
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'])
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...