在Python中获取HTTP GET参数
我正在尝试用一个简单的Python脚本来运行一个Icecast音乐流,这个脚本会从服务器上的歌曲列表中随机挑选一首歌。我想添加一个投票或请求的界面,而我的主机支持通过CGI使用Python来提供网页。不过,我在获取用户提供的GET参数时遇到了问题。我试过用常规的方法,使用sys.argv:
#!/usr/bin/python
import sys
print "Content-type: text/html\n\n"
print sys.argv
但是当我访问http://example.com/index.py?abc=123&xyz=987时,只返回了"['index.py']"。Python有没有其他函数可以用来处理这个,或者我在CGI方面需要做什么更改?我想做的事情到底可不可以实现呢?
谢谢。
3 个回答
由于CGI模块在Python 3.11中已经被弃用,并将在3.13中移除,而这个问题在Google上搜索“python3获取cgi参数”时是最常见的结果之一,这里有一个使用推荐替代方案的例子(urllib.parse):
#!/usr/bin/python3
## import the required libraries
import os
import urllib.parse
## print a HTTP content header
print('Content-type: text/plain\r\n')
## get the query string. this gets passed to cgi scripts as the environment
## variable QUERY_STRING
query_string = os.environ['QUERY_STRING']
## convert the query string to a dictionary
arguments = urllib.parse.parse_qs(query_string)
## print out the values of each argument
for name in arguments.keys():
## the value is always a list, watch out for that
print(str(name) + ' = ' + str(arguments[name]))
这个脚本假设你的Python 3安装在/usr/bin/python3。如果你使用的是非Linux平台,需要根据实际情况调整这个路径。
需要注意的是,这种解析方式会把参数的值以列表的形式返回。除非你多次传递同一个参数,否则这个列表里只会有一个值。
举个例子,如果你在http ://192.168.0.1/script.cgi上托管上述CGI脚本:
请求http ://192.168.0.1/script.cgi?hello=world&foo=bar会返回:
hello = ['world']
foo = ['bar']
请求http ://192.168.0.1/script.cgi?hello=world&foo=bar&hello=now会返回:
hello = ['world', 'now']
foo = ['bar']
对于GET请求,我更喜欢使用 cgi.parse()
。它会返回一个简单的字典,里面是一些列表。
import cgi
args = cgi.parse()
比如,查询字符串 ?key=secret&a=apple
被解析成:
{'key': ['secret'], 'a': ['apple']}
cgi.FieldStorage()
可以帮你解决这个问题... 它会返回一个字典,字典的键是字段名,值是对应的值。
import cgi
import cgitb; cgitb.enable() # Optional; for debugging only
print "Content-Type: text/html"
print ""
arguments = cgi.FieldStorage()
for i in arguments.keys():
print arguments[i].value