我有以下代码:
application = tornado.web.Application([
(r"/get(.*)", GetHandler),
])
class GetHandler(tornado.web.RequestHandler):
def get(self, key):
response = {'key': key}
self.write(response)
当我去时,localhost:port/get?key=python
我收到空键值{'key': ''}
。怎么了
(r"/get(.*)", GetHandler)
这将匹配后跟的任何内容/get
,例如:
/get
/getsomething
/get/something
/get.asldfkj%5E&(*&fkasljf
因此,假设有一个请求传入localhost:port/get/something
,则in中的key
参数值GetHandler.get(self, key)
将为/something
(是,包括斜杠,因为您要进行匹配.*
,这意味着匹配所有内容)。
但是如果请求来自at localhost:port/get?key=python
,则key
in的参数值GETHandler.get(self, key)
将为空字符串。发生这种情况是因为其中包含的部分?key=python
称为查询字符串。它不是url路径的一部分。Tornado(或几乎所有其他Web框架)不会将此作为参数传递给视图。
您可以通过两种方式更改代码:
如果要访问这样的视图- localhost:port/get?key=python
,则需要更改url配置和视图:
application = tornado.web.Application([
(r"/get", GetHandler),
])
class GetHandler(tornado.web.RequestHandler):
def get(self):
key = self.get_argument('key', None)
response = {'key': key}
self.write(response)
如果您不想更改应用程序的url配置和视图,则需要发出类似这样的请求- localhost:port/get/python
。
但仍然需要对url配置进行一些小的更改。/
在get
和之间添加斜线- (.*)
,因为否则key的值将/python
改为python
。
application = tornado.web.Application([
(r"/get/(.*)", GetHandler), # note the slash
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句