Simple Web server example of Python programming implementation

  • 2020-06-03 07:18:53
  • OfStack

This article illustrates a simple Web server implemented by Python programming. To share for your reference, specific as follows:

Recently, there was a need to create an web server as simple as possible. The purpose was to have a background process to receive requests and then process and return the results, so I came up with the idea of using Python.

First, you create an file, which defines a method through which all requests can process the passed url and parameters and return the result.

def myapp(environ, start_response):
  status = '200 OK'
  headers = [('Content-type', 'text/html')]
  start_response(status, headers)
  if len(environ['PATH_INFO']) == 1:
    return "Hello World!"
    return "Hello {name}!".format(name=environ['PATH_INFO'][1:])

Then create an file, where an Http service is started, and use the app created above to receive and process the request

from wsgiref.simple_server import make_server
from myapp import myapp
httpd = make_server('', 8000, myapp)
print "Serving HTTP on port 8000..."

Finally, run "python" to start the service.

Test 1 by entering url below in the browser


For more information about Python, please refer to Python Socket Programming Skills summary, Python URL operation Skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Using Skills Summary, Python String Operation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.

Related articles: