Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current URL in python web page?

I am a noob in Python. Just installed it, and spent 2 hours googleing how to get to a simple parameter sent in the URL to a Python script

Found this

Very helpful, except I cannot for anything in the world to figure out how to replace

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

With what do I replace url = 'string' to make it work? I just want to access http://site.com/test/test.py?param=abc and see abc printed.


Final code after Alex's answer:

url = os.environ["REQUEST_URI"] 
parsed = urlparse.urlparse(url) 
print urlparse.parse_qs(parsed.query)['param']
like image 347
Bogdan P. Avatar asked Jan 22 '13 22:01

Bogdan P.


1 Answers

If you don't have any libraries to do this for you, you can construct your current URL from the HTTP request that gets sent to your script via the browser.

The headers that interest you are Host and whatever's after the HTTP method (probably GET, in your case). Here are some more explanations (first link that seemed ok, you're free to Google some more :).

This answer shows you how to get the headers in your CGI script:

If you are running as a CGI, you can't read the HTTP header directly, but the web server put much of that information into environment variables for you. You can just pick it out of os.environ[].

If you're doing this as an exercise, then it's fine because you'll get to understand what's behind the scenes. If you're building anything reusable, I recommend you use libraries or a framework so you don't reinvent the wheel every time you need something.

like image 159
Alex Ciminian Avatar answered Sep 24 '22 02:09

Alex Ciminian