Python equivalent to $_GET['myparam] in PHP
Go to solution
Solved by maplepants,
A developer after my own heart. I'm a big fan of the default server in python3 as well. It's a bit bare bones though, so basic stuff like parameter handling is something you need to build in. In my self hosted web pages I have a template I use which already has basic parameter handling built it. Adding basic parameter handling to your code would look like this:
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import mysql.connector
import requests
# Define same static variables
hostName = "localhost"
serverPort = 8080
# Data parsing functions
def getParamsFromPath(path) :
getParamsDict = {}
if "?" in path:
pathSplit = path.split("?", 1)
print(str(pathSplit))
if "&" in pathSplit[1]:
paramsRaw = pathSplit[1].split("&")
for pRaw in paramsRaw:
pSplit = pRaw.split("=")
if len(pSplit) == 2:
getParamsDict[str(pSplit[0])] = str(pSplit[1])
elif "=" in pathSplit[1]:
pSplit = pathSplit[1].split("=")
if len(pSplit) == 2:
getParamsDict[str(pSplit[0])] = str(pSplit[1])
return getParamsDict
#The server itself
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
getParameters = getParamsFromPath(self.path)
def greet(name):
return "Hello, " + name + ". Good morning!"
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title><title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes(greet(getParameters["name"]), "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
self.wfile.write(bytes(getParameters["name"], "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
If you call `curl http://localhost:8080/?name=Dave` you'll get back "Hello Dave. Good morning!"

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now