flask 添加用户认证API , python 客户端用户认证
flask blog 演示项目
Documentation = https://flask.palletsprojects.com/tutorial/
中文Documentation = https://flask.net.cn/
源码 https://github.com/pallets/flask/tree/main/examples/tutorial
修改 auth.py 添加用户认证API
### web 访问授权验证
@bp.route("/author", methods=("GET", "POST"))
def author():"""author a user is registered or not"""ret = -1if request.method == "POST":username = request.form["username"]password = request.form["password"]db = get_db()user = db.execute("SELECT * FROM user WHERE username = ?", (username,)).fetchone()if user is None:ret = 1 # "Incorrect username."elif not check_password_hash(user["password"], password):ret = 2 #"Incorrect password."if ret is -1:ret = 0 # "author OK"jsonRet={"status":ret,"value":ret}return jsonRet
client.py 访问 网站 获取认证结果
其中 url = “http://127.0.0.1:5000/auth/author” 替换为实际的 flask服务器地址
我这里在本机演示,所以是"http://127.0.0.1:5000/auth/author"
import requests
import json
from typing import Tupleimport getpassdef author(username: str, password: str) -> Tuple[bool, str]:# 将此URL替换为您要登录的网站的URLurl = "http://127.0.0.1:5000/auth/author"payload = {"username": username,"password": password}response :requests.Response = requests.post(url, data=payload, headers={"Referer": url}) # 模拟浏览器登陆过程print(f"response.url: {response.url}") print(f"response.content: {response.content}")print(f"response.status_code: {response.status_code}")json_data = json.loads(response.content)status = json_data["status"]value = json_data["value"]print(f"status : {status}")print(f"value : {value}")if status == 0:return {True,"author OK"}else:return {False,"author Error"}username = input("请输入用户名:")
# password = input("请输入密码:")
password = getpass.getpass("请输入密码:")ret,message = author(username, password)
print(f"{ret} {message}")
测试
我这网站用户提前添加
用户名 wmx
密码 123
测试,运行client.py
wmx 123 验证正确:
请输入用户名:wmx
请输入密码:
response.url: http://127.0.0.1:5000/auth/author
response.content: b'{\n "status": 0,\n "value": 0\n}\n'
response.status_code: 200
status : 0
value : 0
True author OK
ad ad 验证失败:
请输入用户名:ad
请输入密码:
http://127.0.0.1:5000/auth/author
b'{\n "status": 1,\n "value": 1\n}\n'
200
status : 1
value : 1
False author Error