赞
踩
Sanic 是一个和类Flask 的基于Python3.5+的web框架。
这个框架只支持Python3.5及已上版本,具体的介绍请自行百度,比我写的详细多了。
Sanic框架很轻量级,但是模块还是很丰富的。但是,现在Sanic框架的学习资源还比较少,直接拿来做生产还是需要一定勇气的。
# 导入权限验证模块
from sanic_auth import Auth, User
from sanic import Sanic, response
from sanic.response import text, json
import pymysql
sanic_auth 这个模块需要安装:
pip install --upgrade Sanic-Auth
from sanic_auth import Auth, User from sanic import Sanic, response from sanic.response import text, json import pymysql app = Sanic(__name__) app.config.AUTH_LOGIN_ENDPOINT = 'login' auth = Auth(app) db = pymysql.connect(host='localhost', user='username', passwd='password', database='database_name', charset="utf8") # session字典 session = {} # 存入session @app.middleware('request') async def add_session(request): request['session'] = session auth = Auth(app) # 定义登录函数 @app.route('/login', methods=['GET', 'POST']) async def login(request): message = '' if request.method == 'POST': cursor = db.cursor() username = request.form.get('username') password = request.form.get('password') sql = "SELECT userid, password FROM database_name.user WHERE username='" + username + "'" try: cursor.execute(sql) results = cursor.fetchone() if password == results[1]: user = User(id=results[0], name=username) auth.login_user(request, user) return response.redirect('/profile') except: return text('帐号或密码错误,回去吧!') elif request.method == 'GET': return await response.file('./login.html') # 调用内置的登出函数,清除session @app.route('/logout') @auth.login_required async def logout(request): auth.logout_user(request) return response.redirect('/login') @app.route('/profile') @auth.login_required(user_keyword='user') async def profile(request, user): return response.json({'user': user}) if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。