Last active
August 29, 2015 14:16
-
-
Save href/a4edb486bfac45521342 to your computer and use it in GitHub Desktop.
Neatly Serve Static Files with Morepath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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