I am new to python, i want to know in python how to receive the URL parameter value? I tried with below code, but
import urllib.parse as urlparse
from urllib.parse import urlencode
url = "http://domainanme.com/api/filename.py?para_name=value"
url_parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(url_parts[4]))
Using python i am unable to receive para_name = value
But in PHP can easily get URL parameter value using $_GET['para_name']
, with out knowing the full URL, but in python how do i know the full URL with params
Note: i want to do using core python without any Python framework
CodePudding user response:
You can try this:
import urllib.parse as urlparse
from urllib.parse import urlencode
url = "http://domainanme.com/api/filename.py?para_name=value"
url_parts = urlparse.urlparse(url)
query = urlparse.parse_qs(url_parts.query)
value = query['para_name']
You can access the query string from the query
attribute of the ParseResult
object. Then just access the value by key name.
CodePudding user response:
I hope this will help you
cgi.FieldStorage()
It returns a dictionary with the key as the field and value as its value.
Without any python framework, you can get the URL parameter value
Sample code
import cgi
import cgitb; cgitb.enable() # Optional; for debugging only
print("Content-Type: text/html")
arguments = cgi.FieldStorage()
for i in arguments.keys():
print(arguments[i].value)
Example: save this file as test.py
and execute it in your browser
like http://youdomainname.com/test.py?name=john
in the browser, you can see the result as a john