3

我正在使用Flask-restfuland开发一个 RESTful API Flask-jwt。当我使用@jwt_required()任何端点并发送包含 JSON 数据的请求时,我没有收到我指定的错误消息 JSON。如果我删除 JSON 数据,则请求会得到正确处理。

这是代码:

@jwt_required()
def put(self, user_id):
    user = UserModel.find_by_id(user_id)        
    if user is None:
        return {"message": "User not found!"}, 404

这是邮递员的请求:

PUT /user/2 HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/json
Authorization: JWT xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Cache-Control: no-cache

{
  "backdrop_image": "Sora"
}

和服务器日志:

2017-10-25 18:31:06,256 INFO sqlalchemy.engine.base.Engine (2, 1, 0)
2017-10-25 18:31:06,259 INFO sqlalchemy.engine.base.Engine ROLLBACK
127.0.0.1 - - [25/Oct/2017 18:31:06] "PUT /user/2 HTTP/1.1" 404 -

如果我删除 JSON:

PUT /user/2 HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/json
Authorization: JWT xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Cache-Control: no-cache

我得到了预期的回应:

{
    "message": "User not found!"
}

这是被调用的方法:

@classmethod
    def find_by_id(cls, _id):
        return cls.query.filter_by(id = _id).first()

更新

我发现我得到No handlers could be found for logger "flask_jwt"了第一个请求

4

1 回答 1

0

所以我以不同的可能组合运行了这个,这个问题无法复制。我在服务器文件下使用

from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from flask_restful import Api, Resource
from werkzeug.security import safe_str_cmp

class User(object):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id

users = [
    User(1, 'xyz', 'xyz'),
    User(2, 'user2', 'abcxyz'),
]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}

def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)

api = Api(app)

class HelloWorld(Resource):
    @jwt_required()
    def get(self, user_id):
        return {'hello': 'world'}

    @jwt_required()
    def put(self, user_id):
        user = None
        if user is None:
            return {"message": "User not found!"}, 404

api.add_resource(HelloWorld, '/<string:user_id>')


if __name__ == '__main__':
    app.run()

要求.txt

aniso8601==1.3.0
click==6.7
Flask==0.12.2
Flask-JWT==0.3.2
Flask-RESTful==0.3.6
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
PyJWT==1.4.2
python-dateutil==2.6.1
pytz==2017.2
six==1.11.0
Werkzeug==0.12.2

然后在 POSTMAN 中,无论是否发送 JSON,所有请求都有效

没有身体 没有身体

有身体 有身体

它可能与某些软件包版本问题有关。我建议你跑

pip install flask-jwt flask-restful --force --upgrade

获取最新版本并查看是否可以解决问题。如果没有,请尝试debug=True在您的app.run()

于 2017-11-03T06:51:48.713 回答