Difference between revisions of "Python Code"

From Cordovawiki
Jump to navigation Jump to search
Tag: Reverted
Line 5: Line 5:
<code>python3 -m http.server</code>
<code>python3 -m http.server</code>


# Python 3 server example
<code>
<code>
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import time

Revision as of 16:14, 29 January 2022

This page contains practical examples of Python 2 and 3 code.

To start a webserver run the command below:

python3 -m http.server

  1. 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("

Request: %s

" % self.path, "utf-8"))

       self.wfile.write(bytes("<body>", "utf-8"))

self.wfile.write(bytes("

This is an example web server.

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