前言
web.py框架下面的用戶(hù)登錄功能實(shí)現(xiàn)比較簡(jiǎn)單一點(diǎn),只是針對(duì)sesson的判斷和瀏覽器cookie的處理 我這里只是針對(duì)實(shí)現(xiàn)登錄的功能,對(duì)于賬戶(hù)信息的存儲(chǔ)和密碼的加密都沒(méi)有做任何處理。
session和cookie的原理用戶(hù)訪問(wèn)網(wǎng)站某頁(yè)面,服務(wù)端會(huì)根據(jù)客戶(hù)端傳過(guò)來(lái)的cookie在本地尋找是否有對(duì)應(yīng)的session,如果有則保留上一次的狀態(tài)(如果cookie沒(méi)有過(guò)期),如果沒(méi)有馬上創(chuàng)建一個(gè),然后返回一個(gè)新數(shù)據(jù)給客戶(hù)端。然后跳轉(zhuǎn)到login頁(yè)面,進(jìn)行登錄操作,登錄完成,服務(wù)端會(huì)把cookie的自建參數(shù)傳遞給客戶(hù)端,客戶(hù)端完成cookie的重新創(chuàng)建。
對(duì)session和cookie的一些理解
注意:下面源代碼中涉及py腳本中顯示問(wèn)題,所以html的代碼都加了''轉(zhuǎn)義,如果要使用需要把轉(zhuǎn)義符刪除掉
源代碼
功能實(shí)現(xiàn)
實(shí)現(xiàn)用戶(hù)登錄,根據(jù)用戶(hù)的賬號(hào)和密碼進(jìn)行驗(yàn)證
實(shí)現(xiàn)用戶(hù)登錄和退出功能
實(shí)現(xiàn)已登錄用戶(hù)在多頁(yè)面之間跳轉(zhuǎn)
登錄模塊的源代碼
login.py
#!/usr/bin/env python # coding: utf-8 import web from web import form urls = ( '/','Index', '/test','Test', '/login','Login', '/logout','Logout', ) render = web.template.render('/opt/py/login') allowed = ( ('admin','123123'), ) web.config.debug = False app = web.application(urls, locals()) session = web.session.Session(app, web.session.DiskStore('sessions')) class Index: def GET(self): if session.get('logged_in',False): return '<h1>Login Success!!!</h1>testLogout' raise web.seeother('/login') class Login: def GET(self): return render.login() def POST(self): i = web.input() username = i.get('username') passwd = i.get('passwd') if (username,passwd) in allowed: session.logged_in = True web.setcookie('system_mangement', , 60) raise web.seeother('/') else: return '<h1>Login Error!!!</h1>Login' class Logout: def GET(self): session.logged_in = False raise web.seeother('/login') class Test: def GET(self): if session.get('logged_in',False): return '<h1> test login success!!!</h1>Logout' return '<h1>logout now</h1>Login' if __name__ == '__main__': app.run()
登錄模塊調(diào)用的模板
login.html
<html> <head> <title>Login Test</title> </head> <h1>Login</h1> <FORM method=POST> <table id='login'> <tr> <td>User: </td> <td><input type=text name='username'></td> </tr> <tr> <td>Password: </td> <td><input type='password' name=passwd></td> </tr> <tr> <td></td> <td><input type=submit></td> </tr> </table> </form> </html>
源代碼下載地址: github(保存在login分支里面)
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶(hù)發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。