#!/usr/bin/env python2.4"""static - A stupidly simple WSGI way to serve static (or mixed) content.(See the docstrings of the various functions and classes.)Copyright (C) 2006-2008 Luke Arno - http://lukearno.com/This library is free software; you can redistribute it and/ormodify it under the terms of the GNU Lesser General PublicLicense as published by the Free Software Foundation; eitherversion 2.1 of the License, or (at your option) any later version.This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNULesser General Public License for more details.You should have received a copy of the GNU Lesser General PublicLicense along with this library; if not, write to:The Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.Luke Arno can be found at http://lukearno.com/"""importmimetypesimportrfc822importtimeimportstringimportsysfromosimportpath,statfromwsgirefimportutilfromwsgiref.headersimportHeadersfromwsgiref.simple_serverimportmake_serverfromoptparseimportOptionParsertry:frompkg_resourcesimportresource_filename,Requirementexcept:passtry:importkidexcept:passclassMagicError(Exception):passclassStatusApp:"""Used by WSGI apps to return some HTTP status."""def__init__(self,status,message=None):self.status=statusifmessageisNone:self.message=statuselse:self.message=messagedef__call__(self,environ,start_response,headers=[]):ifself.message:Headers(headers).add_header('Content-type','text/plain')start_response(self.status,headers)ifenviron['REQUEST_METHOD']=='HEAD':return[""]else:return[self.message]classCling(object):"""A stupidly simple way to serve static content via WSGI. Serve the file of the same path as PATH_INFO in self.datadir. Look up the Content-type in self.content_types by extension or use 'text/plain' if the extension is not found. Serve up the contents of the file or delegate to self.not_found. """block_size=16*4096index_file='index.html'not_found=StatusApp('404 Not Found')not_modified=StatusApp('304 Not Modified',"")moved_permanently=StatusApp('301 Moved Permanently')method_not_allowed=StatusApp('405 Method Not Allowed')def__init__(self,root,**kw):"""Just set the root and any other attribs passes via **kw."""self.root=rootfork,vinkw.iteritems():setattr(self,k,v)def__call__(self,environ,start_response):"""Respond to a request when called in the usual WSGI way."""ifenviron['REQUEST_METHOD']notin('GET','HEAD'):headers=[('Allow','GET, HEAD')]returnself.method_not_allowed(environ,start_response,headers)path_info=environ.get('PATH_INFO','')full_path=self._full_path(path_info)ifnotself._is_under_root(full_path):returnself.not_found(environ,start_response)ifpath.isdir(full_path):iffull_path[-1]<>'/'orfull_path==self.root:location=util.request_uri(environ,include_query=False)+'/'ifenviron.get('QUERY_STRING'):location+='?'+environ.get('QUERY_STRING')headers=[('Location',location)]returnself.moved_permanently(environ,start_response,headers)else:full_path=self._full_path(path_info+self.index_file)content_type=self._guess_type(full_path)try:etag,last_modified=self._conditions(full_path,environ)headers=[('Date',rfc822.formatdate(time.time())),('Last-Modified',last_modified),('ETag',etag)]if_modified=environ.get('HTTP_IF_MODIFIED_SINCE')ifif_modifiedand(rfc822.parsedate(if_modified)>=rfc822.parsedate(last_modified)):returnself.not_modified(environ,start_response,headers)if_none=environ.get('HTTP_IF_NONE_MATCH')ifif_noneand(if_none=='*'oretaginif_none):returnself.not_modified(environ,start_response,headers)file_like=self._file_like(full_path)headers.append(('Content-Type',content_type))start_response("200 OK",headers)ifenviron['REQUEST_METHOD']=='GET':returnself._body(full_path,environ,file_like)else:return['']except(IOError,OSError),e:printereturnself.not_found(environ,start_response)def_full_path(self,path_info):"""Return the full path from which to read."""returnself.root+path_infodef_is_under_root(self,full_path):"""Guard against arbitrary file retrieval."""if(path.abspath(full_path)+path.sep)\
.startswith(path.abspath(self.root)+path.sep):returnTrueelse:returnFalsedef_guess_type(self,full_path):"""Guess the mime type using the mimetypes module."""returnmimetypes.guess_type(full_path)[0]or'text/plain'def_conditions(self,full_path,environ):"""Return a tuple of etag, last_modified by mtime from stat."""mtime=stat(full_path).st_mtimereturnstr(mtime),rfc822.formatdate(mtime)def_file_like(self,full_path):"""Return the appropriate file object."""returnopen(full_path,'rb')def_body(self,full_path,environ,file_like):"""Return an iterator over the body of the response."""way_to_send=environ.get('wsgi.file_wrapper',iter_and_close)returnway_to_send(file_like,self.block_size)defiter_and_close(file_like,block_size):"""Yield file contents by block then close the file."""while1:try:block=file_like.read(block_size)ifblock:yieldblockelse:raiseStopIterationexceptStopIteration,si:file_like.close()returndefcling_wrap(package_name,dir_name,**kw):"""Return a Cling that serves from the given package and dir_name. This uses pkg_resources.resource_filename which is not the recommended way, since it extracts the files. I think this works fine unless you have some _very_ serious requirements for static content, in which case you probably shouldn't be serving it through a WSGI app, IMHO. YMMV. """resource=Requirement.parse(package_name)returnCling(resource_filename(resource,dir_name),**kw)classShock(Cling):"""A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you are using Shock with the StringMagic class for instance: shock = Shock('/data', magics=[StringMagic(food='cheese')]) Let's say you have a file called /data/foo.txt.stp containing one line: "I love to eat $food!" When you do a GET on /foo.txt you will see this in your browser: "I love to eat cheese!" This is really nice if you have a color variable in your css files or something trivial like that. It seems silly to create or change a handful of objects for a couple of dynamic bits of text. """magics=()def_match_magic(self,full_path):"""Return the first magic that matches this path or None."""formagicinself.magics:ifmagic.matches(full_path):returnmagicdef_full_path(self,path_info):"""Return the full path from which to read."""full_path=self.root+path_infoifpath.exists(full_path):returnfull_pathelse:formagicinself.magics:ifpath.exists(magic.new_path(full_path)):returnmagic.new_path(full_path)else:returnfull_pathdef_guess_type(self,full_path):"""Guess the mime type magically or using the mimetypes module."""magic=self._match_magic(full_path)ifmagicisnotNone:return(mimetypes.guess_type(magic.old_path(full_path))[0]or'text/plain')else:returnmimetypes.guess_type(full_path)[0]or'text/plain'def_conditions(self,full_path,environ):"""Return Etag and Last-Modified values defaults to now for both."""magic=self._match_magic(full_path)ifmagicisnotNone:returnmagic.conditions(full_path,environ)else:mtime=stat(full_path).st_mtimereturnstr(mtime),rfc822.formatdate(mtime)def_file_like(self,full_path):"""Return the appropriate file object."""magic=self._match_magic(full_path)ifmagicisnotNone:returnmagic.file_like(full_path)else:returnopen(full_path,'rb')def_body(self,full_path,environ,file_like):"""Return an iterator over the body of the response."""magic=self._match_magic(full_path)ifmagicisnotNone:returnmagic.body(environ,file_like)else:way_to_send=environ.get('wsgi.file_wrapper',iter_and_close)returnway_to_send(file_like,self.block_size)classBaseMagic(object):"""Base class for magic file handling. Really a do nothing if you were to use this directly. In a strait forward case you would just override .extension and body(). (See StringMagic in this module for a simple example of subclassing.) In a more complex case you may need to override many or all methods. """extension=''defexists(self,full_path):"""Check that self.new_path(full_path) exists."""ifpath.exists(self.new_path(full_path)):returnself.new_path(full_path)defnew_path(self,full_path):"""Add the self.extension to the path."""returnfull_path+self.extensiondefold_path(self,full_path):"""Remove self.extension from path or raise MagicError."""ifself.matches(full_path):returnfull_path[:-len(self.extension)]else:raiseMagicError,"Path does not match this magic."defmatches(self,full_path):"""Check that path ends with self.extension."""iffull_path.endswith(self.extension):returnfull_pathdefconditions(self,full_path,environ):"""Return Etag and Last-Modified values (based on mtime)."""mtime=int(time.time())returnstr(mtime),rfc822.formatdate(mtime)deffile_like(self,full_path):"""Return a file object for path."""returnopen(full_path,'rb')defbody(self,environ,file_like):"""Return an iterator over the body of the response."""return[file_like.read()]classStringMagic(BaseMagic):"""Magic to replace variables in file contents using string.Template. Using this requires Python2.4. """extension='.stp'safe=Falsedef__init__(self,**variables):"""Keyword arguments populate self.variables."""self.variables=variablesdefbody(self,environ,file_like):"""Pass environ and self.variables in to template. self.variables overrides environ so that suprises in environ don't cause unexpected output if you are passing a value in explicitly. """variables=environ.copy()variables.update(self.variables)template=string.Template(file_like.read())ifself.safeisTrue:return[template.safe_substitute(variables)]else:return[template.substitute(variables)]classKidMagic(StringMagic):"""Like StringMagic only using the Kid templating language. Using this requires Kid: http://kid.lesscode.org/ """extension='.kid'defbody(self,environ,full_path):"""Pass environ and **self.variables into the template."""template=kid.Template(file=full_path,environ=environ,**self.variables)return[template.serialize()]defcommand():parser=OptionParser(usage="%prog DIR [HOST][:][PORT]",version="static 0.3.6")options,args=parser.parse_args()iflen(args)in(1,2):iflen(args)==2:parts=args[1].split(":")iflen(parts)==1:host=parts[0]port=Noneeliflen(parts)==2:host,port=partselse:sys.exit("Invalid host:port specification.")eliflen(args)==1:host,port=None,Noneifnothost:host='0.0.0.0'ifnotport:port=9999try:port=int(port)except:sys.exit("Invalid host:port specification.")app=Cling(args[0])try:make_server(host,port,app).serve_forever()exceptKeyboardInterrupt,ki:print"Cio, baby!"except:sys.exit("Problem initializing server.")else:parser.print_help(sys.stderr)sys.exit(1)deftest():fromwsgiref.validateimportvalidatormagics=StringMagic(title="String Test"),KidMagic(title="Kid Test")app=Shock('testdata/pub',magics=magics)try:make_server('localhost',9999,validator(app)).serve_forever()exceptKeyboardInterrupt,ki:print"Ciao, baby!"if__name__=='__main__':test()