mercredi 28 avril 2021

Setting cookie to random integer: TypeError: Excpected bytes

As the title suggests, I am attempting to set a cookie with a random integer generated with "random.randint(1,5)" and got a TypeError: Expected bytes. I found a method online that almost fixed the problem by changing "resp.set_cookie('ranNum', randomNumber, 3600)" to "resp.set_cookie('ranNum', json.dumps(randomNumber), 3600)". With this method, the cookie would be saved as a random number, but would be altered each time the page was refreshed. Here's how it would change with 2 being the example number and "->" being a page refresh:

2 -> "2" -> ""2"" -> ""\"2\""" -> ""\"\\\"2\\\"\"""

Why are quotation marks and backslashes being added to the integer with each refresh?

    if ("firstName" in request.args) or (request.cookies.get('userFName') is not None):
        
        if request.args.get('firstName') is not None:
            firstName = request.args["firstName"]
        elif request.cookies.get('userFName') is not None:
            firstName = request.cookies.get('userFName')
        if request.args.get('lastName') is not None:
            lastName = request.args["lastName"]
        elif request.cookies.get('userLName') is not None:
            lastName = request.cookies.get('userLName')
        
        if request.cookies.get('ranNum') is None:
            randomNumber = random.randint(1, 5)
        elif request.cookies.get('ranNum') is not None:
            randomNumber = request.cookies.get('ranNum')
        
        resp = make_response(render_template('assignment10_2.html', firstName=firstName, lastName=lastName, randomNumber=randomNumber))
        
        resp.set_cookie('userFName', firstName, 3600)
        resp.set_cookie('userLName', lastName, 3600)
        resp.set_cookie('ranNum', randomNumber, 3600)
        
        return resp



Aucun commentaire:

Enregistrer un commentaire