PyJSONProxy

simple proxy and scraper
git clone https://git.ce9e.org/PyJSONProxy.git

commit
db5d4b2797b145c227988da36cfcdc351ae10ace
parent
050daa3039c9970652be8e18c2ad7c04af0bb7b0
Author
Tobias Bengfort <tobias.bengfort@gmx.net>
Date
2015-12-06 22:05
create flask-inspired wrapper for aiohttp.web

Diffstat

A jsonproxy/web.py 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

1 files changed, 85 insertions, 0 deletions


diff --git a/jsonproxy/web.py b/jsonproxy/web.py

@@ -0,0 +1,85 @@
   -1     1 """Flask inspired wrapper around aiohttp."""
   -1     2 
   -1     3 from functools import lru_cache
   -1     4 from pkg_resources import resource_filename
   -1     5 import asyncio
   -1     6 import logging
   -1     7 import os
   -1     8 
   -1     9 from aiohttp import web
   -1    10 import jinja2
   -1    11 
   -1    12 
   -1    13 @lru_cache()
   -1    14 def get_template(name):
   -1    15 	path = resource_filename(__name__, os.path.join('templates', name))
   -1    16 	with open(path) as fh:
   -1    17 		return jinja2.Template(fh.read())
   -1    18 
   -1    19 
   -1    20 def render_template(name, **kwargs):
   -1    21 	template = get_template(name)
   -1    22 	text = template.render(**kwargs)
   -1    23 	return web.Response(body=text.encode('utf8'))
   -1    24 
   -1    25 
   -1    26 def jsonify(data, **kwargs):
   -1    27 	return web.json_response(data, **kwargs)
   -1    28 
   -1    29 
   -1    30 def abort(code):
   -1    31 	if code == 404:
   -1    32 		raise web.HTTPNotFound
   -1    33 	elif code >= 500:
   -1    34 		raise web.HTTPInternalServerError
   -1    35 	else:
   -1    36 		raise web.HTTPBadRequest
   -1    37 
   -1    38 
   -1    39 def make_response(data, **kwargs):
   -1    40 	if isinstance(data, web.StreamResponse):
   -1    41 		return data
   -1    42 	elif isinstance(data, str):
   -1    43 		return web.Response(body=data.encode('utf8'), **kwargs)
   -1    44 	elif isinstance(data, bytes):
   -1    45 		return web.Response(body=data, **kwargs)
   -1    46 	else:
   -1    47 		raise TypeError('cannot make response from {}'.format(data))
   -1    48 
   -1    49 
   -1    50 class Application:
   -1    51 	def __init__(self, name):
   -1    52 		self.name = name
   -1    53 		self.loop = asyncio.get_event_loop()
   -1    54 		self.app = web.Application(loop=self.loop)
   -1    55 		self.logger = logging
   -1    56 		self.config = {}
   -1    57 		self.debug = False  # NOTE: does not do anything yet
   -1    58 
   -1    59 	def config_from_file(self, path):
   -1    60 		with open(path) as fh:
   -1    61 			exec(compile(fh.read(), path, 'exec'), self.config)
   -1    62 
   -1    63 	def add_route(self, path, fn, methods=('GET',)):
   -1    64 		@asyncio.coroutine
   -1    65 		def wrapped(*args, **kwargs):
   -1    66 			data = yield from asyncio.async(fn(*args, **kwargs))
   -1    67 			return make_response(data)
   -1    68 
   -1    69 		for method in methods:
   -1    70 			self.app.router.add_route(method, path, wrapped)
   -1    71 
   -1    72 	def route(self, path, methods=('GET',)):
   -1    73 		def decorator(fn):
   -1    74 			self.add_route(path, fn, methods=methods)
   -1    75 			return fn
   -1    76 		return decorator
   -1    77 
   -1    78 	def run(self, host='localhost', port=5000):
   -1    79 		server = self.loop.create_server(self.app.make_handler(), host, port)
   -1    80 		self.loop.run_until_complete(server)
   -1    81 		self.logger.info("Server started at http://{}:{}".format(host, port))
   -1    82 		try:
   -1    83 			self.loop.run_forever()
   -1    84 		except KeyboardInterrupt:
   -1    85 			pass