Rud*_*koŭ 2 python json tornado
我有以下代码:
application = tornado.web.Application([
(r"/get(.*)", GetHandler),
])
class GetHandler(tornado.web.RequestHandler):
def get(self, key):
response = {'key': key}
self.write(response)
Run Code Online (Sandbox Code Playgroud)
当我转到时,localhost:port/get?key=python会收到空键值{'key': ''}。怎么了
(r"/get(.*)", GetHandler)这将匹配后跟的任何内容/get,例如:
/get
/getsomething
/get/something
/get.asldfkj%5E&(*&fkasljf
Run Code Online (Sandbox Code Playgroud)
因此,假设有一个请求传入localhost:port/get/something,则in中的key参数值GetHandler.get(self, key)将为/something(是,包括斜杠,因为您要进行匹配.*,这意味着匹配所有内容)。
但是如果请求来自at localhost:port/get?key=python,则keyin 的参数值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)
Run Code Online (Sandbox Code Playgroud)如果您不想更改应用程序的url配置和视图,则需要发出这样的请求- localhost:port/get/python。
但是,仍然需要对url配置进行一些小的更改。/在get和之间添加斜线- (.*),因为否则key的值将/python改为python。
application = tornado.web.Application([
(r"/get/(.*)", GetHandler), # note the slash
])
Run Code Online (Sandbox Code Playgroud)