I am writing a site using cgi, you need to get an unknown number of parameters without a name. Example URL http://127.0.0.1:8000/cgi-bin/script.py?6&20&21&22&23 , for the named parameters used cgi.FieldStorage (), but in this case it returns nothing.
1 answer
Parameters always have names, but not always values. To include no values ββin FieldStorage() , pass the keep_blank_values argument:
#!/usr/bin/env python3 import cgi print("Content-Type: text/plain\n") form = cgi.FieldStorage(keep_blank_values=1) print(*form) See What does it mean * (asterisk) and ** double star in Python?
To start the server for demonstration, execute in the directory with cgi-bin :
$ python3 -mhttp.server --cgi --bind localhost If you go to:
$ python -mwebbrowser "http://localhost:8000/cgi-bin/script.py?6&20&21&22&23" then the browser will show (up to order, see PYTHONHASHSEED ):
21 23 22 6 20 The query in the question also works less common: os.environ['QUERY_STRING'].split('&') and even sys.argv[1].split('&') (if no value is specified β if not '=' in QUERY_STRING ).
- Thank you, but do not tell me how it works * in print (* form)? The only thing I understand is that the elements of the collection are displayed this way - First_Spectr
- one@First_Spectr: added a link to the answer to the explanation of what * does (
list(form)returns all keys (parameter names) as for dictionaries in Python). - jfs
|