Get json from one view by calling it from another view

后端 未结 3 1834
闹比i
闹比i 2020-12-21 08:14

I have a view that returns JSON data. I want to get that data from another view as well, so I tried calling the JSON view from it. However, a Response was ret

3条回答
  •  醉话见心
    2020-12-21 09:13

    Your view has return jsonify(...) at the end of it. jsonify returns a Response with JSON data, it doesn't return the raw data directly. You could re-parse the JSON data from the response object, or you could separate the function that generates data from the view that returns a response.

    from flask import json
    r = get_promoter(id)
    data = json.loads(r.data, encoding=r.charset))
    
    # or separate the data from the view
    def get_promoter(id):
        return json.dumps(...)
    
    @app.route(...)
    def promoter(id):
        return jsonify(**get_promoter(id))
    
    @app.route(...)
    def other_view():
        promoter = get_promoter(400617)
        ...
    

    Other views may return other types of data. jsonify happens to return a Response object, but other valid return values are strings (from render_template, for example) and tuples. Any of these will be turned into Responses when Flask is handling a request, but when just calling the view functions they return whatever they return, which might happen to be a Response.

提交回复
热议问题