版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/monkeysheep1234/article/details/89397606
1:如何实现url中带数字(字符串)类型的匹配?
class PeopleIdHandler(web.RequestHandler):
async def get(self, id, *args, **kwargs):
self.write("用户ID:{}".format(id))
class PeopleNameHandler(web.RequestHandler):
async def get(self, name, *args, **kwargs):
self.write("用户姓名:{}".format(name))
class PeopleInfoHandler(web.RequestHandler):
async def get(self, name, age, gender, *args, **kwargs):
self.write("用户姓名:{},用户年龄:{},用户性别:{},".format(name, age, gender))
……
urls = [
# 匹配数字类型
("/people/(\d+)/", PeopleIdHandler),
# 匹配字符串类型
("/people/(\w+)/", PeopleNameHandler),
# 更丰富的匹配结合正则去实现……
("/people/(\w+)/(\d+)/(\w+)/", PeopleInfoHandler)
]
……
2:地址中有斜杠结尾和没斜杠结尾,访问会出现有成功和失败的情况?
url中 用户没输入斜杠时,程序自动补全,在url配置中最后加上/?即可
urls = [
("/people/(\d+)/?", PeopleIdHandler),
("/people/(\w+)/?", PeopleNameHandler),
("/people/(\w+)/(\d+)/(\w+)/?", PeopleInfoHandler)
]
3:在url中配置一个名称,在程序的执行逻辑中使用该名称实现一些操作
class PeopleIdHandler(web.RequestHandler):
async def get(self, id, *args, **kwargs):
# 实现跳转到/people/name的页面
# reverse_url后传递参数的个数 根据url配置里的设定变动
self.redirect(self.reverse_url("people_name", "bobby"))
……
urls = [
tornado.web.URLSpec("/people/(\d+)/?", PeopleIdHandler, name="people_id"),
tornado.web.URLSpec("/people/(\w+)/?", PeopleNameHandler, name="people_name"),
tornado.web.URLSpec("/people/(\w+)/(\d+)/(\w+)/?", PeopleInfoHandler, name="people_info"),
]
4:在url中传递给handler一些初始化的参数
people_db = {"name":"people_db"}
# 如不同的业务使用的数据库不同时
urls = [
tornado.web.URLSpec("/people/(\d+)/?", PeopleIdHandler, people_db, name="people_id"),
]
# 在handler中获取到传递进来的值,在哪个方法中处理这个值
class PeopleIdHandler(web.RequestHandler):
def initialize(self, name):
self.db_name = name
async def get(self, id, *args, **kwargs):
# 实现跳转到/people/name的页面
# reverse_url后传递参数的个数 根据url配置里的设定变动
self.redirect(self.reverse_url("people_name", "bobby"))
5:在url配置中的推荐写法,提升可读性
urls = [
# 在变量前 加上?P<> ;<>内的值 变量名称要和后面用的保持一致
tornado.web.URLSpec("/people/(?P<name>\w+)/(?P<age>\d+)/(?P<gender>\w+)/?", PeopleInfoHandler, name="people_info"),