python - Tornado :获取请求参数

标签 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)

当我转到 localhost:port/get?key=python 时,我收到空键值 {'key': ''}。这里有什么问题?

最佳答案

正则表达式中的

(.*) 匹配所有内容。所以这个 — (r"/get(.*)", GetHandler) — 将匹配任何后跟 /get 的内容,例如:

/get
/getsomething
/get/something
/get.asldfkj%5E&(*&fkasljf

假设一个请求来自 localhost:port/get/something,然后 GetHandler.get(self, key) 中的 key 参数的值 将是 /something(是的,包括斜线,因为 .* 匹配所有内容)。

但是如果一个请求来自于 localhost:port/get?key=pythonGETHandler.get(self, key ) 将是一个空字符串。发生这种情况是因为包含 ?key=python 的部分称为 Query String .它不是 url 路径 的一部分。 Tornado(或几乎所有其他 Web 框架)不会将其作为参数传递给 View 。


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

  1. 如果您想像这样访问您的 View - localhost:port/get?key=python,您需要更改您的 url 配置和您的 View :

    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 配置和您的 View ,您需要像这样发出请求 - localhost:port/get/python
    但是您仍然需要对您的 url 配置进行一些小的更改。在 get(.*) 之间添加一个斜杠 - /,否则 key 的值将是 /python 而不是 python

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

关于python - Tornado :获取请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47270054/

相关文章:

python - Tornado Web 服务器文件下载的问题

Python。 Tornado 。非阻塞 xmlrpc 客户端

python - 使用 Fabric 递归复制远程目录

android - 从 Android 中的字符串 ArrayList 创建 JSON

javascript - JSON.stringify 返回空

python - gevent 到 Tornado ioloop - 带有协程/生成器的结构代码

python - django spotify api python http发布500错误

python 3 Tkinter : NameError with Entry widget: name 'Entry' is not defined

java - 使用Retrofit从单个键中提取不同的数据

python - Python Web 开发中的装饰器与类