Jorge Arévalo
Jorge Arévalo

Reputation: 3008

Passing parameters to a webapp2.RequestHandler object in python

Is there any way to pass parameters to a RequestHandler object when I create my WSGIApplication instance?

I mean

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

Is it possible to pass some arguments to MainHandler, Handler1 or Handler2?

Thanks in advance

Upvotes: 7

Views: 5705

Answers (2)

Ivan Chaer
Ivan Chaer

Reputation: 7100

You can also pass parameters through a configuration dictionary.

First you define a configuration:

import webapp2

config = {'foo': 'bar'}

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

Then access it as you need. Inside a RequestHandler, for example:

import webapp2

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

From here: webapp2 documentation

Upvotes: 8

Paul Collingwood
Paul Collingwood

Reputation: 9116

You pass "arguments" in the URL essentially.

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'),
])`

From here: features

The page at above link no longer exists. Equivalent doc can be found here.

Upvotes: 8

Related Questions