码迷,mamicode.com
首页 > 数据库 > 详细

Flask连接数据库

时间:2020-07-28 22:47:17      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:span   manager   with   ctc   int   mit   post   root   callback   

     

 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连接数据库

标签:span   manager   with   ctc   int   mit   post   root   callback   

原文地址:https://www.cnblogs.com/Geirge-ye/p/13393836.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!