开发者

How to pass variable to a python cgi script

开发者 https://www.devze.com 2023-04-11 05:16 出处:网络
What I want to do is have a single python program in cgi-bin that is executed by each of many pages on the site, and displays a line of HTML

What I want to do is have a single python program in cgi-bin that is executed by each of many pages on the site, and displays a line of HTML on each page that is different for each file, but keyed to the URL of that file on the site.

I know how to get the URL using javascript (e.g. on http://constitution.org/cs_event.htm ):

<script language="ja开发者_开发百科vascript">
    var myurl = document.location.href;
    document.write(myurl);
</script>
<br>
<script language="javascript">
    var myurl = document.location.href;
    document.write("<A href=\"" + myurl + "\">" + myurl + "<\/A>");
</script>

And I know how to create a link that opens a page to execute the .py script when one clicks on it:

<a href="http://constitution.org/cgi-bin/copy01.py?myurl=myurl">Here</a>

Here is the python script so far:

#!/usr/bin/env python
# This outputs a copyright notice to a web page

import cgi
print "Content-Type: text/html\n"
form = cgi.FieldStorage()

thisurl = form.getvalue("myurl")

print """
<html><head></head>
<body>
"""

print """
Copyright &copy; 1995-2011 Constitution Society. Permission granted to copy with attribution for non-profit purposes.
"""

print """
</body></html>
"""

print thisurl

But it is not so obvious how to pass the variable value to the .py script, and have it automatically display the URL of that page the way the javascript does, or display a line of HTML that it will get from a dictionary in which the URLs are the keys and the HTML lines are the data.

Ultimately, I want to be able to generate, using a single .py script, all the footer content of each page, that can be maintained from a single file that I can edit to make changes that propagate everywhere.


CGI puts various things to do with the current request into the script's shell environment, which you can access in the normal way with os.environ. In particular, os.environ['HTTP_HOST'] will get you the server name, and os.environ['SCRIPT_NAME'] will get you the path.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号