tornado 数据库
tornado+pymysql数据库操作
1 import tornado.web 2 import tornado.ioloop 3 import tornado.options 4 import json 5 import os 6 import pymysql 7 8 tornado.options.define('port',type=int,default=8005,help='服务器端口') 9 10 db=pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='mysql123',db='itcast') 11 cursor=db.cursor() 12 13 class IndexHandler(tornado.web.RequestHandler): 14 def get(self): 15 uid=self.get_argument('uid') 16 sql='select ui_name,ui_mobile,hi_name,hi_address,hi_price from it_user_info inner join it_house_info on ui_user_id=hi_user_id where ui_user_id=%s' 17 print(sql) 18 try: 19 cursor.executemany(sql,[(uid,)]) #防止SQL注入 20 data=cursor.fetchall() 21 # db.close() #别关,不然只能执行一次get 22 print(data) 23 except Exception as e: 24 print(e) 25 return self.write({'errono':1,'errmsg':'db error'}) 26 houses=[] 27 if data: 28 for l in data: 29 house={ 30 'uname': l[0], 31 'umobile': l[1], 32 'hname':l[2], 33 'haddress':l[3], 34 'hprice':l[4] 35 } 36 houses.append(house) 37 self.write({'errono':0,'errmsg':'ok','data':houses}) 38 39 def post(self): 40 name=self.get_argument('username') 41 password=self.get_argument('password') 42 mobile=self.get_argument('mobile') 43 sql='insert into it_user_info(ui_name,ui_password,ui_mobile) values(%s,%s,%s)' #防止SQL注入 44 # sql='insert into it_user_info(ui_name,ui_password,ui_mobile) values("{}","{}","{}")'.format(name,password,mobile) #导致SQL注入 45 print(sql) 46 try: 47 ''' 48 # user_id=Application().cusor.execute(sql) 49 # user_id=Application().cusor.execute(sql,name=name,password=password,mobile=mobile) 50 # Application().db.commit() 51 # Application().db.close() 52 ''' 53 54 # db.cursor().execute(sql) #导致SQL注入 55 cursor.executemany(sql,[(name,password,mobile)]) # 执行SQL,并返回受影响行数(使用pymysql的参数化语句防止SQL注入) 56 db.commit() 57 # db.close() #别关,不然只能执行一次post 58 except Exception as e: 59 print(e) 60 else: 61 self.write('hello') 62 63 64 class Application(tornado.web.Application): 65 def __init__(self,*args,**kwargs): 66 super().__init__(*args,**kwargs) 67 '''Application这个类是初始化一些全局变量,按照道理说里边的self.db 也应该能够被其他类或者派生类调用的,但是db这个属性就是不行无奈只好创建了一个全局的db句柄''' 68 # self.db=pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='mysql123',db='itcast') 69 # self.cusor=self.db.cursor() 70 71 72 if __name__ == '__main__': 73 tornado.options.parse_command_line() 74 75 current_path = os.path.dirname(__file__) 76 77 settings=dict( 78 static_path=os.path.join(current_path,'statics') #通过向web.Application类的构造函数传递一个名为static_path的参数来告诉Tornado从文件系统的一个特定位置提供静态文件 79 ,template_path=os.path.join(current_path,'templates') 80 ,debug=True) 81 82 app=Application( 83 [(r'/',IndexHandler), 84 ] 85 ,**settings) 86 87 app.listen(tornado.options.options.port) 88 tornado.ioloop.IOLoop().current().start()


posted on 2020-04-05 09:16 cherry_ning 阅读(205) 评论(0) 收藏 举报
浙公网安备 33010602011771号