Flask入门及登录应用
入门
安装
pip install 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\r\n\r\n") 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
登录
登录成功将跳转至 index 页面
登录成功之后才能访问,所以需要引入 session
# 在登录函数中添加 session
if user == 'qiu' and pwd == '123':
session['user'] = user
@app.route('/index')
def index():
user = session.get('user')
if not user:
return redirect('/login')
return render_template('index.html')
Django 中 session 的数据放在数据库,但是这里没有连接数据库,这里是放在加密的 cookie 中,但是只加 session 是报错的
RuntimeError: The session is unavailable because no secret key was set.
需要设置 secret key,相当于加密时的 “加盐”
from flask import Flask, render_template, request, redirect, session
app = Flask(__name__)
app.secret_key = 'dsadaf'
@app.route('/login', methods=['GET', 'POST'])
...