def prepare(): app = Sanic('tjs headquarter') app.config.from_object(config) app.on_close = [] jinja2_sanic.setup( app, loader=jinja2.FileSystemLoader(searchpath=[(app.config.ROOT_DIR / 'templates').as_posix()])) @app.get('/') @jinja2_sanic.template('index.html') async def index(_): return {} @app.exception(NotFound) async def not_found(request, *_): if request.headers.get('referer', None) is None: return await index(request) return response.raw(b'\x00') @app.listener('before_server_start') async def setup(app, loop): pass @app.listener('after_server_stop') async def shutdown(app, loop): pass return app
async def test_render_class_view_based(test_client): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) class SimpleView(HTTPMethodView): @jinja2_sanic.template("templates.jinja2") async def get(self, request): return { "Player": "CR7", "Category": "Soccer", } # register routes app.add_route(SimpleView.as_view(), "/") cli = await test_client(app) resp = await cli.get('/') assert resp.status == 200 text = await resp.text() assert text == "<html><body><h1>CR7</h1>Soccer</body></html>"
async def test_render_func(test_client): app = Sanic("test_jinja2_render") # setup template = "foo: {{ foo }}, bar: {{ bar }}, path: {{ request.path }}" context_processors = ( jinja2_sanic.request_processor, asyncio.coroutine( lambda request: {'foo': 1, 'bar': 3}), ) jinja2_sanic.setup( app, loader=jinja2.DictLoader( { "templates.jinja2": template } ), context_processors=context_processors ) @app.route("/") @jinja2_sanic.template("templates.jinja2") async def func(request): return { 'bar': 7 } cli = await test_client(app) resp = await cli.get('/') assert resp.status == 200 text = await resp.text() assert text == "foo: 1, bar: 7, path: /"
async def test_render_context_is_None(test_client): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) @app.route("/") @jinja2_sanic.template("templates.jinja2") async def func(request): return None cli = await test_client(app) resp = await cli.get('/') assert resp.status == 200 text = await resp.text() assert text == "<html><body><h1></h1></body></html>"
async def test_render_func(test_client): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) @app.route("/") @jinja2_sanic.template("templates.jinja2") async def func(request): return "CR7" request = mock.Mock() request.app = app with pytest.raises(ServerError) as ctx: await func(request) assert str(ctx.value) == "context should be mapping, not <class 'str'>"
async def test_render_func_convert_to_coroutine(test_client): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) @app.route("/") @jinja2_sanic.template("templates.jinja2") def func(request): return { "Player": "CR7", "Category": "Soccer", } cli = await test_client(app) resp = await cli.get('/') assert resp.status == 200 text = await resp.text() assert text == "<html><body><h1>CR7</h1>Soccer</body></html>"
async def test_jinja2_filter(test_client): app = Sanic("test_jinja2_render") # setup def simple_func(last_name): return "Y.{last_name}".format(last_name=last_name) jinja2_sanic.setup(app, loader=jinja2.DictLoader( {"templates.jinja2": "{{ 2|simple_func }}"}), filters={'simple_func': simple_func}) @app.route("/") @jinja2_sanic.template("templates.jinja2") async def func(request): return {} cli = await test_client(app) resp = await cli.get('/') assert resp.status == 200 text = await resp.text() assert text == "Y.2"
async def test_render_context_is_httpresponse(test_client): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) @app.route("/") @jinja2_sanic.template("templates.jinja2") async def func(request): return response.json({ "Player": "CR7", "Category": "Soccer", }) cli = await test_client(app) resp = await cli.get('/') assert resp.status == 200 resp_json = await resp.json() assert resp_json == {"Player": "CR7", "Category": "Soccer"}
async def test_render_template_missing(): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) @app.route("/") @jinja2_sanic.template("templates.jinja3") def func(request): return { "Player": "CR7", "Category": "Soccer", } request = mock.Mock() request.app = app with pytest.raises(ServerError) as ctx: await func(request) assert str(ctx.value) == "Template 'templates.jinja3' not found"
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import io import base64 import networkx as nx import asyncio from sample_service_api_client import SampleServiceApiClient client = SampleServiceApiClient() app = Sanic("sanic_jinja2_render") template="<html><head></head><body><h2><font color=#ff4500>{{user_id}} {{searcher_name}}</font></h2>" \ "<h3>{{friends_names}}</h3><div><img src='{{graph}}'> </div></body></html>" jinja2_sanic.setup(app, loader=jinja2.DictLoader({"templates.jinja2": template})) @app.route("/") async def func(request): return response.html("# /user/{nth}/{user_id} で{user_id}の{nth}次までの友達を表示" "<br><br> 例: /2/3 でid=3の友達の友達を表示." "<br>例: /4/8 でid=8の4次の友達(友達の友達の友達の友達)までを表示." "<br><br><br># /user/all ですべての人の関係を表示") def draw_network(client): img = io.BytesIO() G = nx.DiGraph() if len(client.friend_list) == 0 and not client.is_invalid_id: print("no friends")
import pathlib import aiomysql import jinja2 import jinja2_sanic from sanic import Sanic from sanic.response import HTTPResponse, redirect static_folder = pathlib.Path(__file__).resolve().parent / 'public' / 'css' app = Sanic(__name__) app.static('/css', str(static_folder)) jinja2_sanic.setup(app, loader=jinja2.FileSystemLoader('./templates', encoding='utf8')) app.secret_key = os.environ.get('ISHOCON2_SESSION_SECRET', 'showwin_happy') _config = { 'db_host': os.environ.get('ISHOCON2_DB_HOST', 'localhost'), 'db_port': int(os.environ.get('ISHOCON2_DB_PORT', '3306')), 'db_username': os.environ.get('ISHOCON2_DB_USER', 'ishocon'), 'db_password': os.environ.get('ISHOCON2_DB_PASSWORD', 'ishocon'), 'db_database': os.environ.get('ISHOCON2_DB_NAME', 'ishocon2'), } def render_template(template_name, request, **kwargs): return jinja2_sanic.render_template(template_name, request, context=kwargs)
A routing layer for the onboarding bot tutorial built using [Slack's Events API](https://api.slack.com/events-api) in Python """ import os import requests import jinja2 import jinja2_sanic from sanic import Sanic from sanic.response import json, text from bot import pyBot from handler import event_handler app = Sanic() jinja2_sanic.setup(app, loader=jinja2.FileSystemLoader(searchpath="templates")) @app.listener('before_server_start') async def start(app, loop): users = requests.get("https://slack.com/api/users.list", params={ "token": os.environ.get("SLACK_BOT_TOKEN") }).json() if "members" in users: app.users = { member.pop("id"): member for member in users.get("members", []) }
from sanic import Sanic import config from asyncpg import create_pool import jinja2_sanic from jinja2 import FileSystemLoader import logging from .in_log import LOG_SETTINGS from .util import URLCoder from .schema import schema_up blure = Sanic(__name__, log_config=LOG_SETTINGS) log = logging.getLogger('blure') jinja2_sanic.setup(blure, loader=FileSystemLoader('app/templates')) blure.config.from_object(config) blure.static('/static', './app/static') blure.url = URLCoder(blure.config.APP_SECRET[::2]) # cut secret, because it is too long @blure.listener('before_server_start') async def setup_db(_app, loop): _app.pool = await create_pool(_app.config.PG_URI, loop=loop) async with _app.pool.acquire() as conn: await create_tables(conn) @blure.listener('after_server_stop') async def close_db_conns(_app, loop): await _app.pool.close()
def get_app(): app = Sanic('NEUME-HQ') app.gq_schema = schema Config(app, '../conf') app.on_close = [] app.static('/assets', f'{STATIC_DIR}/assets') app.static('/img', f'{STATIC_DIR}/img') app.static('/js', f'{STATIC_DIR}/js') app.static('/service-worker.js', f'{STATIC_DIR}/service-worker.js') loader = jinja2.FileSystemLoader(searchpath=['/var/www/neume-hq/public']) jinja2_sanic.setup(app, loader=loader) app.render = jinja2_sanic.render_template @app.middleware('request') def request_mw(request): print('before') request.app.gq_db.count = 0 print(request.app.gq_db.count) @app.middleware('response') def response_mw(request, response): print('after') print(request.app.gq_db.count) @app.get('/') async def index(request): return app.render('index.html', request, {}) async def not_found(request, *_): if request.headers.get('referer', None) is None: return await index(request) return response.raw(b'\x00') app.error_handler.add(NotFound, not_found) @app.listener('before_server_start') async def setup(app, loop): app._executor = AsyncioExecutor(loop=loop) async with ArangoAdmin('root', 'arango-pw') as admin: dbs, users = await asyncio.gather(admin.get_dbs(), admin.get_users()) await asyncio.gather( *(admin.create_user(name, pw) for name, pw in app.config.DB_USERS.items() if name not in [usr['user'] for usr in users])) for db_name, cfg in app.config.DATABASES.items(): if db_name not in dbs: await admin.create_db(db_name) await asyncio.gather( *(admin.set_access_level(name, db_name, level=grants[role]) for role, name in cfg['users'].items()), *(admin.set_access_level(name, db_name, level='none') for name in app.config.DB_USERS.keys() if name not in cfg['users'].values())) app.gq_db = ArangoDB('user', 'user-pw', 'public') await app.gq_db.login() app.add_route( GraphQLView.as_view(schema=await schema.setup(app.gq_db), context={ 'db': app.gq_db, 'cache': {} }, batch=True, executor=app._executor, graphiql=True), 'graphql') @app.listener('after_server_stop') async def close(app, loop): await asyncio.gather(*(func() for func in app.on_close)) await app.gq_db.close() print('server closed') return app
app.static(f"/{FILE_BASE}", f"./{FILE_BASE}") app.static("/static", "./static") def get_templates(): mapping = {} for file in os.listdir("templates"): if file.endswith(".html"): with open(f"templates/{file}", "r", encoding="UTF-8") as template: mapping[f"templates.{file}".replace(".html", "")] = template.read() return mapping jinja2_sanic.setup(app, loader=jinja2.DictLoader(get_templates())) scheduler = SanicScheduler(app) file_manager = FileManager(base=FILE_BASE) broadcast = LiveFeedBroadcasts() globals.Globals.file_manager = file_manager news_rss = RSSFeed(rss_url="https://www.crunchyroll.com/newsrss", change_callback=broadcast.news_callback) release_rss = RSSFeed( rss_url="http://feeds.feedburner.com/crunchyroll/rss/anime", change_callback=broadcast.release_callback)
from sanic.log import logger app.static('/static', 'app/static') css_files = ['main', 'base', 'navbar', 'forms', 'database', 'pokertables', 'pokertable'] getHeaders = { 'css_urls': [app.url_for('static', filename=f'css/{file}.css') for file in css_files], 'favicon_url': app.url_for('static', filename='favicon.ico') } setup(app, loader=DictLoader({ "template_base": open('app/templates/base.html').read(), "template_signin": open('app/templates/signin.html').read(), "template_signup": open('app/templates/signup.html').read(), "template_database": open('app/templates/database.html').read(), "template_table": open('app/templates/table.html').read(), "template_pokertables": open('app/templates/pokertables.html').read() })) def signinValidate(form): password = form.get('password').encode('utf-8') passhash = sha256(password).hexdigest() account = dbase.selectWhere( DbTable.ACCOUNTS, username = form.get('username'), password_hash = passhash ) return bool(account) def signupValidate(form):