Advertisement
A web server stores and serves website content, such as text, photos, videos, and application data, to clients who request it. A web browser application is the most prevalent sort of client, and it requests data from your website when a user clicks on a link or downloads a document on a page displayed in the browser. There are two approaches to setting up a web server in Python. Python includes a webserver by default. You can also build a custom web server with unique features. This tutorial will teach you how to do so.
Python Default Web Server
Run the following command to start a webserver:
python3 -m http.server
The above code will launch a very simple Web server that will serve files relative to the current directory on port 8000. You can then navigate to http://127.0.0.1:8080/ in your browser.
The webserver is also reachable over the network using your 192.168.-.- IP address. This is the machine’s default server, from which you can download files.
Change Web Server port
Run the following command to change the port of the webserver:
python3 -m http.server 8080
Customize Python Web Server
The above code will set up a very basic server that will serve files from the current directory. It is also possible to build a Web server in python that can respond to HTTP queries and return HTML websites.
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080
class MyWebServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Web Server</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("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyWebServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
The following code set up A web server capable of handling HTTP GET requests and returning an HTML file as a response. When you open a URL like http://127.0.0.1/example
, the method do_GET()
is invoked. In this way, we manually send the webpage.
Create Python Flask Web Server
Flask is a web framework and a Python module that allows you to easily create web applications. It has a tiny and easy-to-extend core: it’s a microframework without an ORM (Object Relational Manager) or similar functionality.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Run the file and the webserver will be created:
$ python server.py
* Serving Flask app "hello"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
It then launches a web server that is solely accessible from your computer. In a web browser, navigate to localhost on port 5000 and you’ll see “Hello World.”
Learn Intermediate Python, GUI Programming in C.
Read more about the python flask web framework.