dimanche 29 mars 2015

How do I get WSGI.py to serve images in static html fies?

Managing a Python (wsgi)-based site for a nonprofit & for historical reasons want to serve old (static) HTML from one subdomain.


Here is wsgi.py:


(Note that html/css files are in static/ folder, others in a subfolder of static/) (This serves all the text w/ styles applied, but gives the alt text for images)



def application(env, start_response):
# some debugging queries to check what's getting passed in:
if env["QUERY_STRING"] == "env":
start_response('200 OK', [('Content-Type',
'text/html; charset=utf-8')])
return ['<!DOCTYPE html><html><meta charset="utf-8">',
'<title>Environment</title>',
repr(env),
"</html>"]
if env["QUERY_STRING"] == "req":
start_response('200 OK', [('Content-Type',
'text/html; charset=utf-8')])
return ['<!DOCTYPE html><html><meta charset="utf-8">',
'<title>Incoming request dump</title>',
"Scriptname: " + env["SCRIPT_NAME"] + "<br>",
"Pathinfo: " + env["PATH_INFO"] + "<br>",
"Querystring: " + env["QUERY_STRING"] + "<br>",
"</html>"]

# the regular server code (runs OK):
try:
if env["PATH_INFO"] == "/": #root, no trailing '/'
htmlfile = open("static/index.html")
start_response('200 OK', [('Content-Type',
'text/html; charset=utf-8')])
return [htmlfile.read()]
elif env["PATH_INFO"].endswith(".html"):
htmlfile = open("static" + env["PATH_INFO"]) #
start_response('200 OK', [('Content-Type',
'text/html; charset=utf-8')])
return [htmlfile.read()]
elif env["PATH_INFO"].endswith(".css"):
cssfile = open("static" + env["PATH_INFO"]) #
start_response('200 OK', [('Content-Type',
'text/css; charset=utf-8')])
return [cssfile.read()]

# This generates "Internal server error:"
elif env["PATH_INFO"].endswith(".jpg") or
env["PATH_INFO"].endswith(".JPG"):
jpegfile = open("static" + env["PATH_INFO"]) #
jpegdata = jpegfile.read()
start_response('200 OK', [('Content-Type', 'image/jpeg'),
('Accept-Ranges', 'bytes'),
('Content-Length', str(len(jpegdata))),
('Connection', 'close')])
return [jpegdata]
except Exception as e:
return ['<!DOCTYPE html><html><meta charset="utf-8"><title>Oops',
"</title>Can't read file on server!</html>"]


-- AFAICS a WSGI app has to return an iterable containing strings; images are bytes objects, but the server is running Python 2.7, & 'bytes' is an alias for 'string' -- so that shouldn't be a problem. I can't find any info on encoding in this situation, & HTTP handles octets. I've tried all sorts of variations & Googled (R) this for days, but still stuck. How do I get this silly thing to serve an image?


Aucun commentaire:

Enregistrer un commentaire