Flask连接数据库
Posted geirge-ye
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask连接数据库相关的知识,希望对你有一定的参考价值。
1 from flask import Flask,jsonify,request 2 import json 3 from flask_cors import * 4 import pymysql 5 6 app = Flask(__name__) 7 8 import contextlib 9 10 @contextlib.contextmanager 11 12 def mysql(host=‘192.168.0.122‘, port=3306, user=‘root‘, passwd=‘我的数据库密码‘, db=‘text1‘,charset=‘utf8‘): 13 conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset) 14 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 15 try: 16 yield cursor 17 final 18 conn.commit() 19 19 cursor.close() 20 conn.close() 21 22 @app.route(‘/aaa‘, methods=[‘GET‘,‘POST‘]) 23 @cross_origin() 24 def aaa(): 25 data= request.args.get("data")#获取前台json数据 26 temp = json.loads(data)#将json转为字典 27 id=temp[‘id‘]#获取相应的值 28 with mysql() as cursor: 29 print(cursor) 30 row_count = cursor.execute("select * from users where id=%s", (id)) 31 row_1 = cursor.fetchone() 32 return "successCallback"+"("+json.dumps(row_1)+")" 33 34 conn.commit() 35 cursor.close() 36 conn.close() 37 38 if __name__ == "__main__": 39 app.run( 40 host = ‘0.0.0.0‘, 41 port = 7777, 42 debug = True 43 )
以上是关于Flask连接数据库的主要内容,如果未能解决你的问题,请参考以下文章