async def html(): """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 get(): return HTMLResponse(html)
async def req_ok(): return HTMLResponse('ok')
async def req_ok_dyn(part): return HTMLResponse('ok')
def home(): with open("./html/index.html") as index123: html = index123.read() return HTMLResponse(content=html, status_code=200)
def upload_form(): """ Upload a YAML file that specifies an experiment. See <a href='#operations-private-process_form_init_exp_post'> the POST description</a> for more detail on the file. """ warning = "" if rj.jsonget("exp_config"): warning = dedent( """<div style="color: #f00;"> <p>Warning: an experiment is already set! Visit [url]:8421/reset to reset the expeirment</p> </div> """ ) password = dedent( """ <h2 style="text-align: center;">Step 1: create new username/password.</h2> <div style="text-align: center; padding: 10px;"> <p>This username/password distinguishes you from any other internet user.</p> <form action="/create_user" enctype="multipart/form-data" method="post"> <ul> <li>Username: <input name="username" placeholder="username" type="text" /></li> <li>Password: <input name="password" placeholder="password" type="text" /></li> <li>Confirm password: <input name="password2" placeholder="password" type="text" /></li> </ul> <input type="submit" value="Create user"> </form> <p> <b>Do not lose this username/password!</b> After you've created a username/password <i>and written it down </i>, then you can create a new experiment. It'll ask for the username/password you just created.</p> </div> """ ) if CREDS_FILE.exists(): with open(CREDS_FILE, "r") as f: passwords = json.load(f) logger.warning(f"passwords={passwords}") if len(passwords): user = list(passwords.keys())[0] letters = list(user) for k, letter in enumerate(letters): if k in [0, len(letters) - 1]: continue letters[k] = "*" user = "".join(letters) password = ( "<div style='text-align: center; padding: 10px;'>" f"<p>A user with name <code>{user}</code> has been created " "(only first and last letters shown). " "Do you know the password?</p>" "</div>" ) body = dedent( f"""<body> <div style="display: table; margin: 0 auto; max-width: 600px;"> <div> <ul> <li> <a href="https://stsievert.com/salmon/"> General Salmon documentation </a> </li> <li> <a href="/docs#/private/process_form_init_exp_post"> Detailed /init_exp endpoint documentation </a> </li> </div> <div style="text-align: center; padding: 10px;"> <p>Two steps are required:<p> <ol> <li>Creating a username/password.</li> <li>Creating a new experiment.</li> </ol> </div> {password} <h2 style="text-align: center;">Step 2: create new experiment.</h2> <h3 style="text-align: center;">Option 1: initialize new experiment.</h3> <div style="text-align: center; padding: 10px;"> <form action="/init_exp" enctype="multipart/form-data" method="post"> <ul> <li>Experiment parameters (YAML file): <input name="exp" type="file"></li> <li>Images/movies (ZIP file, optional): <input name="targets" type="file"></li> </ul> <input type="submit" value="Create experiment"> </form> {warning} </div> <h3 style="text-align: center;">Option 2: restore an old experiment.</h3> <div style="text-align: center; padding: 10px;"> <p>Instructions: <ol style="text-align: left;"> <li>Upload database dump from Salmon. The name should look like <code>exp-2020-03-12-v0.3.1.rdb</code> if downloaded on March 12th, 2020.</li> <li>Restart the server. On Amazon EC2, this means choosing the EC2 instance state "reboot".</li> </ol> </p> <form action="/init_exp" enctype="multipart/form-data" method="post"> <ul> <li>Database file : <input name="rdb" type="file"></li> </ul> <input type="submit" value="Create experiment"> </form> <p> This may fail. See the documentation FAQs for more detail and tips to resolve it: <a href="https://docs.stsievert.com/salmon/installation#troubleshooting">https://docs.stsievert.com/salmon/installation#troubleshooting</a>. </p> </div> </div> </body> """ ) return HTMLResponse(content=body)
async def mock_function(*args, **kwargs): request = kwargs['request'] token = kwargs['token'] if token == 'NO_TOKEN': if response_class is HTMLResponse or 'text/html' in request.headers[ 'accept']: response = HTMLResponse(self.admin.login_page( welcome_message='Login Required'), status_code=401) response.set_cookie('token', 'INVALID') response.set_cookie('ref', request.__dict__['scope']['path']) return response try: token = self.decode_token(token)[1] self.log.debug(f"decoded token: {token}") except Exception: self.log.exception(f"error decoding token") if response_class is HTMLResponse: response = HTMLResponse(self.admin.login_page( welcome_message='Login Required'), status_code=401) response.set_cookie('token', 'INVALID') response.set_cookie('ref', request.__dict__['scope']['path']) return response raise HTTPException( status_code=401, detail=f"not authorized, invalid or expired") allowed = False for auth_type, values in permissions.items(): if not auth_type in token['permissions']: self.log.warning(f"{auth_type} is required") continue for value in values: if value in token['permissions'][auth_type]: allowed = True break if not allowed: if response_class is HTMLResponse: response = HTMLResponse(self.admin.forbidden_page(), status_code=403) response.set_cookie('token', 'INVALID') return response raise HTTPException( status_code=403, detail= f"not authorized, permissions required: {permissions}") if 'access_token' in kwargs: kwargs['access_token'] = token if not send_token: del kwargs['token'] if not send_request: del kwargs['request'] result = func(*args, **kwargs) if asyncio.iscoroutine(result): return await result return result
def art_view(): return HTMLResponse(data)
async def http_server( request: Request, remotepath: str, order: str = "asc", # desc , asc sort: str = "name", # name, time, size ): desc = order == "desc" name = sort == "name" time = sort == "time" size = sort == "size" global _root_dir global _api assert _api remotepath = remotepath.strip("/") _rp = Path(_root_dir) / remotepath _rp_str = _rp.as_posix() _range = request.headers.get("range") if not _api.exists(_rp_str): raise HTTPException(status_code=404, detail="Item not found") is_dir = _api.is_dir(_rp_str) if is_dir: chunks = ["/"] + (remotepath.split("/") if remotepath != "" else []) navigation = [(i - 1, "../" * (len(chunks) - i), name) for i, name in enumerate(chunks, 1)] pcs_files = _api.list(_rp_str, desc=desc, name=name, time=time, size=size) entries = [] for f in pcs_files: p = Path(f.path) entries.append((f.is_dir, p.name, f.size, format_date(f.mtime or 0))) cn = _html_tempt.render(root_dir=remotepath, navigation=navigation, entries=entries) return HTMLResponse(cn) else: range_request_io = _api.file_stream(_rp_str) length = len(range_request_io) headers: Dict[str, str] = { "accept-ranges": "bytes", "connection": "Keep-Alive", } if _range: assert _range.startswith("bytes=") status_code = 206 start, end = _range[6:].split("-") _s, _e = int(start or 0), int(end or length - 1) _io = fake_io(range_request_io, _s, _e) headers["content-range"] = f"bytes {_s}-{_e}/{length}" headers["content-length"] = str(_e - _s + 1) else: status_code = 200 _io = fake_io(range_request_io) headers["content-length"] = str(length) return StreamingResponse(_io, status_code=status_code, headers=headers)
async def get(): return HTMLResponse(html % ('6ec37deb-d87d-4c42-a0cd-3a29ac1cbb2d', '64e42832-d857-4e38-b1ad-c785157c3c12'))
async def get(self_id, another): return HTMLResponse(html % (self_id, another))