Jump to content

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!"

# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import mysql.connector
import requests
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        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("fudge"), "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("**ADD $_GET['name'] HERE**", "utf-8"))
        

if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

 

Link to post
Share on other sites

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!"

Edited by maplepants
fixed a mistake
Link to post
Share on other sites

12 hours ago, QQ_cazo said:

I am not using one yet, I do have a basic HTTP server 

Compared to PHP Python handles web development differently. As you can see above the default HTTP server is super basic and not used in any dynamic website development. For that frameworks are use like Django or Flask. They then handle request/responses, forms, validation and way more.

Link to post
Share on other sites

13 hours ago, riklaunim said:

Compared to PHP Python handles web development differently. As you can see above the default HTTP server is super basic and not used in any dynamic website development. For that frameworks are use like Django or Flask. They then handle request/responses, forms, validation and way more.

Django and Flask are much more powerfull, for sure. But they also require quite a lot of work to get up and running, in comparison with the built in http server. 

 

If you're running some self-hosted LAN only service where the goals are to offer a service & learn some programming, the built in server is the way to go. Especially if you're used to running some other webserver like apache or nginx, the default webserver is good because you really have easy control over headers, status codes and other stuff you might care about.

 

I'm a big fan of not over building my home LAN only projects. 

Link to post
Share on other sites

On 11/24/2021 at 5:18 PM, maplepants said:

If you're running some self-hosted LAN only service where the goals are to offer a service & learn some programming, the built in server is the way to go. Especially if you're used to running some other webserver like apache or nginx, the default webserver is good because you really have easy control over headers, status codes and other stuff you might care about.

 

For development locally Python built in server can be handy, but for other things it's quite bad - in terms of reliability and features. If you are developing a dynamic website in Python then it will be  a framework and it dev server - then production deployment. And if you need static server then you run nginx or apache even. Compared to PHP there isn't pretty much any "simple scripts" really - one or few py files. It died with mod_python and cgi approach among the Python ecosystem.

 

If you need something custom or showcase an implementation, then yes, you can use Python for that, and there are even quite advanced tools for more complex things (although in terms of performance you have to take Python limitations into account).

Link to post
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

×