class HttpException(Exception): def __init__(self): if not hasattr(self, 'code'): raise TypeError('You tried to instanciate HttpException. ' \ + 'Please, only create instances of Http{403,404,500}.') self.template_variable = 'TEMPLATE_%d' % self.code self.template_filename = '%d.xml' % self.code self.status_code = "%d %s" % (self.code, responses[self.code]) if hasattr(settings, self.template_variable): if hasattr(settings, 'CUSTOM_BASE_TEMPLATE'): self.templaterenderer = TemplateRenderer( settings.CUSTOM_BASE_TEMPLATE ) else: self.templaterenderer = TemplateRenderer() self.template = getattr(settings, self.template_variable) else: self.templaterenderer = TemplateRenderer( settings.BUILTIN_BASE_TEMPLATE, template_dir=settings.BUILTIN_TEMPLATES_DIR ) self.template = self.template_filename def get_response(self, path, **kwargs): template_data = { 'request': path, 'title': self.status_code } template_data.update(kwargs) document = self.templaterenderer.render(self.template, template_data) return Response(document, status_code=self.status_code)
class HttpException(Exception): def __init__(self): if not hasattr(self, 'code'): raise TypeError('You tried to instanciate HttpException. ' \ + 'Please, only create instances of Http{403,404,500}.') self.template_variable = 'TEMPLATE_%d' % self.code self.template_filename = '%d.xml' % self.code self.status_code = "%d %s" % (self.code, responses[self.code]) if hasattr(settings, self.template_variable): if hasattr(settings, 'CUSTOM_BASE_TEMPLATE'): self.templaterenderer = TemplateRenderer( settings.CUSTOM_BASE_TEMPLATE) else: self.templaterenderer = TemplateRenderer() self.template = getattr(settings, self.template_variable) else: self.templaterenderer = TemplateRenderer( settings.BUILTIN_BASE_TEMPLATE, template_dir=settings.BUILTIN_TEMPLATES_DIR) self.template = self.template_filename def get_response(self, path, **kwargs): template_data = {'request': path, 'title': self.status_code} template_data.update(kwargs) document = self.templaterenderer.render(self.template, template_data) return Response(document, status_code=self.status_code)
class HttpException(Exception): """ HttpException objects are to be used by end users to facilitate returning HTTP 403, 404 and 500 pages with standard documents. Use e.g. settings.TEMPLATE_403 to override the document for HTTP 403. """ def __init__(self, template_data=None): super(HttpException, self).__init__() if not hasattr(self, 'code'): raise TypeError('You tried to instanciate HttpException. ' + 'Please, only create instances of Http{403,404,500}.') self.template_data = template_data self.template_variable = 'TEMPLATE_%d' % self.code self.template_filename = '%d.xml' % self.code self.status_code = "%d %s" % (self.code, _RESPONSES[self.code]) if hasattr(settings, self.template_variable): self.templaterenderer = TemplateRenderer( getattr(settings, 'CUSTOM_BASE_TEMPLATE', None) ) self.template = getattr(settings, self.template_variable) else: self.templaterenderer = TemplateRenderer( settings.BUILTIN_BASE_TEMPLATE, template_dir=settings.BUILTIN_TEMPLATES_DIR ) self.template = self.template_filename def get_response(self, path, **kwargs): """ Returns a formatted page displaying the error to user """ template_data = { 'request': path, 'title': self.status_code } template_data.update(self.template_data or {}) template_data.update(kwargs) document = self.templaterenderer.render(self.template, template_data) return Response(document, status_code=self.status_code)
def fileserver(request): """ Simple file server for development servers. Not for use in production environments. Typical usage:: from pyroutes import route, utils route('/media')(utils.fileserver) That will add the fileserver to the route /media. If DEV_MEDIA_BASE is defined in settings, host files from this folder. Otherwise, use current working directory. .. note:: DEV_MEDIA_BASE and route path is concatenated, i.e. if you use '/srv/media' for as the media base, and map the route to '/files', all files will be looked for in '/srv/media/files' """ path = request.ENV['PATH_INFO'] path_list = path.lstrip('/').split('/') # Do not expose entire file system if '..' in path_list: raise Http404 if hasattr(settings, 'DEV_MEDIA_BASE'): path = os.path.join(settings.DEV_MEDIA_BASE, *path_list) else: path = os.path.join('.', *path_list) if not os.path.exists(path): raise Http404 if not os.access(path, os.R_OK): raise Http403 modified = datetime.datetime.fromtimestamp(os.path.getmtime(path)) if 'HTTP_IF_MODIFIED_SINCE' in request.ENV: modified = datetime.datetime.strftime(modified, "%a, %d %b %Y %H:%M:%S") if request.ENV.get('HTTP_IF_MODIFIED_SINCE') == modified: return Response(status_code='304 Not Modified', default_content_header=False) modified = datetime.datetime.strftime(modified, "%a, %d %b %Y %H:%M:%S") headers = [ ('Last-Modified', modified), ] if os.path.isdir(path): if not path.endswith('/'): return Redirect(path + '/') listing = [] files = [] for entry in sorted(os.listdir(path)): if os.path.isdir(os.path.join(path, entry)): listing.append({'li': {'a': entry + "/", 'a/href': entry + "/"}}) else: files.append({'li': {'a': entry, 'a/href': entry}}) # Done to list folders before files listing += files template_data = { 'file_list': listing, 'title': 'Listing of %s' % path } templaterenderer = TemplateRenderer( settings.BUILTIN_BASE_TEMPLATE, template_dir=settings.BUILTIN_TEMPLATES_DIR ) return Response( templaterenderer.render( os.path.join('fileserver', 'directory_listing.xml'), template_data ), headers ) contenttype = mimetypes.guess_type(path)[0] or "application/octet-stream" file_to_send = FileWrapper(open(path)) size = os.path.getsize(path) headers.append(('Content-Type', contenttype)) headers.append(('Content-Length', str(size))) return Response(file_to_send, headers=headers)
def fileserver(request): """ Simple file server for development servers. Not for use in production environments. Typical usage:: from pyroutes import route, utils route('/media')(utils.fileserver) That will add the fileserver to the route /media. If DEV_MEDIA_BASE is defined in settings, host files from this folder. Otherwise, use current working directory. .. note:: DEV_MEDIA_BASE and route path is concatenated, i.e. if you use '/srv/media' for as the media base, and map the route to '/files', all files will be looked for in '/srv/media/files' """ path = request.ENV['PATH_INFO'] path_list = path.lstrip('/').split('/') # Do not expose entire file system if '..' in path_list: raise Http404 if hasattr(settings, 'DEV_MEDIA_BASE'): path = os.path.join(settings.DEV_MEDIA_BASE, *path_list) else: path = os.path.join('.', *path_list) if not os.path.exists(path): raise Http404 if not os.access(path, os.R_OK): raise Http403 modified = datetime.datetime.fromtimestamp(os.path.getmtime(path)) if 'HTTP_IF_MODIFIED_SINCE' in request.ENV: modified = datetime.datetime.strftime(modified, "%a, %d %b %Y %H:%M:%S") if request.ENV.get('HTTP_IF_MODIFIED_SINCE') == modified: return Response(status_code='304 Not Modified', default_content_header=False) modified = datetime.datetime.strftime(modified, "%a, %d %b %Y %H:%M:%S") headers = [ ('Last-Modified', modified), ] if os.path.isdir(path): if not path.endswith('/'): return Redirect(path + '/') listing = [] files = [] for entry in sorted(os.listdir(path)): if os.path.isdir(os.path.join(path, entry)): listing.append( {'li': { 'a': entry + "/", 'a/href': entry + "/" }}) else: files.append({'li': {'a': entry, 'a/href': entry}}) # Done to list folders before files listing += files template_data = {'file_list': listing, 'title': 'Listing of %s' % path} templaterenderer = TemplateRenderer( settings.BUILTIN_BASE_TEMPLATE, template_dir=settings.BUILTIN_TEMPLATES_DIR) return Response( templaterenderer.render( os.path.join('fileserver', 'directory_listing.xml'), template_data), headers) contenttype = mimetypes.guess_type(path)[0] or "application/octet-stream" file_to_send = FileWrapper(open(path)) size = os.path.getsize(path) headers.append(('Content-Type', contenttype)) headers.append(('Content-Length', str(size))) return Response(file_to_send, headers=headers)