2017-08-14 46 views
0

我正在写一个Flask应用程序,其中我有一个服务生成一个JWT并将它传递到另一个使用requests.post()的服务,解码后'UTF-8'。JWT正在从str转换为字节requests.post()

在发送JWT时,我可以看到类型是'str'。然而,在其他服务进行json.loads(),我得到的是说

TypeError: the JSON object must be str, not 'bytes'

这里的错误是我的代码:

服务1:

@app.route('/') 
def index(): 
    token = jwt.encode({'message': 'Hello'}, app.config['SECRET_KEY']) 
    # After this statement I am able to verify the type is str and not bytes 
    token = token.decode('UTF-8') 
    headers = {'content-type': 'application/json'} 
    url = 'someUrl' 
    data = {"token": token} 
    data = json.dumps(data) 
    requests.post(url, data=data, headers=headers) 
    return 'Success' 

服务2:

@app.route('/', methods=['POST']) 
def index(): 
    data = json.loads(request.data) 
    return 'Success' 

即使类型转换为字符串,为什么会出现此错误?

编辑:我能够成功地通过传递标题来检索令牌。但我仍然想知道是什么导致了这个错误。

+0

尽量去除'标记= token.decode( 'UTF-8')' – pedrofb

+0

这给了我一 '不JSON序列化类型错误'。它需要在json.dumps之前解码为'UTF-8' –

+0

将'data = json.loads(request.data)'更改为'data = request.get_json()'可能是一种可行的解决方法。 – Fian

回答

-1

您可以将它作为JSON而不是数据发布,并让底层库为您处理它。

服务1个

@app.route('/') 
def index(): 
    token = jwt.encode({'message': 'Hello'}, app.config['SECRET_KEY']).decode('UTF-8') 
    url = 'someUrl' 
    data = {"token": token} 
    requests.post(url, json=data) 
    return 'Success' 

服务2

data = request.get_json()