入门
安装
pip install -i http://pypi.douban.com/simple --trusted-host pypi.douban.com flask
wsgi
-
werkzeug 示例
from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response('Hello World!') if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 4000, hello)
-
wsgiref 示例
from wsgiref.simple_server import make_server def runserver(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ] if __name__ == '__main__': # obj = WSGIHandler() httpd = make_server('', 8000, runserver) httpd.serve_forever()
-
本质的本质
import socket def handle_request(client): buf = client.recv(1024) client.send("HTTP/1.1 200 OK ") client.send("Hello, Seven") def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost',8000)) sock.listen(5) while True: connection, address = sock.accept() handle_request(connection) connection.close() if __name__ == '__main__': main()
基本使用
from flask import Flask
# 实例化 Flask 对象
app = Flask(__name__)
# 将 '/' 和 函数index的对应关系添加到路由中
@app.route('/') # 1. v = app.route('/') 2. v(index)
def index():
return 'Hello World!'
if __name__ == '__main__':
# 监听用户请求
# 如果有用户到来,执行app的__call__方法
app.run()
应用demo
登录
登录成功将跳转至百度页面
信息显示
显示详细信息
登录成功之后才能访问,所以需要引入 session
# 在登录函数中添加 session
if user == 'qiu' and pwd == '123':
session['user_info'] = user
@app.route('/index', methods=['GET'])
def index():
user = session.get('user_info')
if not user:
return redirect('/login')
return render_template('index.html', user_dict=USERS)
反向生成URL
from flask import Flask, render_template, request, redirect, session, url_for
@app.route('/index', methods=['GET'])
def index():
user = session.get('user_info')
if not user:
url =url_for('n1')
return redirect(url)
return render_template('index.html', user_dict=USERS)
@app.route('/login', methods=['GET', 'POST'], endpoint='n1')
def login():
if request.method == 'GET':
return render_template('login.html')
....
应用demo总结
- 示例
- 装饰器:用户认证
- 装饰器
- 多个装饰器
- 反向查找的名称不允许重复:endpoint