简体   繁体   中英

Flask, how to jsonify ONLY when return to browser

I try to build an RESTful api server with Flask, and create some functions that can return JSON format data to browser.

Now I hope to make the code more re-usable, for example:

@simple_page.route('/raw_data')
def raw_data():
    # to json
    pass


@simple_page.route('/score')
def score():
    data = raw_data()
    # some calculation & return the score (to json)
    pass

If there any way in Flask that the function raw_data() returns json format result if and only if the result will be sent back to browser? (Something like @cherrypy.tools.json_out() does in cherrypy)

Thanks in advance.

Factor out producing the raw_data() into a separate function, reused by both routes:

def _produce_raw_data():
    return raw_data

@simple_page.route('/raw_data')
def raw_data():
    return jsonify(_produce_raw_data())


@simple_page.route('/score')
def score():
    data = _produce_raw_data()
    # some calculation & return the score (to json)
    return jsonify(calculation_results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM