在 Python 中获取 HTTP GET 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3582398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:48:33  来源:igfitidea点击:

Getting HTTP GET arguments in Python

pythoncgigetarguments

提问by James

I'm trying to run an Icecast stream using a simple Python script to pick a random song from the list of songs on the server. I'm looking to add a voting/request interface, and my host allows use of python to serve webpages through CGI. However, I'm getting hung up on just how to get the GET arguments supplied by the user. I've tried the usual way with sys.argv:

我正在尝试使用简单的 Python 脚本运行 Icecast 流,以从服务器上的歌曲列表中随机选择一首歌曲。我想添加一个投票/请求接口,我的主机允许使用 python 通过 CGI 提供网页。但是,我对如何获取用户提供的 GET 参数感到困惑。我已经用 sys.argv 尝试了通常的方法:

#!/usr/bin/python
import sys
print "Content-type: text/html\n\n"
print sys.argv

But hitting up http://example.com/index.py?abc=123&xyz=987only returns "['index.py']". Is there some other function Python has for this purpose, or is there something I need to change with CGI? Is what I'm trying to do even possible?

但是点击http://example.com/index.py?abc=123&xyz=987只会返回“['index.py']”。为此,Python 是否还有其他一些功能,或者我需要使用 CGI 进行更改吗?我正在尝试做的甚至可能吗?

Thanks.

谢谢。

采纳答案by lalli

cgi.FieldStorage()should do the trick for you... It returns a dictionary with key as the field and value as its value.

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