Create a Python Web Server

Create a Python Web Server

docs https://pythonbasics.org/webserver/

A webserver in Python can be setup in two ways. Python supports a webserver out of the box. You can start a web server with a one liner.

But you can also create a custom web server which has unique functionality. In this article you’ll learn how to do that.

The web server in this example can be accessed on your local network only. This can either be localhost or another network host. You could serve it cross location with a vpn.

Related course: Complete Python Programming Course & Exercises

Example
Builtin webserver
To start a webserver run the command below:

python3 -m http.server

That will open a webserver on port 8080. You can then open your browser at http://127.0.0.1:8080/

The webserver 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.

Web server
Run the code below 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 3 server example

from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyServer(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>https://pythonbasics.org</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), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

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

If you open an url like http://127.0.0.1/example the method do_GET() is called. We send the webpage manually in this method.

web server in python 3

The variable self.path returns the web browser url requested. In this case it would be /example

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值