async def get_profile(profile_id: str): profile = await get_profile(profile_id) if not profile: raise ServerError('u dun messd up bruther', status_code=500) return { 'profile': { 'id': str(profile['id']), 'name': str(profile['name']), 'profile_img': str(profile['profile_img']), 'description': str(profile['description']), 'phone_number': str(profile['phone_number']) } }
def authorize(request): if aiogoogle.openid_connect.is_ready(CLIENT_CREDS): uri = aiogoogle.openid_connect.authorization_url( client_creds=CLIENT_CREDS, state=state, nonce=nonce, access_type="offline", include_granted_scopes=True, login_hint=EMAIL, prompt="select_account", ) # Step A return response.redirect(uri) else: raise ServerError("Client doesn't have enough info for Oauth2")
def __init__(self): try: config = url_config() self.upload_folder = config["upload_folder"] self.max_connect = config["max_connect"] self.allowed_formats = config["allowed_formats"] self.max_size = config["max_size"] self.chunk_size = config["chunk_size"] logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.ERROR, filename=os.path.join(config["log_folder"], config["log_file"])) self.log = logging.getLogger(__name__) except: raise ServerError("Internal Server Error", status_code=500)
async def callback(request): if request.args.get('error'): return response.text('whoops!', 401) elif request.args.get('code'): returned_state = request.args['state'][0] if returned_state != state: raise ServerError('NO') full_user_creds = await aiogoogle.oauth2.build_user_creds( grant = request.args.get('code'), client_creds = CLIENT_CREDS ) await refresh(full_user_creds) expire_creds_then_refresh(full_user_creds) await revoke(full_user_creds) return response.text('passed')
async def create(cls, sanic_app, scope: ASGIScope, receive: ASGIReceive, send: ASGISend) -> "ASGIApp": instance = cls() instance.sanic_app = sanic_app instance.transport = MockTransport(scope, receive, send) instance.transport.loop = sanic_app.loop setattr(instance.transport, "add_task", sanic_app.loop.create_task) headers = Header([(key.decode("latin-1"), value.decode("latin-1")) for key, value in scope.get("headers", [])]) instance.lifespan = Lifespan(instance) if scope["type"] == "lifespan": await instance.lifespan(scope, receive, send) else: path = (scope["path"][1:] if scope["path"].startswith("/") else scope["path"]) url = "/".join([scope.get("root_path", ""), quote(path)]) url_bytes = url.encode("latin-1") url_bytes += b"?" + scope["query_string"] if scope["type"] == "http": version = scope["http_version"] method = scope["method"] elif scope["type"] == "websocket": version = "1.1" method = "GET" instance.ws = instance.transport.create_websocket_connection( send, receive) await instance.ws.accept() else: raise ServerError("Received unknown ASGI scope") request_class = sanic_app.request_class or Request instance.request = request_class( url_bytes, headers, version, method, instance.transport, sanic_app, ) instance.request.stream = instance instance.request_body = True instance.request.conn_info = ConnInfo(instance.transport) return instance
async def stream_response(self, response): """ Streams a response to the client asynchronously. Attaches the transport to the response so the response consumer can write to the response as needed. """ if self._response_timeout_handler: self._response_timeout_handler.cancel() self._response_timeout_handler = None try: keep_alive = self.keep_alive response.transport = self.transport await response.stream(self.request.version, keep_alive, self.keep_alive_timeout) if self.has_log: netlog.info('', extra={ 'status': response.status, 'byte': -1, 'host': '{0}:{1}'.format(self.request.ip[0], self.request.ip[1]), 'request': '{0} {1}'.format(self.request.method, self.request.url) }) except AttributeError: log.error(('Invalid response object for url {}, ' 'Expected Type: HTTPResponse, Actual Type: {}').format( self.url, type(response))) self.write_error(ServerError('Invalid response type')) except RuntimeError: log.error('Connection lost before response written @ {}'.format( self.request.ip)) except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format( repr(e))) finally: if not keep_alive: self.transport.close() else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback) self._last_response_time = current_time self.cleanup()
async def create_event(name: str, description: str, location: str, time: str, accessibility: str, tags: List[str], groups: List[str], profiles: List[Dict[str, str]]): event_id = await create_event(name, description, location, time, accessibility) await add_event_tags(event_id, tags) await add_event_groups(event_id, groups) for profile in profiles: await add_event_profile(event_id, profile['profile_id'], profile['role']) if not event_id: raise ServerError('u dun messd up bruther', status_code=500) return {'event_id': str(event_id)}
async def weather(_, city): """ fethces the forecast for a given city """ try: response = await fetch_weather(city) return json(format_response(response)) except NotFoundException as error: _logger.exception(error) return json({"error": "city was not found", "city": city}) except Exception as error: _logger.exception("error %s getting weather for %s", error, city) raise ServerError( f"could not get weather for {city}. please try again later")
async def get_metric_ts(request, metric, store_id): """ Get timeseries for store against their benchmark :param request: :return: JSON """ metric_rank = feat.format_issues_columns(metric) + "_rank" if any([m not in stores_ranked_df.columns for m in [metric, metric_rank]]): raise ServerError(status_code=400, message=f"Metric does not exist") tmp_df = feat.get_store_bechmark_comparison(store_id, metric, stores_ranked_df, benchmark_df).dropna() tmp_df.columns = ["metric", "benchmark"] tmp_df.reset_index(inplace=True) tmp_df.date_comment = tmp_df.date_comment.astype(str) return json(tmp_df.to_dict("records"))
async def used_brands_name(request): # 接受参数 date = request.json date['create_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # print(date) # print(type(date)) # 将数据保存进ES es = Elasticsearch(["http://10.168.3.132:9200/"]) index_name = 'used_name' try: es.index(index=index_name, doc_type='used_name', body=date) except Exception: raise ServerError('ES Database index exception', status_code=500) return json({'message': 'ok'})
async def answer(request): try: question = request.args["question"][0] if question == "": return response.json({'message': 'No question given'}, status=400) spans, paras = await app.qa.answer_question(question) answers = select_answers(paras, spans, span_bound, 10) answers = answers[:n_to_return] best_span = max(answers[0].answers, key=lambda x: x.conf) log.info("Answered \"%s\" (with web search): \"%s\"", question, answers[0].original_text[best_span.start:best_span.end]) return json([x.to_json() for x in answers]) except Exception as e: log.info("Error: " + str(e)) raise ServerError(e, status_code=500)
async def view(request): tenantInstance = TenantManagement(request.ctx.tenant_id) await tenantInstance.init(request.ctx.tenant_id) pagination = Pagination(request) # Handling the two existing tabs (all devices & not assigned ones) tab_all = False tab_notAssigned = False # Not assigned devices data table if request.raw_args.get('type') == "notassigned": tab_notAssigned = True await tenantInstance.setNotAssignedDevices( page=pagination.page_number, pagesize=pagination.page_size ) devices = tenantInstance.notAssignedDevices pagination.setElementsNumber(tenantInstance.devicesNotAssignedCount) else: # All devices of the tenant tab_all = True await tenantInstance.setDevices( page=pagination.page_number, pagesize=pagination.page_size ) devices = tenantInstance.devices pagination.setElementsNumber(tenantInstance.devicesCount) # User wants to delete the device if request.method == 'POST': print("Deletion of device_id : ", request.form.get('device-id')) res = await Request.deleteDevice(request.form.get('device-id')) if res == Request.REQ_ERROR: raise ServerError("impossible de supprimer le capteur") return response.redirect("/dashboard") rendered_template = await render( "devices_template.html", request, devices=devices, pagination=pagination, active_tab_all=tab_all, active_tab_notassigned=tab_notAssigned ) return response.html(rendered_template)
async def turn_off_handler( request: Request, ip_address: str, phone_id: str, device_id: str, device_password: str, ) -> HTTPResponse: """Use for handling requests to /switcher/turn_off. Args: request: ``sanic``'s request object. ip_address: the local ip address. phone_id: the extracted phone id. device_id: the extracted device id. device_password: the extracted device password. Raises: sanic.exceptions.ServerError: when encounterd any error. Returns: Json object represnting the request status. More information is available in the ``Usage`` section. Note: Accepts arguments as json body or query parameters. """ try: async with SwitcherV2Api( get_running_loop(), ip_address, phone_id, device_id, device_password, ) as swapi: response = await swapi.control_device(COMMAND_OFF) if (response and response.msg_type == messages.ResponseMessageType.CONTROL): return json({consts.KEY_SUCCESSFUL: response.successful}) return json({ consts.KEY_SUCCESSFUL: False, consts.KEY_MESSAGE: "Failed turning off the device.", }) except ExceptionSet as exc: raise ServerError("Failed turning off the device.", 500) from exc
async def auth_ehall(session: aiohttp.ClientSession, cookies: dict): """ 登录到 ehall 平台 """ # 载入 Cookies auth_server_load_cookies(session, cookies) async with session.get( 'http://ehall.sdut.edu.cn/login?service=http://ehall.sdut.edu.cn/new/ehall.html' ) as resp: url = str(resp.url) if url == 'http://ehall.sdut.edu.cn/new/ehall.html': return True else: if '?ticket=' in url: raise ServerError('认证错误,请重试') print(url) raise Unauthorized('登录失败,可能是\n1. 登录凭证过期\n2. 您主动退出了登录\n3. 您修改了账号密码')
def get(self, *args): base_get = Router.get if hasattr(base_get, "__wrapped__"): base_get = base_get.__wrapped__ if len(args) == 1: path = args[0].path else: path = args[0] bound_get = base_get.__get__(self, Router) get_results = list(bound_get(*args)) if path == "/server-error": from sanic.exceptions import ServerError raise ServerError("Server Error") return get_results
async def ports_open(self, request, localip): clientid = self.host2clientid(request) try: payload = json.loads(request.body.decode("utf-8")) except: raise ServerError("POST body is not valid", 500) response = await ipc.async_http_raw( "POST", SOCK_DATABASE, "/append/list/{}/open_{}".format(clientid, localip), request.body) if ipc.response_valid(response, dict): return sanic.response.json(response["text"]) logger.error( "Unable to save ports open for client {} and IP {}, port: {}". format(clientid, localip, request.body)) return sanic.response.text("Error", status=500)
async def register_client(self, request, publicip, hostname): root = self.hostname2root(hostname) if root is None: raise ServerError("Hostname is not valid", 500) newid = misc.random_id() args = request.raw_args if "port" in args: port = int(args["port"]) else: port = self.main_server["port"] redir = "http://{}.{}:{}{}".format(newid, root, port, self.config["redirect_initial"]) return sanic.response.json({ "redirect": redir, "domain": "{}.{}".format(newid, root) })
async def get_selection(selection_id: str): selection = await get_selection(selection_id) if not selection: raise ServerError('u dun messd up bruther', status_code=500) selection_profiles = await get_selection_profiles(selection_id) return { 'selection': { 'id': str(selection['id']), 'name': str(selection['name']), 'poll_id': str(selection['poll_id']), 'profiles': [str(profile['id']) for profile in selection_profiles] } }
def wrap_exception(exc): if isinstance(exc, SanicException): return exc args = getattr(exc, "args", []) message = repr(exc) if args: try: next_line = str(args[0]) message = message + "\n" + next_line except IndexError: pass try: next_line = args[1] message = message + "\n" + next_line except IndexError: pass return ServerError(message=message)
async def stream_response(self, response): """ Streams a response to the client asynchronously. Attaches the transport to the response so the response consumer can write to the response as needed. """ if self._response_timeout_handler: self._response_timeout_handler.cancel() self._response_timeout_handler = None try: keep_alive = self.keep_alive response.protocol = self await response.stream( self.request.version, keep_alive, self.keep_alive_timeout ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = time() self.cleanup()
async def map(request): tenantInstance = TenantManagement(request.ctx.tenant_id) await tenantInstance.init(request.ctx.tenant_id) await tenantInstance.setZones() if tenantInstance.zones is None: raise ServerError("No zones in DB", status_code=500) for zone in tenantInstance.zones: await zone.setSpots() zonesJson = Tooling.jsonList(tenantInstance.zones) rendered_template = await render("map_template.html", request, tenantInstance=tenantInstance, zoneList=zonesJson) return response.html(rendered_template)
async def generate_questions(request): args = getattr(request, "args", None) logger.info(f"Got generate questions request with args {args}") args_dict = dict(args) if args else {} locale_arg = args_dict.get("locale", []) size_arg = args_dict.get("size", []) locale = locale_arg[0] if locale_arg else "en" size = size_arg[0] if size_arg else 20 if "-" in locale: locale = locale.split("-")[0] if locale not in questions_by_locale: raise InvalidUsage(f"Invalid locale: {locale}") try: logger.info(f"Preparing set of {size} question in {locale} language") return jsonify({"questions": collect_questions(locale, size)}, ensure_ascii=False) except Exception as e: return ServerError("Couldn't prepare a set of questions")
async def get_user(user_id: str, retrieving_user=False): user = await get_user(user_id) if not user: raise ServerError('u dun messd up bruther', status_code=500) if retrieving_user: return { 'user_id': str(user['id']), 'username': str(user['username']), } return { 'user': { 'id': str(user['id']), 'username': str(user['username']), } }
async def get_paste(self, request, shortlink): query = """ SELECT * FROM pastes WHERE shortlink = '{shortlink}' and expired = false """.format(shortlink=shortlink) row = await self.psql_client.fetchrow(query) if not row: raise ServerError('Given shortlink not found or expired', status_code=404) shortlink, bucket_name = parse_paste_path(row['paste_content_link']) paste_content = self.minio_client.get_object( bucket_name=bucket_name, object_name=shortlink, ).read(decode_content=True) return sanic_json({ 'paste_content': paste_content, })
def write_response(self, response): """ Writes response content synchronously to the transport. """ if self._response_timeout_handler: self._response_timeout_handler.cancel() self._response_timeout_handler = None try: keep_alive = self.keep_alive self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout ) ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = current_time self.cleanup()
async def remove_check(request, zone_id): # removing the zone # removing the spots if needed # temporary redirection to dashboard of tenant tenantInstance = TenantManagement(request.ctx.tenant_id) await tenantInstance.init(request.ctx.tenant_id) await tenantInstance.setZones() if tenantInstance.zones is None: raise ServerError("No zones in DB", status_code=500) rendered_template = await render( "dashboard_template.html", request, tenantInstance=tenantInstance, removed_zone=True ) return response.html(rendered_template)
def __init__( self, header: Type[BaseModel] = None, query: Type[BaseModel] = None, path: Type[BaseModel] = None, body: Type[BaseModel] = None, form: Type[BaseModel] = None, error: Type[SanicException] = None, ) -> None: """ The param must be a BaseModel class or must inherit from BaseModel \n if listed, the same model name's model will use strict mode """ try: if body and form: raise AssertionError( "sanic-dantic: " + "body and form cannot be used at the same time.") self.items = { "header": header, "path": path, "query": query, "form": form, "body": body, "error": error } for model in [header, path, query, form, body]: if model and BaseModel not in getmro(model): raise AssertionError( "sanic-dantic: " + "model must inherited from Pydantic.BaseModel") if error and SanicException not in getmro(error): raise AssertionError( "sanic-dantic: " + "error must inherited from SanicException") except AssertionError as e: error_logger.error(e) raise ServerError(str(e))
async def callDelete(expectedStatus): try: async with request.app.ctx.usermgrd.delete( f'http://localhost/{user.name}') as resp: data = await resp.json() status = data['status'] if status == 'user_not_found': request.ctx.logger.warning(__name__ + '.delete.user_gone') return None elif status != expectedStatus: request.ctx.logger.error(__name__ + '.delete.usermgrd_error', reason=data['status']) raise ServerError('backend') return data except aiohttp.ClientConnectionError: request.ctx.logger.error(__name__ + '.delete.usermgrd_connect_failure') raise ServiceUnavailable('backend')
async def callback(request): if request.args.get("error"): error = { "error": request.args.get("error"), "error_description": request.args.get("error_description"), } return response.json(error) elif request.args.get("code"): returned_state = request.args["state"][0] # Check state if returned_state != state: raise ServerError("NO") # Step D & E (D send grant code, E receive token info) full_user_creds = await aiogoogle.oauth2.build_user_creds( grant=request.args.get("code"), client_creds=CLIENT_CREDS) return response.json(full_user_creds) else: # Should either receive a code or an error return response.text("Something's probably wrong with your callback")
async def server(request, name, value): """Quick and dirty API. Async for fun.""" limit = int(request.args.get('limit', 3)) offset = int(request.args.get('offset', 0)) format = request.args.get('format', 'json') logger.info('🙇 Requesting {0} (offset={1}) items in {2}'.format( limit, offset, format)) columns = request.args.get('columns') column_names = columns and columns.split(',') or app.config.columns sirets = retrieve_sirets(name, value, offset=offset, limit=limit) if not sirets: raise ServerError('😢 No entry found for {0}/{1}'.format(name, value)) logger.info('🐿 Retrieving {0} results for the {1}/{2} couple'.format( len(sirets), name, value)) logger.info('🍫 Returning {0} results in {1}'.format(len(sirets), format)) rows = [ decode_siret(retrieve_siret(siret), column_names) for siret in sirets ] return format_response(rows, format, column_names)