[Tutor] How can a CGI program get the URL that called it?

Terry Carroll carroll at tjc.com
Thu Jan 9 23:30:45 CET 2014


How can my Python 2.7 CGI program find the URL that caused the program to 
be called?

I have a program that creates a JPG or PNG file on the fly, and needs to 
construct a URL to it. I know the path relative to my program is, for 
example, "../temp/tmpiicack.png" (the filename generated by 
tempfile.NamedTemporaryFile).  From this, I want to generate a URL for the 
image so it can be displayed.

I invoke My CGI program (in testing) with the URL 
http://localhost:8000/cgi-bin/query.py?tmtype=s&tmnumber=76044902. It is 
usually invoked using a form at http://localhost:8000/cgi-bin/query.py, 
which generates the URL, but can also be invoked by directly going to the 
URL with parameters specified (I want to be able to email a complete URL, 
for example).  In this instance, the URL I want to generate would be 
http://localhost:8000/temp/tmpiicack.png.  The problem is, my program does 
not know the "http://localhost:8000" part.

Module urlparse has facilities for generating a URL from relative parts, 
but requires that I know a base URL to begin with. I've looked in 
os.environ to see if anything is presented, but the only thing close is 
os.environ['HTTP_REFERER'], which is only populated if the program is 
invoked from the form-click, not if directly entered (e.g. copy/paste).

(That's my fall-back solution; but it will mean the image-support will 
fail if a URL is entered directly, and will work only if invoked from a 
form.)

I've also checked os.environ['PATH_INFO'] as suggested in a post on 
stackoverflow,[1] but that is not populated.  (I can't recall whether it's 
a zero-length string or None, but it has nothing useful).

I'm testing using CGIHTTPServer as my server, if it matters.


[1] 
http://stackoverflow.com/questions/4939067/catching-the-url-path-following-a-python-cgi-script/4939137#4939137



More information about the Tutor mailing list