Skip to content

Instantly share code, notes, and snippets.

@href href/
Last active Aug 29, 2015

What would you like to do?
Neatly Serve Static Files with Morepath
import inspect
import morepath
import os
from webob import static
class App(morepath.App):
def static_files(self):
app_path = os.path.dirname(inspect.getfile(self.__class__))
return os.path.join(app_path, 'static')
class StaticFile(object):
def __init__(self, path):
self.path = path
def render_path(content, request):
return request.get_response(static.FileApp(content))
def is_subpath(directory, path):
directory = os.path.join(os.path.realpath(directory), '')
path = os.path.realpath(path)
# return true, if the common prefix of both is equal to directory
# e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
return os.path.commonprefix([path, directory]) == directory
@App.path(model=StaticFile, path='/static', absorb=True)
def get_static_file(app, absorb):
# be sure not to fall for a file path injection vulnerability
if is_subpath(app.static_files, absorb):
return StaticFile(os.path.join(app.static_files, absorb))
@App.view(model=StaticFile, render=render_path)
def view_static_file(self, request):
return self.path
if __name__ == '__main__':
config = morepath.setup()
if not os.path.exists('./static'):
with open('./static/hello.txt', 'w') as f:
f.write('hello world') # open http://localhost:5000/static/hello.txt after this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.