【问题标题】:Passing parameters to a webapp2.RequestHandler object in python将参数传递给 python 中的 webapp2.RequestHandler 对象
【发布时间】:2012-12-18 02:59:33
【问题描述】:

当我创建我的 WSGIApplication 实例时,有什么方法可以将参数传递给 RequestHandler 对象?

我是说

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/route1', Handler1),
    ('/route2', Handler2)
], debug=True)

是否可以将一些参数传递给MainHandlerHandler1Handler2

提前致谢

【问题讨论】:

  • 你想要达到什么目的?
  • 基本上,我想为多条路线使用一个处理程序。我认为您的回复正是我想要的。

标签: google-app-engine python-2.7 webapp2


【解决方案1】:

本质上,您在 URL 中传递“参数”。

class BlogArchiveHandler(webapp2.RequestHandler):
    def get(self, year=None, month=None):
        self.response.write('Hello, keyword arguments world!')

app = webapp2.WSGIApplication([
    webapp2.Route('/<year:\d{4}>/<month:\d{2}>', handler=BlogArchiveHandler, name='blog-archive'),
])`

从这里:features

以上链接的页面已不存在。可以在here 找到等效文档。

【讨论】:

  • 感谢参考!我在找这个。
【解决方案2】:

您还可以通过配置字典传递参数。

首先你定义一个配置:

import webapp2

config = {'foo': 'bar'}

app = webapp2.WSGIApplication(routes=[
    (r'/', 'handlers.MyHandler'),
], config=config)

然后根据需要访问它。在 RequestHandler 内部,例如:

import webapp2

class MyHandler(webapp2.RequestHandler):
    def get(self):
        foo = self.app.config.get('foo')
        self.response.write('foo value is %s' % foo)

从这里:webapp2 documentation

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多