Flask-JWT 小坑:No JSON object could be decoded;AttributeError: 'NoneType' object has no attribute 'get

使用官方的 “QuickStart” 时,

Flask-JWT — Flask-JWT 0.3.2 documentation https://pythonhosted.org/Flask-JWT/


出现了两个小坑:

1) 用命令行:

H:\>curl -i -X POST -H "Content-Type: application/json" -d '{"username":"joe","password":"pass"}' http://127.0.0.1:5000/auth
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html
Content-Length: 177
Server: Werkzeug/0.11.11 Python/2.7.11
Date: Mon, 21 Nov 2016 01:01:07 GMT



400 Bad Request

Bad Request


Failed to decode JSON object: No JSON object could be decoded




2) 用Firefox 插件“RESTClient”时,也报错:

Flask-JWT 小坑:No JSON object could be decoded;AttributeError: 'NoneType' object has no attribute 'get_第1张图片

  File "C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\flask_jwt\__init__.py", line 117, in _default_auth_request_handler
    username = data.get(current_app.config.get('JWT_AUTH_USERNAME_KEY'), None)
AttributeError: 'NoneType' object has no attribute 'get'


解决:

1)命令行:

window CMD用来 post是有问题的,在cygwin (类 Linux)下使用 curl 就OK了

[~]$ curl -i -X POST -H "Content-Type: application/json" -d '{"username":"joe","password":"pass"}' http://127.0.0.1:5000/auth
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   229  100   193  100    36    193     36  0:00:01 --:--:--  0:00:01  188kHTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 193
Server: Werkzeug/0.11.11 Python/2.7.11
Date: Fri, 18 Nov 2016 13:18:24 GMT


{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6MSwiaWF0IjoxNDc5NDc1MTA0LCJuYmYiOjE0Nzk0NzUxMDQsImV4cCI6MTQ3OTQ3NTQwNH0.jbt_P-Bt-NhtvhbqMzb15YbiAr4vbE1sObCsfKCVvlM"
}


2) 插件:

需要手动加上 Content-Type的头,也OK了

Header Name Header Value
Content-Type application/json

Body:

{"username":"joe","password":"pass"}


如果 Flask-Login 和 Flask-JWT 一起使用


# test method
@app.route('/test')
@login_required
@jwt_required()
def test():
    return "yes , you are allowed"
 

效果是:同时生效!

json访问时,也会验证 session是否已经登录

网页访问时,会禁止!因为header 里没有带 Authorization


https://code.csdn.net/Kevin_QQ/flask_jwt_flask_login


JWT如何注销logout

There is no vanilla way to invalidate tokens on the server side. On the client side, a /logout should simply delete the token.

To implement an invalidate on the server side, you'll need to use a short token expiration followed by a refresh token feature (https://stackoverflow.com/questions/3487991/why-does-oauth-v2-have-both-access-and-refresh-tokens and #29)


Other practice:

User 设置个字段:valid_token?


你可能感兴趣的:(Python,Flask,JWT,Python,Flask)