Skip to content

Instantly share code, notes, and snippets.

@href
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save href/a4edb486bfac45521342 to your computer and use it in GitHub Desktop.
Save href/a4edb486bfac45521342 to your computer and use it in GitHub Desktop.
Neatly Serve Static Files with Morepath
import inspect
import morepath
import os
from webob import static
class App(morepath.App):
@property
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()
config.scan()
config.commit()
if not os.path.exists('./static'):
os.mkdir('./static')
with open('./static/hello.txt', 'w') as f:
f.write('hello world')
morepath.run(App()) # 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