Search code examples
pythongoogle-app-enginewebapp2

google app engine (python27) fetch request url


I have been trying to get the request url as follows

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        print self.request.get('url')

app = webapp2.WSGIApplication([('/.*', MainPage)], debug=True)

when the request is

http://localhost:8080/index.html

it gives me something like

Status: 200 Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Content-Length: 70

what I need to get is something like

index.html

edit: so that I can check the string and display the correct html/template file accordingly.

I have already checked Request documentation and tried many alternatives yet I can't seem to find a solution. I'm quite new to web development. What am I missing?


Solution

  • you should start here: https://developers.google.com/appengine/docs/python/gettingstartedpython27/helloworld

    you are not using a template or a templating module/engine so its irrelevant what path you are accessing because you are mapping everything with /.*

    use self.response.write() not print.
    again its better for you if you start reading the documentation from the beginning before checking out the request class.

    EDIT:

    if you want to get the urlpath in the requesthandler and serve different templates based on the urlpath then do something like this:

    def get(self):
        if self.request.path == '/foo':
            # here i write something out
            # but you would serve a template
            self.response.write('urlpath is /foo')
        elif self.request.path == '/bar':
            self.response.write('urlpath is /bar')
        else:
            self.response.write('urlpath is %s' %self.request.path)
    

    a better approach would be to have multiple ReqeustHandlers and map them in the WSGIApplication:

    app = webapp2.WSGIApplication([('/', MainPage),
                                   ('/foo', FooHandler),
                                   ('/bar', BarHandler),
                                   ('/.*', CatchEverythingElseHandler)], debug=True)