-
-
Save Spuffynism/0806ccbc9add92b0e17d82ca419dd76a to your computer and use it in GitHub Desktop.
A minimal http server in python. Responds to GET and POST requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Very simple HTTP server. | |
Upon a GET or POST request, returns a json object with the route of the request | |
and the data of the request body. | |
""" | |
import socket | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import time | |
import json | |
hostName = '' | |
hostPort = 80 | |
class MyServer(BaseHTTPRequestHandler): | |
def do_GET(self): | |
self.respond('GET') | |
def do_POST(self): | |
content_length = int(self.headers.get('Content-Length')) | |
post_data = self.rfile.read(content_length) | |
self.respond('POST', json.loads(str(post_data, 'utf-8'))) | |
def respond(self, verb, data=None): | |
self.send_response(200) | |
self.send_header('Content-Type', 'application/json; charset=utf-8') | |
self.end_headers() | |
response = { | |
'route': "%s %s" % (verb, self.path), | |
} | |
if data != None: | |
response['data'] = data | |
self.wfile.write(bytes(json.dumps(response), 'utf-8')) | |
myServer = HTTPServer((hostName, hostPort), MyServer) | |
print(time.asctime(), "Server started - %s:%s" % (hostName, hostPort)) | |
try: | |
myServer.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
myServer.server_close() | |
print(time.asctime(), "Server stopped - %s:%s" % (hostName, hostPort)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, how could I load files with this server?