Python

Scripting

python3 -m http.server –help

pi@wordpress:~ $ python3 -m http.server –help
usage: server.py [-h] [–cgi] [–bind ADDRESS] [–directory DIRECTORY] [port]

positional arguments:
  port                  Specify alternate port [default: 8000]

optional arguments:
  -h, –help            show this help message and exit
  –cgi                 Run as CGI Server
  –bind ADDRESS, -b ADDRESS
                        Specify alternate bind address [default: all
                        interfaces]
  –directory DIRECTORY, -d DIRECTORY
                        Specify alternative directory [default:current
                        directory]

python -m http.server 8000 --bind 127.0.0.1

pi@wordpress:~ $ ls
environments
pi@wordpress:~ $ cd environments/
pi@wordpress:~/environments $ source my_env/bin/activate
(my_env) pi@wordpress:~/environments $ ls my_env/
bin  include  lib  pyvenv.cfg  share
(my_env) pi@wordpress:~/environments $ deactivate                                   pi@wordpress:~/environments $

Python3 variant that echoes back the request headers to the sender as response headers and body

serve.py

#!/usr/bin/env python3

from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
import logging
import sys

try:
PORT = int(sys.argv[1])
except:
PORT = 8000

class GetHandler(SimpleHTTPRequestHandler):

def do_GET(self):
self.send_response(200, self.headers)
for h in self.headers:
self.send_header(h, self.headers[h])
self.end_headers()


Handler = GetHandler
httpd = TCPServer(('', PORT), Handler)

httpd.serve_forever()

Usage:

$ python3 serve.py

OR

$ python3 serve.py <PORT>

Sample response from curl:

$ curl -v localhost:8000 -H "Host: blah.com"
* Connected to localhost (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> Host: blah.com
> User-Agent: curl/7.71.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Host: blah.com
< User-Agent: curl/7.71.1
< Accept: */*
<

Server: SimpleHTTP/0.6 Python/3.7.7
Date: Fri, 03 Jul 2020 01:52:09 GMT
Host: blah.com
User-Agent: curl/7.71.1
Accept: */*

* Closing connection 0