通过routes传参之get请求:
四种方法:
分别是self.get_argument,self.get_query_argument,
self.get_query_arguments,self.get_query_arguments
公共的参数:第一个字符串对应输出的变量,strip=True
表示去除传参前后的空白,前两个可以定义默认值,后面两个没有这个选项.
前面两个只能传一个,后面可以传多个返回列表
name= self.get_query_argument('name',default='默认',strip=True)
不传参
传参
name= self.get_query_arguments('name',strip=True)
带s的都返回列表
只传一个参数:
传两个参数:
Post请求:
所用的软件为postman
返回列表
name = self.get_body_arguments('name',strip=True)
name = self.get_body_argument('name',default='haha',strip=True)
直接返回,可以定义默认值
当然还有其他的请求方法,以后用到再介绍.
数据库连接和切入点函数:
切入点函数配合数据库使用,def initialize(self)是最先运行的,可以在里面放入数据库连接的代码并开启事务,
self.conn= = pymysql.Connect(host='127.0.0.1',user='root',password='123456',database='tornado1',port=3306)
self.cursor = self.conn.cursor()
然后就是def prepare(self),中间是get请求函数,最后是def on_finish(self)
class EntryHandler(tornado.web.RequestHandler):def initialize(self):
self.conn = pymysql.Connect(host='127.0.0.1',user='root',password='123456',database='tornado1',port=3306)
self.cursor = self.conn.cursor()
self.write('我最先运行')def prepare(self):
self.write('我第二,在get之前')def get(self):
self.write('我用来查询数据,第三步运行')
sql = 'select * from stu'
self.cursor.execute(sql)
data = self.cursor.fetchall()
print(data)def on_finish(self):
self.conn.close()
关于配置router,补充的:
可以在配置的时候,加入正则表达式来约定router
(r'/routes1/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d{2})/',Routes1Handler)
格式就是/(?P<变量名>正则表达式)/
对应get:
def get(self,year,month,day):
self.write('日期:%s年%s月%s日'%(year,month,day))
就可以取到对应的数据了!