Created
April 2, 2017 20:43
-
-
Save arthur17/1ed7690e32ead5b7eaa9ac4b7bea0a8a to your computer and use it in GitHub Desktop.
Simple static file handler for Falcon
This file contains hidden or 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 falcon | |
| import mimetypes | |
| import os.path | |
| from falcon.request import Request | |
| from falcon.response import Response | |
| # simple static file handler for falcon | |
| # it is recommended to use a program like nginx to handle static files | |
| # however this is useful for development and when performance is not a priority | |
| class StaticHandler: | |
| def __init__(self, directory_index: [str] = None): | |
| self.directory_index = directory_index or ['index.html', 'index.htm'] | |
| self.prefix = None # type: str | |
| self.static_path = None # type: str | |
| def on_get(self, req: Request, res: Response) -> None: | |
| # should always start with prefix | |
| # if not req.path.startswith(self.prefix): return | |
| # remove prefix from path and remove leading / if possible | |
| file = req.path[len(self.prefix):] | |
| if len(file) > 0 and file.startswith('/'): file = file[1:] | |
| # join static path and file path | |
| file = os.path.join(self.static_path, file) | |
| file = os.path.abspath(file) | |
| # do not allow to use paths on the top level of self.static_path | |
| # this prevents using urls such as http://127.0.0.1:8080/../package.json | |
| if not file.startswith(self.static_path): | |
| res.status = falcon.HTTP_403 | |
| return | |
| # if file is a directory try to guess index name | |
| if os.path.isdir(file): | |
| initial_file = file | |
| for index_file in self.directory_index: | |
| tmp = os.path.join(file, index_file) | |
| if os.path.isfile(tmp): | |
| file = tmp | |
| break | |
| # if file has not changed return 404 | |
| if initial_file == file: | |
| res.status = falcon.HTTP_404 | |
| return | |
| # get type and encoding from current filename | |
| t, e = mimetypes.guess_type(file) | |
| if t is not None: res.content_type = t | |
| # try to return file | |
| try: | |
| with open(file, 'rb') as f: | |
| res.body = f.read() | |
| # if error happened print error and return 404 | |
| except FileNotFoundError as e: | |
| print(e) | |
| res.status = falcon.HTTP_404 | |
| def enable(self, api: falcon.API, prefix: str, static_path: str) -> None: | |
| self.prefix = prefix | |
| self.static_path = static_path | |
| api.add_sink(self.on_get, self.prefix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This worked as long as I commented out lines 31-33.