These two days for a project written in Bottle+mongodb with the login function, but how can not get to save the cookie, the document to give us the code snippet to manipulate cookies:
@route ('/login ') def login (): username = Request. Forms. Get (' username ') password = Request. Forms. Get (' Passwor d ') if check_user_credentials (username, password): response. Set_cookie ("Account", username, secret= ' Some-secret-key ') return "Welcome%s! Logged in. "% username else: return" Login failed. "@route ('/restricted ') def restricted_area (): Username = Request. Get_cookie ("account", secret= ' Some-secret-key ') if username: return "Hello%s.welcome back" . "% username
Although not documented, there is a way to manipulate cookies:
From bottle import request, Response@route ('/login ', method= "POST") def login (): user = Request. post[' user '] passwd = Request. post[' passwd '] if Check_user_right (USER,PASSWD): response. cookies[' account ' = user else: pass@route ('/admin ') def admin (): user = Request. cookies[' user '] if User: Pass
But no matter how I do it, I can't get a cookie. Best of all. But one of my handling article ClickThrough rate reminds me, the code is as follows:
@route ('/archrives/:aid#\d+# ') def article_show (aid): db = Dbconn. Conndb () artid = Int (aid) # get client IP remoteip = request.environ.get (' remote_addr ') Artcookie = remoteip+ ' IP ' +aid print request. Cookies.keys () # Determines if the cookie exists if Artcookie in request. Cookies.keys (): # exists to update the effective time response. Cookies[artcookie] = True response. cookies[artcookie][' max-age ' = $ Else: # does not exist update article views db.posts.update ({"id": ArtID}, {"$inc": {" Views ": 1}}) # and set Cookie response. Cookies[artcookie] = True response. cookies[artcookie][' max-age ' = template[' posts '] = Getartlist ({"id": ArtID}) Template.update ( SetTempVar ()) return template (' article.html ', template)
This is where the cookie is normally obtained, and the code does not make any difference. The only difference is that the user authentication is a jump page. So I help:
From bottle import responsehelp (Response.set_cookie)
The result of help there are two parameters one is path, and domain:
:p Aram Domain:the Domain that's allowed to read the cookie. (default:current domain) :p Aram Path:limits The cookie to a given path (default:current path)
Obviously bottle cookies are only readable by default in the current path, so the other pages read to the cookie our code must be changed to the following:
From bottle import request, Response@route ('/login ', method= "POST") def login (): user = Request. post[' user '] passwd = Request. post[' passwd '] if Check_user_right (USER,PASSWD): response. cookies[' account ' = user response. cookies[' account ' [' path '] = '/admin ' else: pass@route ('/admin ') def admin (): user = Request. cookies[' user ']
This allows us to access the cookies we set under other paths.