[Twisted-Python] Serving files, again
Mario Ruggier
mario at ruggier.org
Tue Feb 25 18:48:31 EST 2003
Hi,
i had hacked the rpy below, to serve files (those specified by the left
over part of the url,
and rooted on a hard-wired rootdir on the system) following the
suggestions of
this list, picking from the example bits, and salvaging whatever ideas
I can
from the docs. However the mental model i'd like to form is still very
murky...
After Clark's post from yesterday, I tried to redo this in the "proper"
way,
i.e. using putChild. However, the best i could get was
"Request did not return a string", when trying putChild and getChild
as the content of the render() method below (with isLeaf=0).
Would anyone be able to clarify what the render() method should be
such that the url http://host/docs/some/file.txt will return the file
at system location of: /Path/To/Somewhere/some/file.txt ?
Oh, and in general, how does one turn off directory browsing
for a twisted.web server?
Thanks, mario
############################
# docs.rpy
from twisted.protocols import http
from twisted.web import resource, error
import os
###
docsBase = '/Path/To/Somewhere'
serveFileTypes = ['','.txt','.pdf','.gif']
###
class RestrictedResource(resource.Resource):
def isLeaf(self):
return 1
def render(self, request):
# a few var used in blocks below
subPath = '/'.join(request.postpath)
fullPath = docsBase +'/'+ subPath
rootPath = '/docs/'+subPath
if not len(subPath):
rootPath = '/docs'+subPath # otherwise get double slash
(when postpath is zero length)
dirlist = []
# build list or return file
try:
if not os.path.exists(fullPath):
raise Exception # of type...
elif os.path.isdir(fullPath):
dirlist = processDirlist(os.listdir(fullPath))
elif os.path.isfile(fullPath):
import mimetypes
mimetype = mimetypes.guess_type(fullPath)[0]
if not mimetype:
mimetype = 'text/plain' # fallback
request.setHeader("content-type", mimetype)
try:
f = open(fullPath)
return f.read()
finally:
f.close()
else:
raise Exception # of type..
except:
errpage = error.ErrorPage(http.NOT_FOUND,"Not
Found",rootPath)
return errpage.render(request)
# response string
s = '<ul>'
for file in dirlist:
s += '<li><a href="%s">%s</li>' % ( rootPath+'/'+file, file
)
s += '</ul>'
title = 'Directory listing for ' + rootPath
return
'''<html><head><title>%s</title></head><body><h1>%s</h1>%s</body></
html>''' % (title,title,s)
###
resource = RestrictedResource()
###
def processDirlist(dirlist):
dl = []
for filename in dirlist:
(name, suffix) = os.path.splitext(filename)
if suffix in serveFileTypes:
dl.append(filename)
return dl
###
More information about the Twisted-Python
mailing list