Using MySQL in Flask

前端 未结 8 786
忘掉有多难
忘掉有多难 2020-12-02 11:46

Can someone share example codes in Flask on how to access a MySQL DB? There have been documents showing how to connect to sqlite but not on MySQL.

Thank you very muc

8条回答
  •  抹茶落季
    2020-12-02 11:57

    #!/usr/bin/python
    from flask import Flask,jsonify,abort, make_response
    import MySQLdb
    
    app = Flask(__name__)
    
    db = MySQLdb.connect("localhost", "root", "yourDbPassWord", "DBname")
    
    @app.route('/api/v1.0/items', methods=['GET'])
    def get_items():
        curs = db.cursor()
        try:
            curs.execute("SELECT * FROM items")
            ...
    
        except:
            print "Error: unable to fetch items"
        return jsonify({"desired: " response})
    

提交回复
热议问题