flask-jwt-extended TypeError:“函数”类型的对象不是 JSON 可序列化的
Posted
技术标签:
【中文标题】flask-jwt-extended TypeError:“函数”类型的对象不是 JSON 可序列化的【英文标题】:flask-jwt-extended TypeError: Object of type 'function' is not JSON serializable 【发布时间】:2019-10-27 17:28:36 【问题描述】:我正在尝试使用 flask_sqlalchemy 和 flask_jwt_extended,marshmallow 对烧瓶进行 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 输入以获取令牌时,我收到此错误返回:
TypeError:“函数”类型的对象不是 JSON 可序列化的
我做错了什么?谢谢
编辑 这里输入的json和我的数据库一样
"username": "linh",
"password": "123"
【问题讨论】:
【参考方案1】:您需要返回一个可序列化的对象,jsonify
才能工作:
return jsonify(dict(access_token=access_token)), 200
你已经在一个变量中定义了你的access_token
,你可以在字典中返回它。
【讨论】:
以上是关于flask-jwt-extended TypeError:“函数”类型的对象不是 JSON 可序列化的的主要内容,如果未能解决你的问题,请参考以下文章
get_jwt_identity() 在 Flask-JWT-Extended 中返回 None
为 flask-jwt-extended 获取其他用户 jti
使用 flask-jwt-extended + ariadne (graphql) + react 设置身份验证/授权
使用flask-jwt-extended回调与flask-restful和create_app