python server example

Example 1: start a simple http server python3

python3 -m http.server 8000

Example 2: python start simplehttpserver

# If Python version is 3.X
python3 -m http.server

# If Python version is 2.X
python -m SimpleHTTPServer

Example 3: python httpserver

python -m http.server 8000 --bind 127.0.0.1

Example 4: python3 webserver command line

python3 -m http.server

Example 5: create a server in python

# 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.")

Example 6: web server python

# Creating a Web server using Python and Flask

from flask import Flask

app = Flask('app')
@app.route('/')

def run():
    return '<h1>Hello, Server!</h1>'

app.run(host = '0.0.0.0', port = 8080)