如何在 flask-jwt-extended 中获取当前用户(id)?

How can I get the current user(id) in flask-jwt-extended?

我是 python/flask 的新手,我正在处理一对多关系。我尝试了一些解决方案但没有奏效。我的问题是在“/add_about”路由中,我想获取创建此 post 的 user_id 并能够在数据库中看到它。

这是我的代码:

from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, current_user, get_current_user, get_jwt_identity
from app import db
from models.about import About, AboutSchema
from models.users import User


about = Blueprint('about', __name__)

about_schema = AboutSchema()
abouts_schema = AboutSchema(many=True)


@about.route('/')
def hello():
    return "Oh LA LA LA LA !!!!!!"


# Get all abouts:
@about.route('/all', methods=['GET'])
def abouts():
    abouts_list = About.query.all()
    result = abouts_schema.dump(abouts_list)
    return jsonify(result)


@about.route('/add_about', methods=['POST'])
@jwt_required
def add_about():
    description = request.form['description']
    user_id = get_jwt_identity()        #I tried using "current_user" an "get_current_user"
    new_about = About(description=description, user=user_id)

    db.session.add(new_about)
    db.session.commit()
    return jsonify(message="You added a bio"), 201

以下是数据库模型:

from sqlalchemy import Column, Integer, String, FLOAT
from app import db, ma


database models:
class User(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)
    email = Column(String, unique=True)
    password = Column(String)

    about = db.relationship('About', backref='user', lazy='dynamic')


class About(db.Model):
    __tablename__ = 'abouts'
    about_id = Column(Integer, primary_key=True)
    description = Column(String(1000))

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))


class UserSchema(ma.Schema):
    class Meta:
        fields = ('id', 'first_name', 'last_name', 'email', 'password')


class AboutSchema(ma.Schema):
    class Meta:
        fields = ('about_id', 'description')

用户路线如下:

from flask import Blueprint, jsonify, request
from app import db
# from models.users import User, UserSchema
from models.users import User, UserSchema
from flask_jwt_extended import JWTManager, jwt_required, create_access_token


users = Blueprint('user', __name__)


user_schema = UserSchema()
users_schema = UserSchema(many=True)


@users.route('/register', methods=['POST'])
def register():
    email = request.form['email']
    test = User.query.filter_by(email=email).first()
    if test:
        return jsonify(messgae="that email already exists")
    else:
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        password = request.form['password']
        user = User(first_name=first_name, last_name=last_name, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        return jsonify(messgae="User created successfully"), 201


@users.route('/login', methods=['POST'])
def login():
    if request.is_json:
        email = request.json['email']
        password = request.json['password']
    else:
        email = request.form['email']
        password = request.form['password']

    test = User.query.filter_by(email=email, password=password).first()
    if test:
        access_token = create_access_token(identity=email)
        return jsonify(message="Login succeeded!", access_token=access_token), 200
    else:
        return jsonify(message="Bad email or password"), 401

这是我的数据库管理员的截图:

当您在登录时注册您的 jwt 令牌时,您使用用户的电子邮件注册令牌。

用户路线

test = User.query.filter_by(email=email, password=password).first()
    if test:
        access_token = create_access_token(identity=email) # identity = email
        return jsonify(message="Login succeeded!", access_token=access_token), 200
    else:
        return jsonify(message="Bad email or password"), 401

所以有 2 种可能的解决方案:

  1. 您可以在用户 table 的电子邮件地址和 return 用户 ID 中进行数据库查找。
@about.route('/add_about', methods=['POST'])
@jwt_required
def add_about():
    description = request.form['description']
    user = User.query.filter_by(email=get_jwt_identity()).first() # Filter DB by token (email)
    new_about = About(description=description, user=user)
  1. 或者您可以将 user.id 注册为 jwt 令牌
access_token = create_access_token(identity=test.id)

然后 user_id = get_jwt_identity() 应该 return 来自令牌的 user.id