我正在尝试使用 flask_sqlalchemy 和 flask_jwt_extended,marshmallow 对 API jwt 进行身份验证,以验证输入数据登录路径以获取令牌:
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"
}