How to return data from a MySQL query in a Flask app?

前端 未结 1 1525
闹比i
闹比i 2021-01-05 16:36

I have the following code:

import flask as fk
import MySQLdb
import JSONEncoder


class SpecializedJSONEncoder(JSONEncoder):
    def default(o):
        if i         


        
相关标签:
1条回答
  • 2021-01-05 16:50

    Use Flask's built-in jsonify function, as it is already extended to work with dates:

    from Flask import jsonify
    
    @app.route('/temp')
    def temp():
        # Load database results
        # and then ...
        return jsonify(data=cur.fetchall())
    

    The data will be returned as an object with a single key (data) containing an array of rows (which will either be represented as arrays or objects depending on what fetchall returns rows as).

    If you need to serialize more types (as in your case, you are getting back date rather than datetime instances, you will need to override Flask's json_encoder property with a subclass of JSONEncoder that knows how to handle your types:

    class SpecializedJSONEncoder(JSONEncoder):
        def default(o):
            if isinstance(o, date):
                return date.strftime("%Y-%m-%d")
            else:
                super(SpecializedJSONEncoder, self).default(o)
    

    And then you can set it on your Flask instance:

    app.json_encoder = SpecializedJSONEncoder
    

    You will now be able to handle dates as well as datetimes.

    0 讨论(0)
提交回复
热议问题