Ejemplo n.º 1
0
    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 = {
            403: '403 Forbidden',
            404: '404 Not Found',
            500: '500 Server Error'
        }[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
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
    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
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
from pyroutes import route, settings, application
from pyroutes.http.response import Response
from pyroutes.template import TemplateRenderer
import memcache
import simplejson
import urllib

tr = TemplateRenderer()
cache = memcache.Client(servers=['127.0.0.1:11211'])


@route('/')
def index(request):
    fml_endpoint = 'http://graph.facebook.com/search?q="so%20starving&type=post'
    fb_data = cache.get(fml_endpoint)
    if not fb_data:
        fb_response = urllib.urlopen(fml_endpoint).read()
        fb_data = simplejson.loads(fb_response)['data']
        cache.set(fml_endpoint, fb_data)
    return Response(
        tr.render(
            'base.xml', {
                'ul': [{
                    'li': {
                        '#picture': {
                            'img/src':
                            'https://graph.facebook.com/%s/picture' %
                            post['from']['id']
                        },
                        '#message': {
                            '#msg': post['message'],
Ejemplo n.º 9
0
#!/usr/bin/env python
# encoding: utf-8
"""
Small wiki example using pyroutes.
"""

from pyroutes import route, application, utils
from pyroutes.http.response import Response, Redirect
from pyroutes.template import TemplateRenderer

renderer = TemplateRenderer("templates/base.xml")
nodes = {}


@route('/')
def main(request):
    return Redirect('/show/index')


@route('/edit')
def edit(request, node):
    if 'new_node_data' in request.POST:
        nodes[node] = request.POST['new_node_data']
        return Redirect('/show/%s' % node)

    template_data = {
        # XML-Template will remove the textarea node if None
        '#edit_contents': nodes.get(node) or '',
        '#edit_form/action': '/edit/%s' % node,
    }
    return Response(renderer.render("templates/edit.xml", template_data),
Ejemplo n.º 10
0
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)