def respond(docs): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps( dict(message=f"{len(docs)} ações atualizadas com sucesso")).encode( "utf-8") return response
def respond(user): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps( dict(message=f"usuario {user.username} adicionado com sucesso") ).encode("utf-8") return response
def respond(access_token): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps( dict(access_token=access_token, token_type="bearer")).encode("utf-8") return response
async def fetch_exchange_data(response: Response): """Simple GET to Binance via ccxt""" # def fetch_data(symbol: str, timeframe: str, limit: int) -> pd.DataFrame: # 1. Grab our data exchange = ccxt.binance() # open high low close data bars = exchange.fetch_ohlcv(symbol="ETH/USDT", timeframe="1d", limit=30) # Create a DF but only with completed timestamps (ie exclude last row) data = pd.DataFrame( bars[:-1], columns=["timestamp", "open", "high", "low", "close", "volume"]) # Make timestamp easier to read data.timestamp = pd.to_datetime(data.timestamp, unit="ms") # 2021-05-11 23:00:00 data_json = pd.DataFrame.to_json(data) # Q: Should I attach this data to Reponse.body? # A: Works! Can do this if we wanted and adjust in Frontend's await fetch response.body = data_json # print(data.head()) # return data_json # Works "{\"timestamp\": {...}}}" return {"response": response, "data_json": data_json} # Works!
def respond(docs): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps( dict(message=f"{len(docs)} investimentos carregadas com sucesso") ).encode("utf-8") return response
async def webhook_event(request: Request, resp: Response): oapi_request = OapiRequest(uri=request.url.path, body=await request.body(), header=OapiHeader(request.headers)) oapi_resp = handle_event(conf, oapi_request) resp.headers['Content-Type'] = oapi_resp.content_type resp.body = oapi_resp.body resp.status_code = oapi_resp.status_code return resp
def read_vite(response: Response): # return {"request": request, "message": "This is the return from /vite GET"} # return {"request": request } # Error # return {"message": "This is the return from /vite GET"} # Works response.body = "Response body content" return { "response": response, "fruit": "apple", "status_code": response.status_code } # Works
def login(data:dict): print('data', ':', data) resp = Response() resp.headers['Content-Type'] = 'application/json;charset=UTF-8' resp.headers['Set-Cookie'] = 'JSESSIONID=8BC8CCFB02A517C887C83B1DE9F4AE17; Path=/fastgate; HttpOnly' login_result = '' with open('.\\fastgate_login.json', 'r', encoding='utf-8') as f: login_result = f.read() resp.body = bytes(login_result, encoding='utf-8') return resp
async def static(path: str, response: Response): try: proxy = requests.get(os.path.join(FRONTEND_DEV_SERVER, path)) except requests.exceptions.ConnectionError: response.status_code = 404 return response else: response.body = proxy.content response.status_code = proxy.status_code response.media_type = proxy.headers["content-type"] return response
async def transmit(self, response: Response): """ Transmit the message to an external service via HTTP, if self.transmit_server is defined by the workflow. Input: self.message: The python dict for a LinuxForHealthDataRecordResponse instance containing the data to be transmitted response: The FastAPI Response object self.verify_certs: Whether to verify certs, True/False, set at the application level in config.py self.transmit_server: The url of external server to transmit the data to Output: The updated Response object """ if self.transmit_server and response: resource_str = decode_to_str(self.message['data']) resource = json.loads(resource_str) transmit_start = datetime.now() self.message['transmit_date'] = str( transmit_start.replace(microsecond=0)) + 'Z' try: async with AsyncClient(verify=self.verify_certs) as client: result = await client.post(self.transmit_server, json=resource) except: transmit_delta = datetime.now() - transmit_start self.message[ 'elapsed_transmit_time'] = transmit_delta.total_seconds() raise transmit_delta = datetime.now() - transmit_start self.message[ 'elapsed_transmit_time'] = transmit_delta.total_seconds() response.body = result.text response.status_code = result.status_code # Merge result headers into response headers with overwrite for key, value in result.headers.items(): if key not in ['Content-Length', 'Content-Language', 'Date']: response.headers[key] = value # Set original LFH message uuid in response header response.headers['LinuxForHealth-MessageId'] = str( self.message['uuid']) self.use_response = True
async def forward(self, request: Request, response: Response) -> Response: url_tail = URL( path=request.url.path.replace("/v0", ""), fragment=request.url.fragment, ) body: bytes = await request.body() resp = await self.client.request( request.method, str(url_tail), params=dict(request.query_params), data=body, headers=dict(request.headers), ) # Prepared response response.body = resp.content response.status_code = resp.status_code response.headers.update(resp.headers) # NOTE: the response is NOT validated! return response
async def proxy_volume(volume: str, obj_path: str) -> Response: # if not (public_dataset(volume) or current_user.can_read(volume)): # raise HTTPException(status_code=401, detail=f"no permission to do proxy requests to dataset {volume}") if volume not in cache: raise HTTPException( status_code=400, detail=f"no volume information available for {volume}") # perform the proxy async with httpx.AsyncClient() as client: bucket = quote(cache[volume].bucket, safe='') obj = quote(cache[volume].path + '/' + obj_path, safe='') proxy_url = f"https://storage.googleapis.com/storage/v1/b/{bucket}/o/{obj}?alt=media" proxy = await client.get(proxy_url) response = Response() response.body = proxy.content response.status_code = proxy.status_code response.headers['Content-Type'] = proxy.headers['Content-Type'] response.headers['Access-Control-Allow-Origin'] = '*' response.headers[ 'Access-Control-Allow-Methods'] = 'POST, GET, DELETE, OPTIONS' response.headers[ 'Access-Control-Allow-Headers'] = 'Authorization, Content-Type' return response
def respond(stocks): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps({"stock_list": stocks}).encode("utf-8") return response
def respond_with_error(message: str = "Erro ao buscar lista de ações"): response = Response() response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR response.body = json.dumps(dict(message=message)).encode("utf-8") return response
def respond(dashboard): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps({"dashboard_info": dashboard}).encode("utf-8") return response
def respond(investments): response = Response() response.status_code = status.HTTP_200_OK response.body = json.dumps({"investments_list": investments}).encode("utf-8") return response
def respond_with_error(message: str = "Erro ao carregar investimentos"): response = Response() response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR response.body = json.dumps(dict(message=message)).encode("utf-8") return response
def respond_with_error(message: str = "Incorrect username or password"): response = Response(headers={"WWW-Authenticate": "Bearer"}) response.status_code = status.HTTP_401_UNAUTHORIZED response.body = json.dumps(dict(message=message)).encode("utf-8") return response