Created
April 2, 2014 20:18
-
-
Save r3econ/9942258 to your computer and use it in GitHub Desktop.
HTTP server deamon in Python. Perfect for testing GET/POST requests.
This file contains 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
__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