def wrapped(request: Request): data = fn() if "ui" in request.query_params: return HTMLResponse(template(request, data)) return data
def root(): with open('/app/app/static/index.html') as f: return HTMLResponse(content=f.read(), status_code=200)
def get_graphiql_response(self) -> HTMLResponse: html = get_graphiql_html() return HTMLResponse(html)
def root(): return HTMLResponse( pkg_resources.resource_string(__name__, "static/index.html"))
def form(request): return HTMLResponse( """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <title>Detect Eye Diseases</title> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8"> <h1>Detect Eye Diseases with Deep Learning Technology</h1> <h2>This example is based on the fast.ai deep learning framework: <a href="https://www.fast.ai/">https://www.fast.ai/</a></h2> <p><strong>Image classifier that detects different categories of eye diseases:<strong> <ul class="list-group"> <li class="list-group-item">Normal Eye</li> <li class="list-group-item">Glaucoma</li> <li class="list-group-item">Retina Disease</li> <li class="list-group-item">Cataract</li> </ul> </p> <form action="/upload" method="post" enctype="multipart/form-data"> <div class="form-group"> Select image to upload: <input type="file" name="file" class="input-sm"> <input type="submit" value="Upload and Analyze Image" class="btn btn-primary"> </div> </form> </div> <div class="col-md-2"> </div> </div> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8"> Or submit a URL: <form action="/classify-url" method="get"> <div class="form-group"> <input type="url" name="url" class="input-sm"> <input type="submit" value="Fetch and Analyze image" class="btn btn-primary"> </div> </form> </div> <div class="col-md-2"> </div> </div> </div> </body> </html> """)
def home(request): # return render_template("index.html") html_file = path / 'templates' / 'index.html' return HTMLResponse(html_file.open().read())
def index(request): html = path / 'view/index.html' return HTMLResponse(open(html).read())
async def homepage(request): if request.method == "POST": values = await request.form() print("POST params:", values) if values['metricInput'].startswith("use-"): if USE_ENABLED is False: raise ValueError("USE not enabled.") sentences, graph, lang = summarize_use( values['text'], model_name=values['metricInput'][4:]) elif values['metricInput'].startswith("laser"): if LASER_ENABLED is False: raise ValueError("LASER not enabled.") sentences, graph, lang = summarize_laser(values['text']) else: sentences, graph, lang = summarize_textrank(values['text']) print("Language dected:", lang) keywords, lemma2words, word_graph, pagerank_scores = _keywords( values['text']) if lang == "en": keyword_formatted = [ key + " %.2f (%s)" % (score, ", ".join(lemma2words[key])) for score, key in keywords[:int(values["n_keywords"])] ] else: keyword_formatted = [ key + " %.2f" % score for score, key in keywords[:int(values["n_keywords"])] ] if graph is None: return HTMLResponse(sentences[0] + "\nDectected language: " + lang) # print([sentence.token for sentence in sentences if sentence.token]) try: add_alpha(sentences, int(values["n_sentences"])) except (ValueError, KeyError): print("Warning: invalid *n* parameter passed!") add_alpha(sentences) n_paragraphs = max([x.paragraph for x in sentences]) + 1 paragraphs = [] for i in range(n_paragraphs): paragraphs.append( sorted([x for x in sentences if x.paragraph == i], key=lambda x: x.index)) node_mapping, edges = reconstruct_graph(graph, sentences, lang) word_node_mapping, word_edges = reconstruct_word_graph( word_graph, pagerank_scores, top_n=int(values["n_keywords"]) * 5) response = templates.TemplateResponse( 'index.jinja', dict(request=request, paragraphs=paragraphs, text=values['text'], n_sentences=values["n_sentences"], n_keywords=values["n_keywords"], metricInput=values["metricInput"], word_edges=word_edges, edges=edges, n_nodes=len(node_mapping), n_word_nodes=len(word_node_mapping), node_mapping=node_mapping, word_node_mapping=word_node_mapping, stats=[("# of Sentence Nodes", len(node_mapping)), ("# of Sentence Edges", len(edges)), ("Max Edge Weight", "%.4f" % max([float(x[2]) for x in edges])), ("Min Edge Weight", "%.4f" % min([float(x[2]) for x in edges])), ("Max Node Score", "%.4f" % max([float(x[3]) for x in node_mapping.values()])), ("Min Node Score", "%.4f" % min([float(x[3]) for x in node_mapping.values()]))], keywords=keyword_formatted)) else: response = templates.TemplateResponse( 'index.jinja', dict(request=request, text="", n_sentences=2, n_keywords=5, metricInput="textrank")) return response
async def handle_graphiql(self, request: Request) -> Response: text = GRAPHIQL.replace("{{REQUEST_PATH}}", json.dumps(request.url.path)) return HTMLResponse(text)
views ''' async def index(request): ip = request.headers.get('X-Real-IP', '127.0.0.1') if (answer := request.query_params.get('answer')) is None: prefix, time_remain = powser.get_challenge(ip) return HTMLResponse(config.pow_html.render(dict( prefix=prefix, difficulty=powser.difficulty, ip=ip, time_remain=time_remain, min_refresh_time=powser.min_refresh_time, ))) res, msg = powser.verify_client(ip, str(answer), with_msg=True) if not res: return HTMLResponse(msg) user = await db.create_user(token_urlsafe(16), config.user_init_balance) return RedirectResponse(url='/' + user.uid, status_code=HTTP_303_SEE_OTHER) @login_required async def home(request, user): if user.balance >= 10000: msg = config.flag elif bool(user.bankrupt): msg = 'You are bankrupt ¯\_(ツ)_/¯' else: msg = "Once you have >= $10,000, you'll see the flag in this page." task = None if request.method == 'POST': if user.balance <= 0:
async def __call__(self, receive, send): response = HTMLResponse() await response(receive, send)
def dashboard(skip: int = 0, db: Session = Depends(get_db)): items = crud.get_items(db=db, skip=skip) template = Template(''' <table style="width:100%"> <script> function refreshPage(){ window.location.reload(); } </script> <tr> <th>ID</th> <th>Fecha</th> <th>Incidencia</th> <th>Detalle</th> <th>Mapa</th> <th>Foto</th> <th>Usuario</th> <th>Estado</th> </tr> {% for item in reversed(items) %} <tr> <td>{{ item['id'] }}</td> <td>{{ item['timestamp'] }}</td> <td>{{ item['inc_type'] }}</td> <td>{{ item['inc_detail'] }}</td> <td><a href={{ item['url'] }}>{{ item['lat'] }} {{ item['lon'] }}</a></td> <td><iframe src={{ item['pic'] }}></iframe></td> <td>{{ item['owner_id'] }}</td> {% if item['is_active'] %} <td> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $('a#active').bind('click', function() { $.getJSON('/update/{{ item['id'] }}/', function(data) { //do nothing }); return refreshPage(); }); }); </script> <div class='container'> <form> <a href=# id=active><button class='btn button2'>Activo</button></a> </form> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $('a#move').bind('click', function() { $.getJSON('/move/{{ item['id'] }}/', function(data) { //do nothing }); return refreshPage(); }); }); </script> <div class='container'> <form> <a href=# id=move><button class='btn button3'>Invalidar</button></a> </form> </div> </td> {% else %} <td> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $('a#solved').bind('click', function() { $.getJSON('/update/{{ item['id'] }}/', function(data) { //do nothing }); return refreshPage(); }); }); </script> <div class='container'> <form> <a href=# id=solved><button class='btn button1'>Resuelto</button></a> </form> </div> </td> {% endif %} </tr> {% endfor %} </table> <style> table { margin: 0 auto; font-size: medium; border: 1px solid black; } td { background-color: #ccffff; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; font-family: 'Helvetica'; } td { font-weight: lighter; } .button1 {background-color: #4CAF50;} .button2 {background-color: #FF0000;} .button3 {background-color: #CC99FF;} </style> ''') template.globals['reversed'] = reversed return HTMLResponse(template.render(items=items))
def index(request): html = Path('app/view/index.html') print(html.open().read()) return HTMLResponse(html.open().read())
async def homepage(request): # template = path / 'app/view' / 'keywords.html' # context = {"request": request} # return templates.TemplateResponse(template, context) html_file = path / 'app/view' / 'keywords.html' return HTMLResponse(html_file.open().read())
async def progress(request): template = app.get_template('index.html') content = template.render(request=request) return HTMLResponse(content)
async def handle_playground(self, request: Request) -> Response: text = get_playground_template(str(request.url)) return HTMLResponse(text)
def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: html = """ <!DOCTYPE html> <html lang="en-US"> <body onload="run()"> </body> </html> <script> 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr; if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1); } else { qp = location.search.substring(1); } arr = qp.split("&") arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';}) qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value) } ) : {} isValid = qp.state === sentState if (( oauth2.auth.schema.get("flow") === "accessCode"|| oauth2.auth.schema.get("flow") === "authorizationCode" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server" }); } if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); } oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server" }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); } </script> """ return HTMLResponse(content=html)
async def verify_user(request, call_next): if request.user.is_authenticated: if request.user.display_name == request.path_params['user_id']: response = await call_next(request) return response return HTMLResponse('Forbidden', status_code=403)
async def swagger_doc_handler(request): return HTMLResponse(content=self.doc_html, media_type='text/html')
async def index(): return HTMLResponse(index_html)
def form(request): index_html = path/'static'/'index.html' return HTMLResponse(index_html.open().read())
import time from uuid import uuid4 from starlette.applications import Starlette from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response app = Starlette() # first add ten more routes to load routing system # ------------------------------------------------ for n in range(5): app.route(f"/route-{n}")(HTMLResponse('ok')) app.route(f"/route-dyn-{n}/{{part}}")(HTMLResponse('ok')) # then prepare endpoints for the benchmark # ---------------------------------------- @app.route("/html") async def html(request): """Return HTML content and a custom header.""" content = "<b>HTML OK</b>" headers = {'x-time': f"{time.time()}"} return HTMLResponse(content, headers=headers) @app.route("/upload", methods=['POST']) async def upload(request): """Load multipart data and store it as a file.""" formdata = await request.form() if 'file' not in formdata: return Response('ERROR', status_code=400)
async def _(_): return HTMLResponse("<pre>not found</pre>", status_code=404)
async def html(request): """Return HTML content and a custom header.""" content = "<b>HTML OK</b>" headers = {'x-time': f"{time.time()}"} return HTMLResponse(content, headers=headers)
async def render_playground( # pylint: disable=unused-argument self, request: Request) -> Response: return HTMLResponse(PLAYGROUND_HTML)
async def get(self, request): return HTMLResponse(html)
def index(request): html = path / 'view' / 'index.html' return HTMLResponse(html.open().read())
async def get(): return HTMLResponse(html)
async def homepage(request): html_file = path / 'view' / 'index.html' return HTMLResponse(html_file.open().read())
def form(request): with open('templates/home.html', 'r') as f: st = f.read() return HTMLResponse(st)