How To Get Query Parameters In Python

A necessity is using Python in HTML is the ability to pass query parameters from page to page.

You are going to want to do this passing as you move from page to page, or you submit values from the page you are currently on to itself to be entered into the database.

This process of passing variables in the url is using the GET action of your form. It supposedly “insecure” versus POST, because it shows the passed values in the url, but check out all the pages you visit that are passing data in the url…

This can be done in various ways (I showed another way on this blog, but this way is cleaner, IMHO), but a functional way I have found to do this is found by clicking the link below:

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Python Query Params</title>"
print "</head>"
print "<body>"

import os


def init():
	#read the url
	params = os.environ.get('QUERY_STRING')

	print ("Click this url that has params in address: <a href='https://pythoninhtmlexamples.com/files/python-query-params/index.py?id=5&fname=kelly&lastname=schnerde'>https://pythoninhtmlexamples.com/files/python-query-params/index.py?id=5&fname=kelly&lastname=schnerde</a><br><br>")

	print ("Click this url that has <b>NO</b> params in address: <a href='https://pythoninhtmlexamples.com/files/python-query-params/index.py'>https://pythoninhtmlexamples.com/files/python-query-params/index.py</a><br><br>")


	print ("<br><br><br>********************************************************<br><br><br>")

	res = params.split('=') #TESTS THAT THERE IS A QUERY STRING

	#display based on if params were sent
	if  str(res) == "['']":
		print ('no query params')
		print '<br>'
	else:
		print ('some params were passed - show them')
		print '<br>'
		
		#searchParams is an array of type [['key','value'],['key','value']]	
		searchParams = [i.split('=') for i in params.split('&')] #parse query string
		for key, value in searchParams:
			print('<b>' + key + '</b>: ' + value + '<br>\n')			
		

    
#start here:
init()


print "</body>"
print "</html>"

Here is the working sample (remember to CHMOD 755 your file):

https://pythoninhtmlexamples.com/files/python-query-params/index.py

Facebooktwitterredditpinterestlinkedinmail
Tags: ,
Previous Post

Python Project – Login Form

Next Post

Python Project – Online Quiz Management