Did I find the right examples for you? yes no      Crawl my project      Python Jobs

All Samples(7)  |  Call(7)  |  Derive(0)  |  Import(0)
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.
(more...)

        def fileserver(request, *path_list):
    """
    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_list = request.matched_path.strip('/').split('/') + list(path_list)

    # Do not expose entire file system
    if '..' in path_list:
        raise Http404

    path = os.path.join(getattr(settings, 'DEV_MEDIA_BASE', '.'), *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))
    modified = datetime.datetime.strftime(modified, "%a, %d %b %Y %H:%M:%S")
    if 'HTTP_IF_MODIFIED_SINCE' in request.ENV:
        if request.ENV.get('HTTP_IF_MODIFIED_SINCE') == modified:
            return Response(status_code='304 Not Modified',
                    default_content_header=False)

    headers = [
        ('Last-Modified', modified),
    ]

    if os.path.isdir(path):
        if not request.ENV['PATH_INFO'].endswith('/'):
            return Redirect(path.lstrip('.') + '/')

        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.lstrip('.')
        }

        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)
        


src/p/y/pyroutes-HEAD/tests/utils_test.py   pyroutes(Download)
    def test_with_custom_settings(self):
        settings.DEV_MEDIA_BASE = '.'
        self.request.ENV['PATH_INFO'] = '/'
        response = utils.fileserver(self.request)
        for dir in [d for d in os.listdir(os.path.abspath(os.path.curdir)) if os.path.isdir(d)]:
 
        self.request.ENV['PATH_INFO'] = '/pyroutes/'
        response = utils.fileserver(self.request, 'pyroutes')
        self.assertTrue(('Last-Modified', modified) in response.headers)
 
        self.request.ENV['HTTP_IF_MODIFIED_SINCE'] = modified
        response = utils.fileserver(self.request, 'pyroutes')
        modified = datetime.strftime(modified, "%a, %d %b %Y %H:%M:%S")
        self.request.ENV['HTTP_IF_MODIFIED_SINCE'] = modified
        response = utils.fileserver(self.request, 'pyroutes')
        self.assertEqual(response.status_code, '200 OK')
 
    def test_redirects(self):
        self.request.ENV['PATH_INFO'] = '/pyroutes'
        response = utils.fileserver(self.request)
        self.assertEqual(response.status_code, '302 Found')