Flask连接数据库
时间:2021-07-01 10:21:17
帮助过:33人阅读
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连接数据库
标签:span manager with ctc int mit post root callback