Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting HTTP GET arguments in Python

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.

like image 705
James Avatar asked Aug 27 '10 08:08

James


People also ask

How do you get parameters in Python?

To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.

How do you add parameters to a URL in Python?

The results of urlparse() and urlsplit() are actually namedtuple instances. Thus you can assign them directly to a variable and use url_parts = url_parts. _replace(query = …) to update it.

What is params in Python?

Param is a library providing Parameters: Python attributes extended to have features such as type and range checking, dynamically generated values, documentation strings, default values, etc., each of which is inherited from parent classes if not specified in a subclass.


1 Answers

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 
like image 72
lalli Avatar answered Oct 20 '22 01:10

lalli