Python Web Server can be set up in two ways. Python supports a Web Server in the “out of the box” way. We can even start a web server with just a one-liner in Python!
This post will demonstrate how to run another Python feature in Python4Delphi with RAD Studio: Python Web Server in Python GUI apps and gets the output. The web server in this example can be accessed on your local network only.
Prerequisites: Before we begin to work, download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out the easy instructions found in this video Getting started with Python4Delphi.
First, open and run our Python GUI using project Demo1 from Python4Delphi with RAD Studio. Then insert the script into the lower Memo, click the Execute button, and get the result in the upper Memo. You can find the Demo1 source on GitHub. The behind the scene details of how Delphi manages to run your Python code in this amazing Python GUI can be found at this link.
Table of Contents
1. One-Liner Example
Let’s run the built-in web server in our command prompt, using this command:
python3 -m http.server
That will open a web server on port 8000. You can then open your browser at http://127.0.0.1:8000/ or http://localhost:8000/
The web server is also accessible over the network using your 192.168.-.- address. This is a default server that you can use to download files from the machine.
Let’s see it in action, both in your command prompt and browser:
2. Web Server in Python GUI in Python4Delphi
Let’s run the code below in our Demo01 VCL to start a custom web server. To create a custom web server, we need to use the HTTP protocol. By design the http protocol has a “get” request which returns a file on the server. If the file is found it will return 200.
The server will start at port 8080 and accept default web browser requests:
# Python web server example
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<p>This is an example web server run by Python4Delphi.</p>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
Output in our Python GUI:
If you open the URL like http://127.0.0.1:8000/ or http://localhost:8000/ the method do_GET() is called. We send the web page manually in this method.
Appearance in our browser:
The variable self.path returns the web browser URL requested.
http.server is not recommended for production. It only implements basic security checks.
Check out Python4Delphi which easily allows you to build Python GUIs for Windows using Delphi.