EDIT: extended source code in Simple CGI Server with CGI scripts in different languages.
I have structure: (all code is at the end)
project
├── cgi-bin
│ └── image.py
├── image.png
├── index.html
└── server.py
and I run ./server.py
(or python3 server.py
)
CGI server can serve images without extra code. You can try
http://localhost:8000/image.png
Or put tag in HTML (ie. in index.html
)
< img src="/image.png" >
and run
http://localhost:8000/index.html
If you need dynamically created image then create folder cgi-bin
with script ie. image.py
(on Linux you have to set execution attribute chmod +x image.py
)
And then you can run this script directly
http://localhost:8000/cgi-bin/image.py
or in HTML
< img src="/cgi-bin/image.py" >
server.py
#!/usr/bin/env python3
from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8000)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
cgi-bin/image.py
#!/usr/bin/env python3
import sys
import os
src = "image.png"
length = os.stat(src).st_size
sys.stdout.write("Content-Type: image/png\n")
sys.stdout.write("Content-Length: " + str(length) + "\n")
sys.stdout.write("\n")
sys.stdout.flush()
sys.stdout.buffer.write(open(src, "rb").read())
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Index</title>
</head>
<body>
<h1>image.png</h1>
<img src="/image.png">
<h1>cgi-bin/image.py</h1>
<img src="/cgi-bin/image.py">
</body>
</html>
image.png
