Return JSON response from Flask view

前端 未结 15 2589
时光取名叫无心
时光取名叫无心 2020-11-21 05:11

I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I r

15条回答
  •  借酒劲吻你
    2020-11-21 06:04

    I use a decorator to return the result of jsonfiy. I think it is more readable when a view has multiple returns. This does not support returning a tuple like content, status, but I handle returning error statuses with app.errorhandler instead.

    import functools
    from flask import jsonify
    
    def return_json(f):
        @functools.wraps(f)
        def inner(**kwargs):
            return jsonify(f(**kwargs))
    
        return inner
    
    @app.route('/test/')
    @return_json
    def test(arg):
        if arg == 'list':
            return [1, 2, 3]
        elif arg == 'dict':
            return {'a': 1, 'b': 2}
        elif arg == 'bool':
            return True
        return 'none of them'
    

提交回复
热议问题