如何将变量传递给Python CGI脚本
我想做的是在cgi-bin里放一个单独的python程序,这个程序可以被网站上很多页面调用,并且在每个页面上显示一行不同的HTML内容,这些内容是根据该页面的URL来决定的。
我知道怎么用javascript获取URL(比如在http://constitution.org/cs_event.htm这个链接上):
<script language="javascript">
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>
我也知道怎么创建一个链接,当点击它时可以打开一个页面来执行.py脚本:
<a href="http://constitution.org/cgi-bin/copy01.py?myurl=myurl">Here</a>
到目前为止,这是我的python脚本:
#!/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 © 1995-2011 Constitution Society. Permission granted to copy with attribution for non-profit purposes.
"""
print """
</body></html>
"""
print thisurl
但是,怎么把变量的值传递给.py脚本,并让它像javascript那样自动显示该页面的URL,或者从一个字典中获取一行HTML(这个字典的键是URL,值是HTML内容),这点还不是很清楚。
最终,我希望能通过一个.py脚本生成每个页面的底部内容,这样我只需要维护一个文件,编辑这个文件就能让所有页面的内容都更新。
1 个回答
0
CGI会把当前请求的各种信息放到脚本的环境中,你可以通过正常的方式使用os.environ
来访问这些信息。特别是,os.environ['HTTP_HOST']
可以获取到服务器的名称,而os.environ['SCRIPT_NAME']
则可以获取到脚本的路径。