flask-jwt-extended TypeError: Object of type 'function' is not JSON serializable

flask-jwt-extended TypeError: Object of type 'function' is not JSON serializable

我正在尝试使用 flask_sqlalchemy 和 flask_jwt_extended 棉花糖对烧瓶进行 API jwt 验证以验证输入数据 获取token的登录路径:

from flask import Flask,request,jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from models import Book, Publisher, User
from crud import session
from config import DATABASE_URL
from marshmallow import Schema, fields, validates, ValidationError
from marshmallow.validate import Length, Range
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    get_jwt_identity
)
import os
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = '1234'
jwt = JWTManager(app)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#init db
db = SQLAlchemy(app)
#init ma
ma = Marshmallow(app)
@app.route('/login', methods=['POST'])
def login():
  if not request.is_json:
    return jsonify({"msg": "Missing JSON in request"}), 400
  username = request.json['username']
  password = request.json['password']
  if not username:
    return jsonify({"msg": "Missing username"}), 400
  if not password:
    return jsonify({"msg": "Missing password"}), 400
  if not db.session.query(User).filter(User.username == username, User.password == password).first():
    return jsonify({"msg": "Wrong username or password"}), 401
  access_token = create_access_token(identity=username)
  return jsonify(access_token=create_access_token), 200
#protected route 
@app.route('/book', methods=['POST'])
@jwt_required
def add_book():
  id = request.json['id']
  title = request.json['title']
  author = request.json['author']
  publisher_id = request.json['publisher_id']
  price = request.json['price']
  pages = request.json['pages']
  published = request.json['published']
  errors = create_book_schema.validate(request.get_json())
  if errors:
    return jsonify(msg=errors), 400
  new_book = Book(id=id,title=title,author=author,publisher_id=publisher_id,price=price,pages=pages,published=published)
  db.session.add(new_book)
  db.session.commit()
  return jsonify(msg='book successfully created', book_id=new_book.id), 200

当我通过邮递员在“/login”路由上发送 json 输入以获取令牌时,我收到了这个错误 return :

TypeError: Object of type 'function' is not JSON serializable

我做错了什么?感谢

编辑 这里的输入 json 与我的数据库中的相同

{
    "username": "linh",
    "password": "123"
}

您需要 return 一个可序列化对象才能 jsonify 工作:

return jsonify(dict(access_token=access_token)), 200

您已经在变量中定义了 access_token,您可以在字典中 return 它。