async def handle_request(request): urls = request.args.getlist('url') callback = request.args.get('callback') if urls: if len(urls) > 10: return response.json([{ 'ok': False, 'error': 'Max 10 URLs allowed' }], status=400) async with aiohttp.ClientSession() as session: head_infos = await asyncio.gather(*[ head(session, url) for url in urls ]) if callback and is_valid_callback(callback): return response.text( '{}({})'.format(callback, json.dumps(head_infos, indent=2)), content_type='application/javascript', headers={'Access-Control-Allow-Origin': '*'}, ) else: return response.json( head_infos, headers={'Access-Control-Allow-Origin': '*'}, ) else: return response.html(INDEX)
def default(self, request, exception): self.log(format_exc()) if issubclass(type(exception), SanicException): return text( 'Error: {}'.format(exception), status=getattr(exception, 'status_code', 500), headers=getattr(exception, 'headers', dict()) ) elif self.debug: html_output = self._render_traceback_html(exception, request) response_message = ('Exception occurred while handling uri: ' '"%s"\n%s') logger.error(response_message, request.url, format_exc()) return html(html_output, status=500) else: return html(INTERNAL_SERVER_ERROR_HTML, status=500)
def render_worker_map(): template = env.get_template('workersmap.html') return html(template.render( area_name=conf.AREA_NAME, map_center=center, map_provider_url=conf.MAP_PROVIDER_URL, map_provider_attribution=conf.MAP_PROVIDER_ATTRIBUTION, social_links=social_links() ))
def default(self, request, exception): """ Provide a default behavior for the objects of :class:`ErrorHandler`. If a developer chooses to extent the :class:`ErrorHandler` they can provide a custom implementation for this method to behave in a way they see fit. :param request: Incoming request :param exception: Exception object :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: """ self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = "Exception occurred while handling uri: %s" logger.exception(response_message, url) if issubclass(type(exception), SanicException): return text( "Error: {}".format(exception), status=getattr(exception, "status_code", 500), headers=getattr(exception, "headers", dict()), ) elif self.debug: html_output = self._render_traceback_html(exception, request) return html(html_output, status=500) else: return html(INTERNAL_SERVER_ERROR_HTML, status=500)
def render_map(): css_js = '' if conf.LOAD_CUSTOM_CSS_FILE: css_js = '<link rel="stylesheet" href="static/css/custom.css">' if conf.LOAD_CUSTOM_JS_FILE: css_js += '<script type="text/javascript" src="static/js/custom.js"></script>' js_vars = Markup( "_defaultSettings['FIXED_OPACITY'] = '{:d}'; " "_defaultSettings['SHOW_TIMER'] = '{:d}'; " "_defaultSettings['TRASH_IDS'] = [{}]; ".format(conf.FIXED_OPACITY, conf.SHOW_TIMER, ', '.join(str(p_id) for p_id in conf.TRASH_IDS))) template = env.get_template('custom.html' if conf.LOAD_CUSTOM_HTML_FILE else 'newmap.html') return html(template.render( area_name=conf.AREA_NAME, map_center=center, map_provider_url=conf.MAP_PROVIDER_URL, map_provider_attribution=conf.MAP_PROVIDER_ATTRIBUTION, social_links=social_links(), init_js_vars=js_vars, extra_css_js=Markup(css_js) ))
async def handle_request_with_no_domain(request): if not request.cookies.get("user_id"): return html(""" <li><a href="./tokyo.example.com">tokyo.example.com</a></li> <li><a href="./osaka.example.com">osaka.example.com</a></li> """)
async def index(request): template = env.get_template('index.html') html_content = template.render(socket_url=socket_url) return html(html_content)
async def service_edit(request): if request.method == "GET": service_id = request.args.get("service_id") service_types = constants.SERVICE_TYPE_DICT with yhk_session() as session: categories = await Category.get_all(session) if not service_id: return html(await render_template('/admin/service_edit.html', request=request, data=None, categories=categories, service_types=service_types)) else: service = await Service.get(session, service_id) service.packages = list( filter(lambda p: p.delete_flag is False, service.packages)) return html(await render_template('/admin/service_edit.html', request=request, data=service, categories=categories, service_types=service_types)) elif request.method == "POST": service_id = request.form.get("service_id") service_name = request.form.get("service_name") sub_heading = request.form.get("sub_heading") price = request.form.get("price") enable = request.form.get("enable") category_id = request.form.get("category_id") order_no = request.form.get("order_no") remark = request.form.get("remark") instruction = request.form.get("instruction") service_type = request.form.get("service_type") if not (service_name and sub_heading and price and enable and category_id and order_no and instruction and service_type): return json({"code": 500, "message": "请填写完整信息!"}) if service_id: service_id = int(service_id) category_id = int(category_id) order_no = int(order_no) price = float(price) enable = True if enable == "true" else False with yhk_session() as session: if not service_id: service = Service() session.add(service) else: service = await Service.get(session, service_id) if not service: return json({"code": 4001, "message": "当前服务不存在!"}) service.service_name = service_name service.sub_heading = sub_heading service.price = price service.enable = enable service.category_id = category_id service.order_no = order_no service.remark = remark service.instruction = instruction service.service_type = service_type session.commit() return json({ "code": 200, "message": "保存成功!", "service_id": service.id })
async def config(request): template = env.get_template('configuration.html') return html(template.render( config='active', botname=botname ))
async def test(request): template = open(os.getcwd() + "/project/index.html") return html(template.read())
async def index(request): with open('app.html') as f: return html(f.read())
def handle_request(request): return response.html('<p>Hello world!</p><p>{}</p>'.format(print_myself()))
def template(tpl, **kwargs): template = env.get_template(tpl) return html(template.render(kwargs))
async def template(tpl, **kwargs): template = env.get_template(tpl) rendered_template = await template.render_async(**kwargs) return html(rendered_template)
async def test(request): data = request.json return html(template.render(**data))
def page(tpl, **kwargs): template = env.get_template(tpl) return html(template.render(kwargs))
async def index(request): with open('simple.html') as f: return html(f.read())
async def root(request): return html(index_html)
async def handle_request(request, exception): start_time = time.time() format = 'html' url = request.path headers = dict() if url.startswith('/http'): url = url[1:] elif url.startswith('/html/http'): url = url[6:] elif url.startswith('/mhtml/http'): format = 'mhtml' url = url[7:] elif url.startswith('/pdf/http'): format = 'pdf' url = url[5:] elif url.startswith('/jpeg/http'): format = 'jpeg' url = url[6:] elif url.startswith('/png/http'): format = 'png' url = url[5:] if request.query_string: url = url + '?' + request.query_string parsed_url = urlparse(url) proxy = request.headers.get('X-Prerender-Proxy', '') if not parsed_url.hostname: return response.text('Bad Request', status=400) if ALLOWED_DOMAINS: if parsed_url.hostname not in ALLOWED_DOMAINS: return response.text('Forbiden', status=403) skip_cache = request.method == 'POST' if not skip_cache: try: data = await cache.get(url, format) modified_since = await cache.modified_since(url) or time.time() headers['Last-Modified'] = formatdate(modified_since, usegmt=True) try: if_modified_since = parsedate(request.headers.get('If-Modified-Since')) if_modified_since = time.mktime(if_modified_since) except TypeError: if_modified_since = 0 if modified_since and if_modified_since >= modified_since: logger.info('Got 304 for %s in cache in %dms', url, int((time.time() - start_time) * 1000)) return response.text('', status=304, headers=headers) if data is not None: headers['X-Prerender-Cache'] = 'hit' logger.info('Got 200 for %s in cache in %dms', url, int((time.time() - start_time) * 1000)) if format == 'html': return response.html( apply_filters(data.decode('utf-8'), HTML_FILTERS), headers=headers ) return response.raw(data, headers=headers) except Exception: logger.exception('Error reading cache') if sentry: sentry.captureException() if CONCURRENCY <= 0: # Read from cache only logger.warning('Got 502 for %s in %dms, prerender unavailable', url, int((time.time() - start_time) * 1000)) return response.text('Bad Gateway', status=502) try: if _ENABLE_CB: user_agent = request.headers.get('user-agent', '') _os, browser = httpagentparser.simple_detect(user_agent) breaker = _BREAKERS[browser] data, status_code = await breaker.run(lambda: _render(request.app.prerender, url, format, proxy)) else: data, status_code = await _render(request.app.prerender, url, format, proxy) headers.update({'X-Prerender-Cache': 'miss', 'Last-Modified': formatdate(usegmt=True)}) logger.info('Got %d for %s in %dms', status_code, url, int((time.time() - start_time) * 1000)) if format == 'html': if 200 <= status_code < 300: executor.submit(_save_to_cache, url, data.encode('utf-8'), format) return response.html( apply_filters(data, HTML_FILTERS), headers=headers, status=status_code ) if 200 <= status_code < 300: executor.submit(_save_to_cache, url, data, format) return response.raw(data, headers=headers, status=status_code) except (asyncio.TimeoutError, asyncio.CancelledError, TemporaryBrowserFailure, RetriesExhausted): logger.warning('Got 504 for %s in %dms', url, int((time.time() - start_time) * 1000)) return response.text('Gateway timeout', status=504) except TooManyResponseError: logger.warning('Too many response error for %s in %dms', url, int((time.time() - start_time) * 1000)) return response.text('Service unavailable', status=503) except CircuitOpen: logger.warning('Circuit breaker open for %s', browser) return response.text('Service unavailable', status=503) except Exception: logger.exception('Internal Server Error for %s in %dms', url, int((time.time() - start_time) * 1000)) if sentry: sentry.captureException() return response.text('Internal Server Error', status=500)
async def index(request): with open('latency.html') as f: return html(f.read())
async def main_page(_request) -> HTTPResponse: return html(""" <a href="/login">Simple login</a></br> <a href="/login/gitlab">Gitlab login</a></br> <a href="/login/discord">Discord login</a></br> """)
def home(request: Request) -> html: html_content = open(os.path.join(build_dir, 'index.html'), 'r').read() return html(html_content)
async def graphiql_view(request): return response.html(render_graphiql())
async def apiui_documentation(request, user): template = env.get_template('apiui_documentation.html') content = template.render(name=user['username'], links=links) return response.html(content)
async def index(request): return response.html(HOME_PAGE)
async def handle_request(request): return response.html("""<html><head><script> var exampleSocket = new WebSocket("ws://" + location.host + '/feed'); exampleSocket.onmessage = function (event) { console.log(event.data)};</script></head><body><h1>Hello socket!</h1><p>hello</p></body></html>""" )
async def index(request, token): if token not in TOKENS: return response.text("Not Found! \nIncorrect token could be used!", 404) return response.html(INDEX_PAGE)
async def index(request, number=1): return response.html("{}-fib({})={}".format(__file__, number, _fib(int(number))))
async def index(request): statements = await parse() random.shuffle(statements) return html(render_template('index.html', statements=statements))
async def post(request): data = request.form number = data['fib'][0] return response.html("{}-fib({})={}".format(__file__, number, _fib(int(number))))
async def index(request): return html(await render_template('/admin/service.html', request=request))
def home(req): return html(main_page)
async def bot(request): template = env.get_template('bot_profile.html') return html(template.render( bot='active', botname=botname ))
async def nobel(req, blog, article, no): article = Article(blog, article, no) progress_table[article.name] = article ws = ws_page.replace("HASHDATA", article.name) return html(ws)
async def cmds(request): template = env.get_template('commands.html') return html(template.render( commands='active', botname=botname ))
def render(template, **kwargs): return response.html(render_text(template, **kwargs))
async def index(request, path): template = template_env.get_template("index.html") config = get_token(path) content = template.render(config=json.dumps(config), domain=path) return html(content)
def render_template(self, template=None): return html(template)
async def index(request): users = ['Jack', 'Sakamoto', 'Michael', 'Chen'] return html(template.render(users=users))
def index(request): return response.html('Hello, world!')
async def servers(request): logger.info('SERVER LIST') page = get_final_html(bot.get_servers(), str(bot.client.user)) return html(page)
async def config(request, zone_id): changes = False tenantInstance = TenantManagement(request.ctx.tenant_id) await tenantInstance.init(request.ctx.tenant_id) zoneInstance = ZoneManagement(zone_id) await zoneInstance.init(zone_id) await zoneInstance.setSpots() formGeneral = ConfigurationForm(request, zoneInstance, prefix="genForm") formSpots = SpotsAddingForm(request, prefix="spotsForm") # We need the not assigned devices from this tenant deviceList = await tenantInstance.getNotAssignedDevices() if deviceList == Request.REQ_ERROR: raise ServerError("Impossible de charger les capteurs non assignés.") # Creating form and setting device selection formSpots.deviceSelect.choices = deviceList # Informing user if no device is available if deviceList == []: formSpots.deviceSelect.description = "ATTENTION : aucun capteur disponible !" # Handling general configuration if formGeneral.validate_on_submit(): # Deletion clicked if formGeneral.delete.data: print("Zone deletion") res = await Request.deleteZone(zoneInstance.id) if res == Request.REQ_ERROR: raise ServerError("erreur lors de la suppression de la zone") else: print("RES: ", res) return response.redirect("/dashboard") # General form validated elif formGeneral.submitGen.data: print("General form validated") res = await Request.updateZone( zone_id=zone_id, tenant_id=request.ctx.tenant_id, name=formGeneral.name.data, type=formGeneral.type.data, color=Tooling.formatColor(formGeneral.color.data), polygon="" ) if res == Request.REQ_ERROR: raise ServerError("impossible de mettre à jour la zone", 500) changes = True # Checking if user wants to add spots if formSpots.validate_on_submit(): print("Spot adding form validated") lnglat = formSpots.coordinatesInput.data.split(',') res = await Request.createSpot( zone_id=zone_id, device_id=formSpots.deviceSelect.data, type=formSpots.typeSelect.data, coordinates=[float(lnglat[0]) ,float(lnglat[1])] ) if res == Request.REQ_ERROR: raise ServerError("impossible d'ajouter une place", 500) return response.redirect("/parking/zone/"+zone_id+"/spots") rendered_template = await render( 'parking_template.html', request, active_tab_config='true', zone_id=zone_id, zoneInstance=zoneInstance, tenantInstance=tenantInstance, formGeneral=formGeneral, formSpots=formSpots, spotList=Tooling.jsonList(zoneInstance.spots), changesApplied=changes ) return response.html(rendered_template)
def privacy(request): html_file = os.path.join(template, 'privacy.html') with open(html_file) as f: content = f.read() return html(content)
async def test(request): script = autoload_server(model=None, url='http://localhost:5116/bkapp') with open("templates/embed.html") as tmp: templt = tmp.read() return html(Template(templt).render(script=script))