In the command line, we can do this:
$ python3 -m http.server 8674
But in Python code (in .py), how to do this?
P.S. Don't use os.system! I'm going to use it in an exe, and that will fail.
P.P.S. Don't suggest this. Really from code, not command line.
-
No but I'll suggest reading the docs as there's examples on how to run it in code. It's a module so you can just import it.Torxed– Torxed2020-05-25 13:09:43 +00:00Commented May 25, 2020 at 13:09
-
@Torxed see accepted answer below.wyz23x2– wyz23x22020-05-25 13:25:54 +00:00Commented May 25, 2020 at 13:25
Add a comment
|
2 Answers
All you have to do is import the http.server default module.
from http.server import HTTPServer, SimpleHTTPRequestHandler
def run(number=8080, server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
server_address = ('', number)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Exit")
See Python docs for further explanations.
2 Comments
wyz23x2
Why do I get this error:
code 501, message Unsupported method ('GET')Tim
When do you get this error ? Upon launching the server ? You can try to replace BaseHTTPRequestHandler with SimpleHTTPRequestHandler, make sure you import it. See this thread : stackoverflow.com/questions/40031792/…
Website can be served through a Python program easily by using these 2 modules:
- http.server (for http)
- socketserver (for TCP port)
Here is an example of working code:
# File name: web-server-demo.py
import http.server
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving the website at port # ", PORT)
httpd.serve_forever()
Sample index.html file:
<!DOCTYPE html>
<html>
<head>
<title>Website served by Python</title>
</head>
<bod>
<div>
<h1>Website served by Python program</h2>
</div>
</body>
</html>
Output:
> python web-server-demo.py
serving the website at port # 8080
127.0.0.1 - - [25/May/2020 14:19:27] "GET / HTTP/1.1" 304 -
1 Comment
Gopinath
More information: tutorialspoint.com/python_network_programming/…
