Getting HTTP GET arguments in Python
Asked Answered
B

3

26

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:

#!/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=987 only 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?

Thanks.

Book answered 27/8, 2010 at 8:16 Comment(0)
A
51

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

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
Aftershaft answered 27/8, 2010 at 8:40 Comment(0)
Y
4

For GET requests I prefer cgi.parse(). It returns a simple dictionary of lists.

import cgi
args = cgi.parse()

For example, the query string ?key=secret&a=apple is parsed as:

{'key': ['secret'], 'a': ['apple']}
Yolanthe answered 7/5, 2021 at 21:36 Comment(0)
H
1

Given that the CGI module is depreceated as of Python 3.11 and will be removed in 3.13, and this question is one of the top Google results for "python3 get cgi parameters" here is an example using the proposed replacement (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]))

This script assumes that your Python 3 install is located at /usr/bin/python3. You will need to adjust this for non-Linux platforms.

It should be noted that parsing in this way will give you values as a list. Unless you pass the same parameter multiple times, this list will only have one value.

For example, if you are hosting the above CGI script at http ://192.168.0.1/script.cgi:

A request to http ://192.168.0.1/script.cgi?hello=world&foo=bar will give

hello = ['world']
foo = ['bar']

A request to http ://192.168.0.1/script.cgi?hello=world&foo=bar&hello=now will give:

hello = ['world', 'now']
foo = ['bar']
Hent answered 16/12, 2023 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.