flask 简单编写一个验证登录的案例

苦咖啡flask 2020-06-18

import base64
import random
import time
from flask import Flask, request

app = Flask(__name__)

users = {  # 模拟一个用户信息
    "Tom": ["123456"]
}


def gen_token(uid):  # 获取token模块
    token = base64.b64encode(":".join([str(uid), str(random.random()), str(time.time() + 7200)]))
    users[uid].append(token)
    print users
    return token


def verify_token(token):  # 验证token模块
    _token = base64.b64decode(token)
    if not users.get(_token.split(":")[0])[-1] == token:
        return -1
    if float(_token.split(":")[-1]) >= time.time():
        return 1
    else:
        return 0


@app.route("/login", methods=["post"])
def login():  # 登录模块
    print request.headers
    uid, pw = base64.b64decode(request.headers[‘Authorization‘].split(" ")[-1]).split(":")
    if users.get(uid)[0] == pw:
        return gen_token(uid)
    else:
        return "error"


@app.route("/test", methods=["post", ‘get‘])
def test():  # 测试的模块
    token = request.args.get("token")
    if verify_token(token) == 1:
        return "data"
    else:
        return "error"


if __name__ == "__main__":
    app.run(debug=True)  # 开发者模式
    # app.run()

在写一个请求的模块来请求:

# -*- coding: utf-8 -*-

import requests

r=requests.post("http://127.0.0.1:5000/login",auth=("Tom","123456"))#这里用auth,requests会把他变成请求头中的Authorization的值。
print r.text

token=r.text
r=requests.get("http://127.0.0.1:5000/test",params={"token":token})
print r.text

相关推荐

yyyxxxs / 0评论 2020-05-10