Bhargav
Bhargav

Reputation: 918

How to get the url from the request

I am building a blog and I am working on a way to export it's contents to json and xml. To get this working, I thought of getting the url of the page whose content I wanted to export from the request headers. But I am doubting whether it would work because googling around has not given me any answers.

I am making it such that when I add .json to the end of my blog url the json is being displayed, so that's why I am looking into getting the url from the request, I even used os.environ but that did not work.

EDIT: So as per @Timbtron's answer I used the

self.request.get['path_url']

But it only resulted in a key error.

Sorry I understood that wrong it's supposed to be

self.request.path_url

Upvotes: 0

Views: 885

Answers (2)

Brent Washburne
Brent Washburne

Reputation: 13158

Instead of parsing the url_path in your code, you could let the URI Routing take care of it for you (borrowing from Tombatron's example):

class HtmlBlogHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('This is the HtmlBlogHandler.')

class JsonBlogHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('This is the JsonBlogHandler.')

class XmlBlogHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('This is the XmlBlogHandler.')

app = webapp2.WSGIApplication([
    (r'/article.html', HtmlBlogHandler),
    (r'/article.json', JsonBlogHandler),
    (r'/article.xml', XmlBlogHandler),
])

You can customize the routes to handle various article IDs and types.

Upvotes: 0

Tombatron
Tombatron

Reputation: 1347

If I understand you correctly, you are trying to get the URL that the user requested while processing that user's request. If so, take a look at the following doc:

Request data - webapp2

Another strategy to consider is that you could create 3 handlers, one for HTML, XML, and JSON. You could setup routing rules to hit the appropriate handler depending on the "file extension" that the user was requesting.

For example:

Just another idea to consider.

Upvotes: 1

Related Questions