简体   繁体   English

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

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

I am new to python/flask and I am working on one to many relationships.我是 python/flask 的新手,我正在处理一对多的关系。 I tried some solutions but didn't work.我尝试了一些解决方案,但没有奏效。 My problem here is in the "/add_about" route I want to get the user_id that created this post and be able to see that reflected in the database.我的问题出在“/add_about”路由中,我想获取创建此帖子的 user_id 并能够看到数据库中反映的内容。

Here is my code:这是我的代码:

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

Here are the db models:以下是数据库模型:

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')

Here are the user routes:以下是用户路线:

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

here is a screenshot from my db admin:这是我的数据库管理员的屏幕截图: 在此处输入图像描述

When you register your jwt token on login, you register the token with the users email.当您在登录时注册 jwt 令牌时,您向用户 email 注册令牌。

user route用户路线

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

So 2 possible solutions:所以2个可能的解决方案:

  1. You can do a db lookup in the user table on email address and return the userId.您可以在 email 地址的用户表中进行 db 查找并返回 userId。
@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. Or you can register the user.id as the jwt token或者您可以将 user.id 注册为 jwt 令牌
access_token = create_access_token(identity=test.id)

Then user_id = get_jwt_identity() should then return the user.id from the token然后user_id = get_jwt_identity()应该从令牌中返回 user.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM