Last active
February 24, 2016 04:12
-
-
Save oneyoung/36ddecc5a3905f43ed44 to your computer and use it in GitHub Desktop.
Falcon framework: static file handler for debug
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
class StaticFileRes(object): | |
def __init__(self, static_root='.'): | |
self.static_root = os.path.abspath(static_root) | |
def on_get(self, req, resp): | |
path = req.path | |
if path == '/': # handle default page | |
path = '/index.html' | |
full_path = self.static_root + path | |
if os.path.isfile(full_path): | |
import mimetypes | |
filetype = mimetypes.guess_type(full_path, strict=True)[0] | |
if not filetype: | |
filetype = 'text/plain' | |
resp.content_type = filetype | |
resp.status = falcon.HTTP_200 | |
resp.stream_len = os.path.getsize(full_path) | |
resp.stream = open(full_path, 'rb') | |
else: | |
resp.status = falcon.HTTP_404 | |
resp.data = "Not found" | |
# url config | |
# application is what Gunicorn expect | |
api = application = falcon.API(router=router) | |
# let assume all your rest url starts with '/api/' prefix | |
api.add_route('/api/hosts', 'HostsRes()') | |
api.add_route('/api/hosts/{host}', 'HostRes()', name='host') | |
api.add_route('/api/devices/', 'DevicesRes()') | |
# static file handler, debug only | |
# put static root is in 'static/' | |
static_path = os.path.join(os.path.dirname(__file__), 'static') | |
api.add_route('/', StaticFileRes(static_path), name='default') # create a url name 'default' |
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
from falcon.routing import DefaultRouter | |
class ReverseRouter(DefaultRouter): | |
url_map = {} | |
# override add_route to add our map | |
def add_route(self, uri_template, method_map, resource, name=None): | |
if name: | |
self.url_map[name] = uri_template | |
DefaultRouter.add_route(self, uri_template, method_map, resource) | |
def reverse(self, _name, **kwargs): | |
''' | |
reverse url | |
''' | |
# FIXME: should return the full url | |
assert _name in self.url_map, "url name: %s not in url map" % _name | |
url_tmpl = self.url_map.get(_name) | |
return url_tmpl.format(**kwargs) | |
def find(self, uri): | |
ret = DefaultRouter.find(self, uri) | |
if ret == (None, None, None): | |
if not uri.startswith('/api/') and 'default' in self.url_map: | |
default_url = self.reverse('default') | |
return DefaultRouter.find(self, default_url) | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment