龙卷风:获取请求参数

Rudziankoŭ

我有以下代码:

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,则keyin参数GETHandler.get(self, key)将为空字符串。发生这种情况是因为其中包含的部分?key=python称为查询字符串它不是url路径的一部分Tornado(或几乎所有其他Web框架)不会将此作为参数传递给视图。


您可以通过两种方式更改代码:

  1. 如果要访问这样的视图- 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)
    
  2. 如果您不想更改应用程序的url配置和视图,则需要发出类似这样的请求- localhost:port/get/python
    但仍然需要对url配置进行一些小的更改。/get之间添加斜线- (.*),因为否则key的值将/python改为python

    application = tornado.web.Application([
        (r"/get/(.*)", GetHandler), # note the slash
    ])
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章