Skip to content

Instantly share code, notes, and snippets.

@r3econ
Created April 2, 2014 20:18
Show Gist options
  • Save r3econ/9942258 to your computer and use it in GitHub Desktop.
Save r3econ/9942258 to your computer and use it in GitHub Desktop.
HTTP server deamon in Python. Perfect for testing GET/POST requests.
__author__ = 'Rafał Sroka'
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
# Port on which server will run.
PORT = 8080
class HTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
""" Handle GET Request"""
# Prepend the file name with current dir path.
path = os.getcwd() + self.path
# Check if file exists there.
if os.path.isfile(path):
# Read the file and return its contents.
with open(path) as fileHandle:
# Send headers.
self.send_header('Content-type', 'text/json')
self.send_response(200)
self.end_headers()
# Send file content.
self.wfile.write(fileHandle.read().encode())
# Fail with 404 File Not Found error.
else:
# Send headers with error.
self.send_header('Content-type', 'text/json')
self.send_response(404, 'File Not Found')
self.end_headers()
def do_POST(self):
""" Handle POST Request"""
# Check if path is there.
if self.path:
# Get length of the data and read it.
length = self.headers['content-length']
data = self.rfile.read(int(length))
# Write the data to a file in current dir.
with open(os.getcwd() + self.path, 'w') as file:
file.write(data.decode())
# Send success response.
self.send_header('Content-type', 'text/json')
self.send_response(200, 'OK')
self.end_headers()
if __name__ == '__main__':
HTTPDeamon = HTTPServer(('', PORT), HTTPRequestHandler)
print("Listening at port", PORT)
try:
HTTPDeamon.serve_forever()
except KeyboardInterrupt:
pass
HTTPDeamon.server_close()
print("Server stopped")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment