- 1.基础使用
import json
from flask import Flask,request,jsonify,redirect
app = Flask(__name__)
@app.before_request # 请求前置,每次访问前都会执行这个函数,一般没有返回值,如果有返回值,不会继续往下走
def auth():
print(123)
# return "无权访问"
@app.route('/home',methods=['GET','POST'])
def home():
# URL中传递的参数
print(request.args)
print(request.args.get("name"))
# print(request.args.getlist("name")) # 多个参数值一样的时候,这样取
# POST参数
# print(request.form) # form格式
# print(request.json) # json格式
# print(request.headers) # 请求头数据
# print(request.cookies) # cookies数据
# print(request.files) # 文件
# return "home"
# return json.dumps({"status":"true","data":123})
# return jsonify({"status":"true","data":123})
return redirect("http:www.baidu.com")
@app.route('/login')
def login():
return "login"
if __name__ == '__main__':
app.run(host='127.0.0.1',port=8009)
- 2.基于登录的token验证示例
import json
import os
import uuid
from flask import Flask,request,jsonify,redirect
app = Flask(__name__)
@app.before_request
def auth():
if request.path == '/login':
return
token = request.args.get('token')
name_list = os.listdir('token')
for name in name_list:
file_path = os.path.join(token,name)
with open(file_path,"r",encoding='utf8') as f:
uid = f.read().strip()
if token == uid:
return
return jsonify({"status": False, "data": "无效token"})
@app.route('/home',methods=['GET','POST'])
def home():
pass
@app.route('/login',methods=['POST'])
def login():
mobile = request.args.get('mobile')
pwd = request.args.get('pwd')
# 登录数据,可以基于文件或者数据库
with open('userinfo.json',mode='r',encoding='utf8') as f:
user_dict = json.load(f)
info = user_dict.get(mobile)
print(type(pwd),pwd)
print(info)
print(type(info.get('pwd')),info.get('pwd'))
if not info:
return jsonify({"status": False, "data": "用户不存在"})
if int(pwd) != info.get('pwd'):
return jsonify({"status": False, "data": "密码错误"})
uid = str(uuid.uuid4())
with open(os.path.join("token",f'{mobile}.txt'),"w",encoding='utf8') as f:
f.write(uid)
return jsonify({"status": False, "data": uid})
if __name__ == '__main__':
app.run(host='127.0.0.1',port=8009)
标签:__,web,return,入门,flask,app,request,print,name
From: https://www.cnblogs.com/xwltest/p/18427984