Mercurial > hg > GlobalNeighbors
diff globalneighbors/web.py @ 10:21ed15391e8a
add a placeholder view for a city based on geoid
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sun, 25 Jun 2017 12:28:36 -0700 |
parents | 254195d0bac2 |
children | d1b99c695511 |
line wrap: on
line diff
--- a/globalneighbors/web.py Sun Jun 25 11:37:52 2017 -0700 +++ b/globalneighbors/web.py Sun Jun 25 12:28:36 2017 -0700 @@ -21,6 +21,29 @@ from .template import template_dir from .template import TemplateLoader +here = os.path.dirname(os.path.abspath(__file__)) +static_dir = os.path.join(here, 'static') + + +class PassthroughFileserver(object): + + """serve files if they exist""" + + + def __init__(self, app, directory=static_dir): + self.app = app + self.directory = directory + self.fileserver = StaticURLParser(self.directory) + + def __call__(self, environ, start_response): + + path = environ['PATH_INFO'].strip('/') + + if path and os.path.exists(os.path.join(self.directory, path)) and '..' not in path: + + return self.fileserver(environ, start_response) + return self.app(environ, start_response) + def autocomplete(cities, startswith=None, limit=None): """autocomplete function for city names""" @@ -64,7 +87,7 @@ def cities(self, startswith=None): """return list of cities""" - return autocomplete(self._cities, + return autocomplete(self._cities.values(), startswith=startswith) def GET(self, request): @@ -87,6 +110,10 @@ fields=fields) self.locations = locations(self.cities) + # convert cities to a dict for lookup + self.cities = {city['geonameid'] : city + for city in self.cities} + # declare handlers self.handlers = {'/cities': CitiesHandler(self.locations, @@ -95,6 +122,7 @@ # template loader self.loader = TemplateLoader(template_dir) self.index = self.loader.load('index.html') + self.citypage = self.loader.load('city.html') def GET(self, request): @@ -102,10 +130,18 @@ # Landing page return Response(content_type=self.content_type, body=self.index.render(n_cities=len(self.cities))) + elif request.path_info in self.handlers: + return request.get_response(self.handlers[request.path_info]) else: - handler = self.handlers.get(request.path_info) - if handler: - return request.get_response(handler) + try: + geoid = int(request.path.strip('/')) + city = self.cities.get(geoid) + if not city: + return + return Response(content_type=self.content_type, + body=self.citypage.render(**city)) + except ValueError: + pass