flask的基本使用 token插件(二)

一、安装flask-jwt-extended

安装flask-jwt-extend得时候 会自动安装一个pyjwt得库。pyjwt可以直接使用来生成JWT和验证。但是在flask中,可以通过Flask-JWT-Extended来实现JWT能,因为他封装了使用方式,以及一些属性和装饰器,用起来更加方便

python 复制代码
pip install flask-jwt-extended

二、基本使用

1.简介

1.1 create_access_token()

create_access_token 函数用来生成实际的 JWT token

1.2 @jwt_required()

@jew_required 装饰器可以用来保护路由

1.3 get_jwt_identity()

get_jwt_identity()函数用来保护视图里面获取用户的身份信息。

2.初始化项目

创建python包 名称为api.

编辑api内 "init.py" 文件

python 复制代码
from flask import  Flask,blueprints
from flask_jwt_extended import JWTManager
from .views.home import blue_home


#创建flask 实例的函数
def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "super-secret"
    app.register_blueprint(blue_home)
    return  app

# 初始化jwt的函数
def create_jwt(app):
    jwt = JWTManager()
    jwt.init_app(app)
    return jwt

3.创建token

编写main.py

python 复制代码
from flask import request,jsonify
from api import create_app,create_jwt
from flask_jwt_extended import create_access_token

app = create_app()
jwt = create_jwt(app)


@app.route('/login',methods=["POST"])
def index():
    username = request.form.get("username")
    password = request.form.get("password")
    if username == "admin" and password == "admin":
        # 当用户登陆成功,创建token并返回
        access_token = create_access_token(identity="admin")
        return  jsonify(access_token)
    else:
        return "用户名或者密码错误!!!"


if __name__ == "__main__":
    app.run(debug=True,host="0.0.0.0")

请求127.0.0.1:5000/login得到访问token

json 复制代码
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTcwNzAzNTg5MSwianRpIjoiNGJjNjY4NDctZTQxYy00ZjdmLWIxZWYtOTNjYjJmMTBjYzFmIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6ImFkbWluIiwibmJmIjoxNzA3MDM1ODkxLCJjc3JmIjoiY2VlZGNkZmMtNDIwMS00NmE4LWEzYTItZDRhNTliMDIwYjQ5IiwiZXhwIjoxNzA3MDM2NzkxfQ.SzMKMthP_xQ02QwgFwSu3Refc2oz1EseFgntPzS5U0g"

4.保护视图

创建一个视图函数 views/home.py

python 复制代码
from flask import  Blueprint
from flask_jwt_extended import jwt_required,get_jwt_identity

blue_home = Blueprint('home',__name__)

@blue_home.route('/home')
# 校验token 的函数
@jwt_required()
def home():
    # 可以获取token中的用户
    print(get_jwt_identity())
    return "<h1>home页面<h1>"

当用户不带token访问的时候,会报错

python 复制代码
{
  "msg": "Missing Authorization Header"
}

客户端携带token认证格式

c 复制代码
import requests,json
header = {
    "Authorization": "Bearer eyJhbGciOi.................."
}
res = requests.get("http://127.0.0.1:5000/home",headers=header)

参考连接:https://juejin.cn/post/7234450312726691898#heading-1

相关推荐
9ilk19 小时前
【C++】 --- 哈希
c++·后端·算法·哈希算法
愚戏师19 小时前
Python3 多线程
linux·运维·服务器·python
MC丶科19 小时前
Spring Boot + Elasticsearch 实现全文搜索功能(商品搜索)!让搜索快如闪电
spring boot·后端·elasticsearch·软考高级·软考架构师
子午19 小时前
【食物识别系统】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积网络+resnet50算法
人工智能·python·深度学习
曾经的三心草19 小时前
基于正倒排索引的Java文档搜索引擎2-实现Index类
java·python·搜索引擎
疏狂难除19 小时前
尝试rust与python的混合编程(二)
数据库·python·rust
9***P33420 小时前
Rust在网络中的Rocket
开发语言·后端·rust
Wzx19801220 小时前
go聊天室
开发语言·后端·golang
子午20 小时前
【蘑菇识别系统】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积网络+resnet50算法
人工智能·python·深度学习
Mr_Xuhhh20 小时前
pytest -- 指定⽤例执⾏顺序
开发语言·python·pytest