async def admin(request, host=""): form_data = await request.post() host = request.match_info.get('host', None) session = await get_session(request) session['last_visit'] = time.time() session['nickname'] = 'admin' if host: h = history[host] if host in history else {} return aiohttp_jinja2.render_template('admin.html', request, {'host': host, 'history': history}) return aiohttp_jinja2.render_template('admin.html', request, {'history': history})
def wrapped(*la, **kwa): route = la[0] request = route.request http_log = logging.getLogger("aio.http.request") http_log.info(request) if asyncio.iscoroutinefunction(func): coro = func else: coro = asyncio.coroutine(func) try: context = yield from coro(*la) except Exception as e: import traceback traceback.print_exc() log.error("Error calling route handler: %s" % e) raise e if isinstance(context, aiohttp.web.StreamResponse): return context try: response = aiohttp_jinja2.render_template( template_name, request, context, app_key=app_key, encoding=encoding) response.set_status(status) except Exception as e: import traceback traceback.print_exc() log.error("Error calling route (%s): %s" % ( template_name, e)) raise e return response
def wrapped(*la, **kwa): request = la[0] if asyncio.iscoroutinefunction(func): coro = func else: coro = asyncio.coroutine(func) try: context = yield from coro(*la) except Exception as e: import traceback traceback.print_exc() log.error("Error calling template handler: %s" % e) raise e try: response = aiohttp_jinja2.render_template( template_name, request, context, app_key=app_key, encoding=encoding) response.set_status(status) except Exception as e: import traceback traceback.print_exc() log.error("Error calling template (%s): %s" % ( template_name, e)) raise e return response
def response(self, document): if self.json: return web.Response(body=json_util.dumps(document, sort_keys=True, indent=4).encode()) context = {'json': json_util.dumps(document, sort_keys=True, indent=4)} return aiohttp_jinja2.render_template('base.html', self.request, context)
async def output(request): data = await request.content.read() name = data.decode('utf-8').replace('+',' ').partition('scientist_name=')[2] response = aiohttp_jinja2.render_template('viz.html', request, {'name': name}) await get_abstracts(name) return response
async def index(request): resp = web.WebSocketResponse() ok, protocol = resp.can_start(request) if not ok: return aiohttp_jinja2.render_template('index.html', request, {}) await resp.prepare(request) name = (random.choice(string.ascii_uppercase) + ''.join(random.sample(string.ascii_lowercase*10, 10))) log.info('%s joined.', name) resp.send_str(json.dumps({'action': 'connect', 'name': name})) for ws in request.app['sockets'].values(): ws.send_str(json.dumps({'action': 'join', 'name': name})) request.app['sockets'][name] = resp while True: msg = await resp.receive() if msg.type == web.MsgType.text: for ws in request.app['sockets'].values(): if ws is not resp: ws.send_str(json.dumps({'action': 'sent', 'name': name, 'text': msg.data})) else: break del request.app['sockets'][name] log.info('%s disconnected.', name) for ws in request.app['sockets'].values(): ws.send_str(json.dumps({'action': 'disconnect', 'name': name})) return resp
def fortunes(request): """Test type 4: Fortunes""" container = request.app.ah_container return aiohttp_jinja2.render_template('fortunes.html.j2', request, {'fortunes': (yield from get_fortunes(container))})
def login(self, request): """接受登录表单提交的数据,登录后跳转或登录失败后展示错误信息。 :param request: aiohttp.web.Request :return: aiohttp.web.HTTPFound or aiohttp.web.Response """ post = yield from request.post() session = yield from get_session(request) login_id = post.get('login_id', None) password = post.get('password', None) mode = int(post.get('mode', 1)) session['mode'] = mode if login_id and password: kancolle = KancolleAuth(login_id, password) if mode in (1, 2, 3): try: yield from kancolle.get_flash() session['api_token'] = kancolle.api_token session['api_starttime'] = kancolle.api_starttime session['world_ip'] = kancolle.world_ip if mode == 2: return aiohttp.web.HTTPFound('/kcv') elif mode == 3: return aiohttp.web.HTTPFound('/poi') else: return aiohttp.web.HTTPFound('/kancolle') except OOIAuthException as e: context = {'errmsg': e.message, 'mode': mode} return aiohttp_jinja2.render_template('form.html', request, context) elif mode == 4: try: osapi_url = yield from kancolle.get_osapi() session['osapi_url'] = osapi_url return aiohttp.web.HTTPFound('/connector') except OOIAuthException as e: context = {'errmsg': e.message, 'mode': mode} return aiohttp_jinja2.render_template('form.html', request, context) else: raise aiohttp.web.HTTPBadRequest() else: context = {'errmsg': '请输入完整的登录ID和密码', 'mode': mode} return aiohttp_jinja2.render_template('form.html', request, context)
def wshandler_login(ws, request, msg): kwds = msg["data"].split() if len(kwds) > 1: ws.send_str(json.dumps({'eventName': 'inject', 'data': '<div style="border:4px solid green;">login user: '******'</div>'})) else: response = aiohttp_jinja2.render_template('login.jinja2', request, {}) response_text = response.text ws.send_str(json.dumps({'eventName': 'inject', 'data': response_text}))
def mesajlasma(request): global tox data="" data=open("mesaj.log","r").read() context = {'data': data} response = aiohttp_jinja2.render_template("mesajlasma.html", request, context) response.headers['Content-Language'] = 'tr' return response
def dps(request): global tox data="" print(request.method) context = {'data': data} response = aiohttp_jinja2.render_template("dps.html", request, context) response.headers['Content-Language'] = 'tr' return response
def complete(request): messages = yield from peewee_async.execute(Message.select()) messages = list(messages) messages.append(Message(content='Hello, World!')) messages.sort(key=lambda m: m.content) return aiohttp_jinja2.render_template('template.html', request, { 'messages': messages })
async def logout(request): data={} data['title']='登录' data['main']=static.assets res = aiohttp_jinja2.render_template('login.jinja2', request, data) res.set_cookie('Authentication','logout') return res
async def main(request: web.Request, token): # redirect to /login if not logged in if not token: return web.HTTPFound('/login') return render_template('base.html', request, {'version': version, 'commit_id': commit_id, 'additional_views': additional_views, 'additional_js': additional_js, 'additional_nav_html': additional_nav_html})
async def get_message_intermediate(request): token = request.match_info['token'].encode() if teabag.is_message_exists(token): context = {'url': '/message/{}'.format(token.decode())} response = aiohttp_jinja2.render_template( 'intermediate.jinja2', request, context) else: response = _get_404_response(request) return response
async def home(request): context = {} response = aiohttp_jinja2.render_template('home.html', request, context) if 'rateapp' not in request.cookies: new_id = id_generator() logger.info("new client connecting, id=%s", new_id) response.set_cookie('rateapp', new_id) return response
async def hello(request): form_data = await request.post() session = await get_session(request) session['last_visit'] = time.time() host = request.host[:request.host.find(':')] # host if 'nickname' in form_data and form_data['nickname'] != 'admin': session['nickname'] = form_data['nickname'] return web.HTTPFound(app.router['chat_page'].url(parts={'host':host})) # get chat.html return aiohttp_jinja2.render_template('home.html', request, {})
async def get_message(request): token = request.match_info['token'].encode() try: message = teabag.get_message(token) context = {'message': message} response = aiohttp_jinja2.render_template( 'message.jinja2', request, context) except FileNotFoundError: response = _get_404_response(request) return response
def search(request): domain = request.GET['domain'] search = request.GET['search'] tld = request.GET['tld'] if not domain: return {'error': 'You forgot the domain'} if not search: return {'error': 'You forgot the search term'} try: data = yield from keyword_analysis(request.app, domain, search, tld) results = { 'search_results': [url.url for url in data['search_results']], 'total_sites': data['total_sites'], 'website_keywords': [key.to_dict() for key in data['keywords']], 'keywords': [key.to_dict() for key in data['keywords']] } return {'domain': domain, 'search': search, 'tld': tld, 'results': results} except MonkeyLearnAPIError as exc: log.exception(exc) response = aiohttp_jinja2.render_template( 'index.html', request, { 'error': 'MonkeyLearn API Error, status code {}, body: "{}"'.format( exc.status_code, exc.body ) } ) except DownloadMainSiteFail as exc: log.exception(exc) response = aiohttp_jinja2.render_template('index.html', request, {'error': str(exc)}) except Exception as exc: log.exception(exc) response = aiohttp_jinja2.render_template( 'index.html', request, {'error': 'An internal error occurred.'} ) response.set_status(500) return response
def test(request): document = yield from db['restaurants'].find_one() # assert 0, document # return web.Response(body=json.dumps(document).encode()) context = {'json': json_util.dumps(document, sort_keys=True, indent=4)} # context = {'json': pprint.pformat(document)} response = aiohttp_jinja2.render_template('base.html', request, context) # assert 0 return response
async def template_handler(request): """ :param request: :return: """ print(type(request)) response = aiohttp_jinja2.render_template('base_template.html', request, {}) print(response) response.headers['Content-Language'] = 'en' return response
async def retrieve_paste(self, request): try: paste_id = request.match_info['paste_id'] except KeyError: raise web.HTTPBadRequest() paste = await request.app['db'].retrieve_paste(paste_id) if paste is None: response = aiohttp_jinja2.render_template('404.html', request, {}) return response return {'title': APP_TITLE, 'paste_content': paste}
async def create_response(self, context): if settings.DEBUG: return aiohttp_jinja2.render_template( self.template, self.request, context) html = await cache.cache_per_context(aiohttp_jinja2.render_string)( self.template, self.request, context, app_key='aiohttp_jinja2_environment') response = aiohttp.web.Response() response.content_type = 'text/html' response.charset = 'utf-8' response.text = html return response
def connector(self, request): """适配登录器直连模式结果页面,提供osapi.dmm.com的链接。 :param request: aiohttp.web.Request :return: aiohttp.web.Response or aiohttp.web.HTTPFound """ session = yield from get_session(request) osapi_url = session.get('osapi_url', None) if osapi_url: context = {'osapi_url': osapi_url} return aiohttp_jinja2.render_template('connector.html', request, context) else: self.clear_session(session) return aiohttp.web.HTTPFound('/')
def root(request): global tuntox context = {} text = "milisia-dugum adresi" text+="<br>"+str(tox.self_get_address()) text+="<br>" +"milisia-tuntox adresi" if tuntox is None: if(os.path.isfile("ozel/tox_save")): tuntox = tox_factory(ProfileHelper.open_profile("ozel/tox_save")) else: text+="<br>"+str(tuntox.self_get_address()) context = {'data': text} response = aiohttp_jinja2.render_template( "ana.html", request, context) response.headers['Content-Language'] = 'tr' return response
def index_handler(request): logger.debug('index_handler') context = {} cookie = None if hasattr(request, 'session') and request.session.get('logged'): if 'after_login' in request.GET: cookie = get_signed_cookie(request.app['secret_key'], id=request.session['id']) if 'user' in request.session: context['user'] = request.session['user'] resp = aiohttp_jinja2.render_template('index.html', request, context) if cookie: cookie_name = get_session_cookie_name(request.app) resp.set_cookie(cookie_name, cookie, max_age=SESSION_COOKIE_MAX_AGE) return resp
def kcv(self, request): """适配KanColleViewer或者74EO中进行游戏的页面,提供一个iframe,在iframe中载入游戏FLASH。该页面会检查会话中是否有api_token、 api_starttime和world_ip三个参数,缺少其中任意一个都不能进行游戏,跳转回登录页面。 :param request: aiohttp.web.Request :return: aiohttp.web.Response or aiohttp.web.HTTPFound """ session = yield from get_session(request) token = session.get('api_token', None) starttime = session.get('api_starttime', None) world_ip = session.get('world_ip', None) if token and starttime and world_ip: return aiohttp_jinja2.render_template('kcv.html', request, context={}) else: self.clear_session(session) return aiohttp.web.HTTPFound('/')
def get(self, request): context = yield from self.common(request) csrf_token = request.cookies.get('csrf-token') or generate_token() context.update({'person': request.app['ldap'].get_person(request.token.user_id), 'token': request.token, 'csrf_token': csrf_token}) response = render_template('authorize.html', request, context) if 'csrf-token' not in request.cookies: response.set_cookie('csrf-token', csrf_token, httponly=True, secure=(request.scheme=='https')) return response
def get(self, request): context, reference_data = yield from asyncio.gather( self.get_api_json(request, 'accident?' + request.query_string), self.get_api_json(request, 'reference-data')) context.update({ 'severity': request.GET.getall('severity', ()), 'dateTimeLower': request.GET.get('dateTimeLower', ''), 'dateTimeUpper': request.GET.get('dateTimeUpper', ''), 'involvedVehicleType': request.GET.getall('involvedVehicleType', ()), 'involvedCasualtyType': request.GET.getall('involvedCasualtyType', ()), 'highwayAuthority': request.GET.get('highwayAuthority'), 'news': request.GET.get('news'), 'referenceData': reference_data, }) context['referenceData']['HighwayAuthority'] = \ OrderedDict(i for i in sorted(context['referenceData']['HighwayAuthority'].items(), key=lambda i: i[1]['label'])) return aiohttp_jinja2.render_template('accident-list.html', request, context)
async def handler(request): await asyncio.sleep(0.01) session = request.app['session'] resp = await session.get(service_b_api) data_b = await resp.json() resp = await session.get(service_e_api) data_e = await resp.json() tree = { 'name': 'service_a', 'host': host, 'port': port, 'children': [data_b, data_e], } ctx = {'zipkin': zipkin_ui_address, 'service': tree} return aiohttp_jinja2.render_template('index.html', request, ctx)
async def index_handler(request): context = {} response = aiohttp_jinja2.render_template("index.html", request, context) return response
async def index(self, request): """Function which renders a form for user to fill.""" context = {} return render_template("user_processing/user_processing.html", request, context)
def handle_index(request, **kwargs): return render_template("index.html", request, {})
async def index(request): ws_current = web.WebSocketResponse() ws_ready = ws_current.can_prepare(request) if not ws_ready.ok: return aiohttp_jinja2.render_template('index.html', request, {}) # Does this means I have connected in js? await ws_current.prepare(request) g = request.app['games'] waiting_players = request.app['waiting'] name = None is_playing = True while True: msg = await ws_current.receive() broadcast_result = {} cur_result = {} if msg.type == aiohttp.WSMsgType.text: try: parsed = json.loads(msg.data) action, arg = parsed['action'], parsed['arg'] print(name, action, arg) if not is_playing: continue if action == 'NEW_PLAYER': request.app['websockets'][arg] = ws_current name = arg if g.status == 'NEW': g.new_player(arg) cur_result['hand'] = g.get_hand(name) cur_result['player_id'] = g.get_player_id(name) else: waiting_players.append(arg) broadcast_result['waiting'] = waiting_players is_playing = False elif action == 'START': g.start(arg['num_decks']) g.clean_table() broadcast_result['draw_until'] = arg['draw_until'] broadcast_result['hand'] = [] elif action == 'DRAW': g.draw(name, arg) cur_result['hand'] = g.get_hand(name) elif action == 'CLEAN_TABLE': g.clean_table() elif action == 'PLAY': arg = map(int, arg) g.play(name, arg) cur_result['hand'] = g.get_hand(name) elif action == 'TAKE_BACK': arg = map(int, arg) g.take_back(name, arg) cur_result['hand'] = g.get_hand(name) elif action == 'END_TURN': g.end_turn(name) elif action == 'RETURN_TO_DECK': arg = list(map(int, arg)) g.return_to_deck(name, arg) cur_result['hand'] = g.get_hand(name) elif action == 'END_DRAW': g.end_draw() elif action == 'TAKE_TURN': g.set_turn(name) elif action == 'MESSAGE': broadcast_result['msg'] = arg elif action == 'SPREAD_CARDS': count = int(arg) await spread_cards(g, request.app['websockets'], count) elif action == 'DEAL': count = int(arg) g.deal(count) elif action == 'SET_POINTS': broadcast_result['points'] = arg else: raise ValueError('{} is not valid action'.format(action)) except ValueError as e: print(e) import traceback traceback.print_exc() await ws_current.send_json({'error': str(e)}) else: broadcast_result.update(g.visible_state()) for ws in request.app['websockets'].values(): await ws.send_json(broadcast_result) if cur_result: await ws_current.send_json(cur_result) print('result:', cur_result) else: break del request.app['websockets'][name] g.remove_player(name) for ws in request.app['websockets'].values(): await ws.send_json({'players': g.players()}) return ws_current
async def index_page(self, request): t = self._template context = {'name': self._name} return render_template(t, request, context, app_key=TEMPLATE_APP_KEY)
async def login_page(self, request): t = self._login_template context = {} return render_template(t, request, context, app_key=TEMPLATE_APP_KEY)
async def about(request): app = request.app app['log'].info('open main page') data = {} response = aiohttp_jinja2.render_template('main.html', request, data) return response
async def handle_404(request, reason): return aiohttp_jinja2.render_template('404.html', request, { 'request': request, 'reason': reason })
async def index(request: web.Request) -> web.Response: return render_template("index.html", request, {"chunk_size": request.app._client_max_size - 1})
async def list_updates(request): updates = [update.save_data() for update in TelegramUpdate.find()] params = {'queue': updates} response = aiohttp_jinja2.render_template('queue.html', request, params) return response
async def handle_500(request): return aiohttp_jinja2.render_template('500.html', request, {})
async def handle_404(request): return aiohttp_jinja2.render_template('404.html', request, {})
async def index(request): with pytest.raises(TypeError, match=(r"argument value should be str or int, " r"got arg -> \[<class 'bool'>\] True")): aiohttp_jinja2.render_template('tmpl.jinja2', request, {}) return web.Response()
async def page_handler(request): pk = request.match_info.get('pk') all_objects = await objects.execute(Page.select().where(Page.id == pk)) context = {'page': [x for x in all_objects][0]} response = render_template('page.html', request, context) return response
def error_html(template, request, context={}, status_code=200): return aiohttp_jinja2.render_template(template, request, context, status=status_code)
async def index(request): """ Returns the main page of the public area. """ return render_template("index.html", request, {})
async def get(self): session = await get_session(self.request) if session.get('user'): redirect(self.request, 'active') context = {} return render_template('login.html', self.request, context)
async def privacy(request): return jinja2.render_template("/legal/cookies.html", request, {})
async def index_get(request): return aiohttp_jinja2.render_template('index.html', request, { 'message': 'Online' })
async def index_post(request): return aiohttp_jinja2.render_template('index.html', request, { 'message': json.dumps(await request.json(), indent=4) })
async def list_failed_updates(request): failed_updates = [update.save_data() for update in FailedUpdate.find()] params = {'failed_updates': failed_updates} response = aiohttp_jinja2.render_template('failed_updates.html', request, params) return response
async def list_downloads(request): # TODO: params = {'list_downloads': []} response = aiohttp_jinja2.render_template('downloads.html', request, params) return response
async def imprint(request): return jinja2.render_template("/legal/imprint.html", request, {})
async def index(request): with pytest.raises(jinja2.UndefinedError, match="'url' is undefined"): aiohttp_jinja2.render_template('tmpl.jinja2', request, {}) return web.Response()
async def handle_404(self, request, _): resp = aiohttp_jinja2.render_template("index.html", request, {}) resp.set_status(404) return resp
async def main(request): response = aiohttp_jinja2.render_template('index.html', request, {}) return response
async def handle(req): print('/') return aiohttp_jinja2.render_template('index.html', req, {})
async def dashboard(request): params = {'cnt_failed_updates': len(FailedUpdate.find())} return aiohttp_jinja2.render_template('dashboard.html', request, params)
async def index(request): with pytest.raises(RuntimeError, match='static_root_url'): aiohttp_jinja2.render_template('tmpl.jinja2', request, {}) return web.Response()
async def sql_editor(self, request): return aiohttp_jinja2.render_template( "sql_editor.html", request, context=await self.get_context(request, {}), )