| #!/usr/bin/env python | |
| """ | |
| Very simple HTTP server in python (Updated for Python 3.7) | |
| Usage: | |
| ./dummy-web-server.py -h | |
| ./dummy-web-server.py -l localhost -p 8000 | |
| Send a GET request: | |
| curl http://localhost:8000 | |
| Send a HEAD request: | |
| curl -I http://localhost:8000 | |
| Send a POST request: | |
| curl -d "foo=bar&bin=baz" http://localhost:8000 | |
| """ | |
| import argparse | |
| from http.server import HTTPServer, BaseHTTPRequestHandler | |
| class S(BaseHTTPRequestHandler): | |
| def _set_headers(self): | |
| self.send_response(200) | |
| self.send_header("Content-type", "text/html") | |
| self.end_headers() | |
| def _html(self, message): | |
| """This just generates an HTML document that includes `message` | |
| in the body. Override, or re-write this do do more interesting stuff. | |
| """ | |
| content = f"<html><body><h1>{message}</h1></body></html>" | |
| return content.encode("utf8") # NOTE: must return a bytes object! | |
| def do_GET(self): | |
| self._set_headers() | |
| self.wfile.write(self._html("hi!")) | |
| def do_HEAD(self): | |
| self._set_headers() | |
| def do_POST(self): | |
| # Doesn't do anything with posted data | |
| self._set_headers() | |
| self.wfile.write(self._html("POST!")) | |
| def run(server_class=HTTPServer, handler_class=S, addr="localhost", port=8000): | |
| server_address = (addr, port) | |
| httpd = server_class(server_address, handler_class) | |
| print(f"Starting httpd server on {addr}:{port}") | |
| httpd.serve_forever() | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Run a simple HTTP server") | |
| parser.add_argument( | |
| "-l", | |
| "--listen", | |
| default="localhost", | |
| help="Specify the IP address on which the server listens", | |
| ) | |
| parser.add_argument( | |
| "-p", | |
| "--port", | |
| type=int, | |
| default=8000, | |
| help="Specify the port on which the server listens", | |
| ) | |
| args = parser.parse_args() | |
| run(addr=args.listen, port=args.port) |
This comment has been minimized.
This comment has been minimized.
dneyirp
commented
Aug 8, 2016
|
No |
This comment has been minimized.
This comment has been minimized.
dneyirp
commented
Aug 8, 2016
|
Nice project. Just one thing to add to it, if you want access to the POSTed data you do so like this: def do_POST(self):
# Doesn't do anything with posted data
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
self._set_headers()
self.wfile.write("<html><body><h1>POST!</h1></body></html>") |
This comment has been minimized.
This comment has been minimized.
qianguozheng
commented
Aug 26, 2016
|
Great job, this it what I finding, print the post data |
This comment has been minimized.
This comment has been minimized.
arvindsree
commented
Nov 21, 2016
|
Nice |
This comment has been minimized.
This comment has been minimized.
scorpiodawg
commented
Dec 6, 2016
|
Oh, and to print the POSTed data:
|
This comment has been minimized.
This comment has been minimized.
pincioc
commented
Jan 6, 2017
|
This comment has been minimized.
This comment has been minimized.
ml693
commented
Feb 4, 2017
|
Nice, I would welcome very much if someone could answer the following: suppose I post .txt file to this server. How to make server save this file in its local directory? |
This comment has been minimized.
This comment has been minimized.
tarvos21
commented
Mar 15, 2017
•
|
Great script, thanks! Is there a Python3 version? |
This comment has been minimized.
This comment has been minimized.
ghost
commented
Apr 12, 2017
•
|
just stumbled in here by google result. That one works 4 me in python3
|
This comment has been minimized.
This comment has been minimized.
vmrekhate
commented
Apr 21, 2017
|
Any help to make this work for HTTPS as well? |
This comment has been minimized.
This comment has been minimized.
parijatmukherjee
commented
May 30, 2017
|
Thanks a lot. Saved my couple of hours :) |
This comment has been minimized.
This comment has been minimized.
tkavitharaj
commented
Jun 25, 2017
|
Thanks for the code. |
This comment has been minimized.
This comment has been minimized.
AnnaPanov
commented
Jul 28, 2017
•
|
to make it work in python 3, the imports should be:
, and do_GET + do_POST change into:
|
This comment has been minimized.
This comment has been minimized.
bmcculley
commented
Aug 16, 2017
|
my forked version works on both python 2 and 3 |
This comment has been minimized.
This comment has been minimized.
hgfeaon
commented
Aug 30, 2017
|
useful for debugging the HTTP client & proxy on a raw machine |
This comment has been minimized.
This comment has been minimized.
f41ardu
commented
Sep 8, 2017
•
|
Nice script following the KISS principle. But I tried to process incoming data using i.e. matplotlib and this still didn't work. Update: Code works fine on my Raspberry but not on my Windows 8.1 PC. |
This comment has been minimized.
This comment has been minimized.
j796160836
commented
Sep 26, 2017
|
Nice script! That is exactly what I want. Thanks. |
This comment has been minimized.
This comment has been minimized.
TheNilesh
commented
Oct 9, 2017
|
How to return headers and http response code in response ? |
This comment has been minimized.
This comment has been minimized.
psankar
commented
Oct 12, 2017
|
@6f0 Your link is broken. |
This comment has been minimized.
This comment has been minimized.
soulfly
commented
Oct 23, 2017
|
This is actually awesome, thank you! |
This comment has been minimized.
This comment has been minimized.
ArrrNeo
commented
Nov 27, 2017
|
this is exactly what I needed... i was able to complete a home project of mine with this, thanks :) |
This comment has been minimized.
This comment has been minimized.
lily524
commented
Nov 28, 2017
|
both python 2 and 3 works for me. Many thanks. |
This comment has been minimized.
This comment has been minimized.
pspangler
commented
Dec 3, 2017
|
Great simple utility here. Very helpful! |
This comment has been minimized.
This comment has been minimized.
HelloTan
commented
Dec 31, 2017
|
self.__http_response = self.__http.getresponse()
AttributeError: HTTPS instance has no attribute 'getresponse' How to fix python2.7?? in thttpclient.py |
This comment has been minimized.
This comment has been minimized.
lukapaunovic
commented
Jan 14, 2018
|
This is USEFUL! :) |
This comment has been minimized.
This comment has been minimized.
reillychase
commented
Apr 20, 2018
|
HTTPS support? |
This comment has been minimized.
This comment has been minimized.
Auto-Rooter
commented
May 30, 2018
|
Thanks a lot, very helpful |
This comment has been minimized.
This comment has been minimized.
emrekgn
commented
Jun 4, 2018
|
This is very helpful, thanks! For anyone interested, note that |
This comment has been minimized.
This comment has been minimized.
NilatGitHub
commented
Jun 19, 2018
|
Hi Guys, class MyHandler(BaseHTTPRequestHandler):
self.serve_forever() #default is 0.5 2 sec
|
This comment has been minimized.
This comment has been minimized.
nikitaKravchenko
commented
Jul 18, 2018
|
Thank you, it is useful. |
This comment has been minimized.
This comment has been minimized.
jharitesh108
commented
Aug 1, 2018
|
thank you. |
This comment has been minimized.
This comment has been minimized.
Terkwood
commented
Aug 19, 2018
|
Thanks! |
This comment has been minimized.
This comment has been minimized.
denzenin
commented
Nov 2, 2018
|
Brad, thanks you! Also I am using Python 3.7 and the following corrections were needed for provided snippet to work properly:
|
This comment has been minimized.
This comment has been minimized.
prabindh
commented
Feb 2, 2019
|
For testing POST, if encountering Need to use curl as below: |
This comment has been minimized.
This comment has been minimized.
jsdevtom
commented
May 9, 2019
It works for me without this import with python 2.7... |
This comment has been minimized.
This comment has been minimized.
drjoms
commented
May 16, 2019
|
I take it's python 2.7, as print function doesn't use square brackets and: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer Any chance thsi wil lbe made in version 3? |
This comment has been minimized.
This comment has been minimized.
drjoms
commented
May 16, 2019
|
also, please mark code as 2.* version of python somewhere in title. |
This comment has been minimized.
This comment has been minimized.
gotev
commented
Sep 27, 2019
|
Used this as a base for a static JSON File Server in Python 3.7. Files are a in a sub directory called #!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
base_path = os.path.dirname(__file__)
class StaticServer(BaseHTTPRequestHandler):
def execute_request(self):
filename = 'cached-responses' + self.path + '.json'
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
with open(os.path.join(base_path, filename), 'rb') as fh:
self.wfile.write(fh.read())
def do_POST(self):
self.execute_request()
def do_GET(self):
self.execute_request()
def run(server_class=HTTPServer, handler_class=StaticServer, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting Server on port {}'.format(port))
httpd.serve_forever()
run() |
This comment has been minimized.
This comment has been minimized.
|
I've updated the original post for Python 3.7, and cleaned it up a bit. Hope this continues to be useful |
This comment has been minimized.
This comment has been minimized.
emccrckn
commented
Sep 27, 2019
|
Good stuff! |
This comment has been minimized.
This comment has been minimized.
joshwlewis
commented
Sep 27, 2019
|
Wow, neat. It even takes CLI arguments! |
This comment has been minimized.
This comment has been minimized.
|
@joshwlewis @emccrckn |
This comment has been minimized.
This comment has been minimized.
sharifulgeo
commented
Sep 28, 2019
|
good start! |
This comment has been minimized.
This comment has been minimized.
cdowns71
commented
Oct 18, 2019
|
Just tumbled into this myself. ! fantastic. |
This comment has been minimized.
This comment has been minimized.
texasStronger
commented
Oct 31, 2019
|
For python 3.7 on windows 10, I had to add decode to the post_data.
|
This comment has been minimized.
mhchia commentedJun 24, 2016
Is
import SocketServerunneeded ?!