Duan
Duan

Reputation: 53

Google appengine rewrite question

How can I rewrite url for python:

http://localhost:8081/?page=1

to

http://localhost:8081/1

here is my code, but it's not working:

class MainPage(webapp.RequestHandler):
    def get(self, page):
        mypage = self.request.get('page')
        self.response.headers['Content-Type'] = 'text/plain'
        if mypage == "":
            self.response.out.write('Hello, webapp World!')
        else:
            self.response.out.write('page is ' + mypage)


application = webapp.WSGIApplication([('/', MainPage),('/(\d+)', MainPage)], debug=True)

Upvotes: 4

Views: 613

Answers (3)

Nick Johnson
Nick Johnson

Reputation: 101139

You've defined two mappings for your MainPage handler, one that will pass in no parameters ('/'), and one that will pass in one parameter ('/(\d+)'). Your handler, however, expects exactly one argument, named page.

You either need to use two different handlers, or supply a default value for the page argument, like this:

class MainPage(webapp.RequestHandler):
    def get(self, page=None):
        if not page:
          self.redirect('/%s', self.request.get('page'))
          return
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('page is ' + mypage)

For future reference, when you get a stacktrace, include it in your question! Saying "It's not working" and making us guess exactly what's going wrong isn't a good way to get useful answers to your question.

Upvotes: 1

Justin Morgan
Justin Morgan

Reputation: 2435

You can use regular expressions in your controller. It's not Apache-style URL rewriting per se, but it gets the job done. The rewritten parameter is passed as an argument to the handler.

class MyRequestHandler(webapp.RequestHandler):
    def get(self, page):
        self.response.headers['Content-Type'] = 'text/plain'
        if not page:
            self.response.out.write('Hello, webapp World!')
        else:
            self.response.out.write('page is ' + page)

url_map = [('/(\d+)', MyRequestHandler)]
application = webapp.WSGIApplication(url_map, debug=True)

See How to configure app.yaml to support urls like /user/<user-id>? for a similar application.

Upvotes: 4

Wooble
Wooble

Reputation: 89847

Assuming you're using webapp:

class Rewriter(webapp.RequestHandler):
    def get(self):
        self.redirect(self.request.get('page'))

application = webapp.WSGIApplication([('/', Rewriter)],)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

Upvotes: 1

Related Questions