flask 添加用户认证API , python 客户端用户认证

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

python 复制代码
### web 访问授权验证 
@bp.route("/author", methods=("GET", "POST"))
def author():
    """author a user is registered or not"""

    ret = -1

    if 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"

python 复制代码
import requests
import json
from typing import Tuple

import getpass

def author(username: str, password: str) -> Tuple[bool, str]:
    # 将此URL替换为您要登录的网站的URL
    url = "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 验证正确:

bash 复制代码
请输入用户名: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 验证失败:

bash 复制代码
请输入用户名: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
相关推荐
蛋仔聊测试7 分钟前
Playwright 中 Page 对象的常用方法详解
python
前端付豪19 分钟前
17、自动化才是正义:用 Python 接管你的日常琐事
后端·python
jioulongzi20 分钟前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
我是一只代码狗23 分钟前
springboot中使用线程池
java·spring boot·后端
PanZonghui39 分钟前
Centos项目部署之安装数据库MySQL8
linux·后端·mysql
Victor35642 分钟前
MySQL(119)如何加密存储敏感数据?
后端
破无差1 小时前
python实现简单的地图绘制与标记20250705
python
用户3966144687191 小时前
TypeScript 系统入门到项目实战-慕课网
后端
guojl1 小时前
Dubbo SPI原理与设计精要
后端