在 Python 中获取 HTTP GET 参数

问题描述 投票:0回答:3

我正在尝试使用简单的 Python 脚本运行 Icecast 流,以从服务器上的歌曲列表中随机选择一首歌曲。我希望添加一个投票/请求接口,并且我的主机允许使用 python 通过 CGI 提供网页服务。但是,我对如何获取用户提供的 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 进行更改吗?我想做的事情可能吗?

谢谢。

python cgi get arguments
3个回答
51
投票

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

4
投票

对于 GET 请求,我更喜欢

cgi.parse()
。它返回一个简单的列表字典。

import cgi
args = cgi.parse()

例如,查询字符串

?key=secret&a=apple
被解析为:

{'key': ['secret'], 'a': ['apple']}

0
投票

鉴于 CGI 模块 自 Python 3.11 起已弃用,并将在 3.13 中删除,并且此问题是“python3 get cgiparameters”的 Google 搜索结果之一,这里是使用建议的替换的示例( 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 平台进行调整。

应该注意的是,以这种方式解析将为您提供列表形式的值。除非多次传递相同的参数,否则该列表将只有一个值。

例如,如果您将上述 CGI 脚本托管在 http://192.168.0.1/script.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']
© www.soinside.com 2019 - 2024. All rights reserved.