Пример #1
0
 def __call__(self, environ, start_response):
     path = environ['PATH_INFO']
     normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
     absolute_path = self.finders.find(normalized_path)
     if not absolute_path:
         print(('Static file %s does not exist' % path))
         start_response('404 NotFound', [])
         return ['']
     else:
         return static.FileApp(absolute_path)(environ, start_response)
Пример #2
0
    def test_allowed_methods(self):
        app = static.FileApp(self.tempfile)

        # Alias
        resp = lambda method: get_response(app, method=method)

        self.assertEqual(200, resp(method='GET').status_code)
        self.assertEqual(200, resp(method='HEAD').status_code)
        self.assertEqual(405, resp(method='POST').status_code)
        # Actually any other method is not allowed
        self.assertEqual(405, resp(method='xxx').status_code)
Пример #3
0
    def test_allowed_methods(self):
        app = static.FileApp(self.tempfile)

        # Alias
        def resp(method):
            return get_response(app, method=method)

        self.assertEqual(200, resp(method="GET").status_code)
        self.assertEqual(200, resp(method="HEAD").status_code)
        self.assertEqual(405, resp(method="POST").status_code)
        # Actually any other method is not allowed
        self.assertEqual(405, resp(method="xxx").status_code)
Пример #4
0
    def test_use_wsgi_filewrapper(self):
        class TestWrapper(object):
            def __init__(self, file, block_size):
                self.file = file
                self.block_size = block_size

        environ = environ_from_url('/')
        environ['wsgi.file_wrapper'] = TestWrapper
        app = static.FileApp(self.tempfile)
        app_iter = Request(environ).get_response(app).app_iter

        self.assertTrue(isinstance(app_iter, TestWrapper))
        self.assertEqual(bytes_('import this\n'), app_iter.file.read())
        self.assertEqual(static.BLOCK_SIZE, app_iter.block_size)
Пример #5
0
    def test_exception_while_opening_file(self):
        # Mock the built-in ``open()`` function to allow finner control about
        # what we are testing.
        def open_ioerror(*args, **kwargs):
            raise IOError()

        def open_oserror(*args, **kwargs):
            raise OSError()

        app = static.FileApp(self.tempfile)

        app._open = open_ioerror
        self.assertEqual(403, get_response(app).status_code)

        app._open = open_oserror
        self.assertEqual(403, get_response(app).status_code)
Пример #6
0
    def test_use_wsgi_filewrapper(self):
        class TestWrapper:
            __slots__ = ("file", "block_size")

            def __init__(self, file, block_size):
                self.file = file
                self.block_size = block_size

        environ = environ_from_url("/")
        environ["wsgi.file_wrapper"] = TestWrapper
        app = static.FileApp(self.tempfile)
        app_iter = Request(environ).get_response(app).app_iter

        self.assertTrue(isinstance(app_iter, TestWrapper))
        self.assertEqual(bytes_("import this\n"), app_iter.file.read())
        self.assertEqual(static.BLOCK_SIZE, app_iter.block_size)
Пример #7
0
    def test_fileapp(self):
        app = static.FileApp(self.tempfile)
        resp1 = get_response(app)
        self.assertEqual(resp1.content_type, 'text/x-python')
        self.assertEqual(resp1.charset, 'UTF-8')
        self.assertEqual(resp1.last_modified.timetuple(),
                         gmtime(getmtime(self.tempfile)))

        resp2 = get_response(app)
        self.assertEqual(resp2.content_type, 'text/x-python')
        self.assertEqual(resp2.last_modified.timetuple(),
                         gmtime(getmtime(self.tempfile)))

        resp3 = get_response(app, range=(7, 11))
        self.assertEqual(resp3.status_code, 206)
        self.assertEqual(tuple(resp3.content_range)[:2], (7, 11))
        self.assertEqual(resp3.last_modified.timetuple(),
                         gmtime(getmtime(self.tempfile)))
        self.assertEqual(resp3.body, bytes_('this'))
Пример #8
0
    def test_fileapp(self):
        app = static.FileApp(self.tempfile)
        resp1 = get_response(app)
        assert resp1.content_type in ("text/x-python", "text/plain")
        self.assertEqual(resp1.charset, "UTF-8")
        self.assertEqual(resp1.last_modified.timetuple(),
                         gmtime(getmtime(self.tempfile)))
        self.assertEqual(resp1.body, b"import this\n")

        resp2 = get_response(app)
        assert resp2.content_type in ("text/x-python", "text/plain")
        self.assertEqual(resp2.last_modified.timetuple(),
                         gmtime(getmtime(self.tempfile)))
        self.assertEqual(resp2.body, b"import this\n")

        resp3 = get_response(app, range=(7, 11))
        self.assertEqual(resp3.status_code, 206)
        self.assertEqual(tuple(resp3.content_range)[:2], (7, 11))
        self.assertEqual(resp3.last_modified.timetuple(),
                         gmtime(getmtime(self.tempfile)))
        self.assertEqual(resp3.body, bytes_("this"))
Пример #9
0
def serve_static(context, request):
    path = context.resource_path()
    if not path:
        raise HTTPNotFound()

    settings = request.app.settings.__dict__
    max_age = int(settings.get('caching', {}).get('max-age', (60 * 60)))

    etag = request.headers.get('If-None-Match', '')

    def add_headers(response):
        response.headers.add('Cache-Control', 'public, max-age=%s' % max_age)
        response.headers.add('Expires', (
            datetime.utcnow() +
            timedelta(seconds=max_age)).strftime(r'%a, %d %b %Y %H:%M:%S GMT'))
        response.headers.add('ETag', ETAG)

    if etag and etag == ETAG:

        @request.after
        def add_notmodified_headers(response):
            add_headers(response)

        return morepath.Response(status=304)

    resp = request.get_response(static.FileApp(path))
    if resp.status_code == 404:
        raise HTTPNotFound()
    if resp.status_code == 403:
        raise HTTPUnauthorized()

    @request.after
    def add_caching_headers(response):
        add_headers(response)

    return resp
Пример #10
0
 def test_unexisting_file(self):
     app = static.FileApp("/tmp/this/doesnt/exist")
     self.assertEqual(404, get_response(app).status_code)
Пример #11
0
 def static_file(self, fname):
     file_app = static.FileApp(os.path.join(self.static_dir(), fname))
     self.response = self.request.get_response(file_app)
     raise Interrupt()
Пример #12
0
def serve_deformstatic(context, request):
    path = resource_filename('deform', 'static')
    return request.get_response(
        static.FileApp(os.path.join(path, context.path)))
Пример #13
0
def serve_static(context, request):
    path = os.path.join(os.path.dirname(__file__), 'static_files')
    return request.get_response(
        static.FileApp(os.path.join(path, context.path)))