async def get_post_by_id(id: int, db: Session = Depends(get_db)): """Endpoint for viewing post""" post = await get_post(db, id) if not post: raise HTTPException(status_code=404, detail="No post was found") return ShowPost.from_orm(post)
# "HTTP" is an important word here, as SOAP # has a damn hell of different headers. response: str = client.service.DaneSzukajPodmioty( pParametryWyszukiwania=query_params) parsed_response: Union[OrderedDict, None] = xmltodict.parse(response) if parsed_response is None: raise HTTPException( 400, f"Response is malformed. RESPONSE = '{response}'") elif response_body := parsed_response.get("root", {}).get("dane", {}): if isinstance(response_body, list): to_parse = response_body[0] elif response_body.get("Regon"): to_parse = response_body else: error_response_reformatted = { key: response_body.get(value, None) for key, value in parsing_error_dict.items() } return RegonApiNotFoundFailure(**error_response_reformatted) response_reformatted = { key: to_parse.get(value, None) for key, value in parsing_dict.items() } return RegonApiSuccess(**response_reformatted) else: raise HTTPException( 400, f"Response is malformed. RESPONSE = '{response}'")
def validate_underpaid_percentage(cls, v): if v < 0 or v >= 100: raise HTTPException( 422, "Underpaid percentage must be in range from 0 to 99.99") return float(v)
async def _delete(id: DaemonID): try: await store.delete(id=id) except KeyError: raise HTTPException(status_code=404, detail=f'{id} not found in {store!r}')
def get_or_404(self, pk): inst = self.get(pk) if not inst: raise HTTPException(status_code=404) return inst
async def _delete(id: uuid.UUID, workspace: bool = False): try: store.delete(id=id, workspace=workspace) except KeyError: raise HTTPException(status_code=404, detail=f'{id} not found in {store!r}')
def get_valid_project(project_uuid: UUID = PathParam( ..., description="Project unique identifier")) -> UUID: if project_uuid not in _PROJECTS: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project does not exists") return project_uuid
def delete(self, oid): try: del self.DBS[self.dbname][oid] except KeyError: raise HTTPException(status_code=404)
def get(self, oid: str): obj = self.DBS[self.dbname].get(oid) if obj is None: raise HTTPException(status_code=404) return {"id": oid, "item": obj}
from fastapi.exceptions import HTTPException from starlette import status TodoNotFoundException = HTTPException(status_code=status.HTTP_404_NOT_FOUND)
async def create_user(user: users.UserCreate): db_user = await users_utils.get_user_by_email(email=user.email) if db_user: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Email already registered.') return await users_utils.create_user(user=user)
def get_user(session: Session, user_id: int) -> User: user = session.get(User, user_id) if not user: raise HTTPException(status_code=404, detail="User not found") return user
def trade(tradeid: int = 0, rpc: RPC = Depends(get_rpc)): try: return rpc._rpc_trade_status([tradeid])[0] except (RPCException, KeyError): raise HTTPException(status_code=404, detail='Trade not found.')
def check_post_len(post_content: PostContent): post_len = len(post_content.postcontent) if post_len < 1 or post_len > 160: raise HTTPException( status_code=400, detail="Post need to be between 1 and 160 chars long")
async def get_current_active_user(current_user: User = Depends(get_current_user)): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user
async def twitch_webhook_stream_post(data: dict, request: Request): """ { "data": [ { "id": "0123456789", "user_id": "5678", "user_name": "wjdtkdqhs", "game_id": "21779", "community_ids": [], "type": "live", "title": "Best Stream Ever", "viewer_count": 417, "started_at": "2017-12-01T10:09:45Z", "language": "en", "thumbnail_url": "https://link/to/thumbnail.jpg" } ] } """ if await is_request_valid(request): if len(data["data"]) > 0: data = data["data"][0] live = "true" if data.get("type", False) == "live" else "false" else: live = "false" uri = "ws://bot:13337" try: async with websockets.connect(uri) as s: # We don't actually need this, but we have to read it before the bot will accept commands await s.recv() # There are two entries returned, and we need to return both await s.recv() # Define the messages to send going_live_msg = dict( type="run_command", command="stream", channel=getenv("TWITCH_CHANNEL"), args=["live", live], ) reset_wigs_msg = dict( type="run_command", command="wig", channel=getenv("TWITCH_CHANNEL"), args=["reset"], ) # Combine to an interable and loop over them messages = list() if live == "true": # Commands sent when going live messages.append(going_live_msg) else: # Commands sent when going offline messages.append(going_live_msg) messages.append(reset_wigs_msg) for msg in messages: await s.send((json.dumps(msg) + "\n").encode("utf8")) # Check if the message was successful resp = json.loads(await s.recv()) if resp.get("type", "fail") != "success": raise HTTPException(status_code=503) # 204 is a No Content status code return Response(status_code=HTTP_204_NO_CONTENT) except ConnectionRefusedError: print("Unable to connect to bot for stream status change") raise HTTPException(status_code=503) except Exception as e: print(f"Unknown exception trying to send message to bot. {e}") raise HTTPException(status_code=503)
def raise_banned(self) -> None: if self.banned and not self.admin: raise HTTPException(403, "You are banned.")
async def send_specific_joke(index: int): if index > len(all_jokes) or index < 0: raise HTTPException(status_code=404, detail="Index out of range") return {"joke": all_jokes[index]}
async def _status(id: 'uuid.UUID', ): try: return store[id] except KeyError: raise HTTPException(status_code=404, detail=f'{id} not found in {store!r}')
async def index(id: int) -> ContatoResponse: try: contato = ContatoModel.get(ContatoModel.id == id) except ContatoModel.DoesNotExist: raise HTTPException(status_code=404) return ContatoResponse(**contato.__data__)
async def _status(id: DaemonID): try: return store[id] except KeyError: raise HTTPException(status_code=404, detail=f'{id} not found in flow store')
async def user_create(user: UserCreateRequest) -> User: try: user = create_user(**user.dict()) except IntegrityError: raise HTTPException(status_code=400) return User(**user.__data__)
def first_or_404(self): f = self.first() if f is None: raise HTTPException(status_code=404) return f
async def get_token(Bearer: str = Header(None), db: Session = Depends(get_db)): try: user = UC(db).get_user_from_id_token(Bearer) return UserToken.construct(token=user.token) except Exception: raise HTTPException(status_code=404, detail="Could not find this user in the db")
def passwords_match(cls, v, values, **kwargs): if 'new_password' in values and v != values['new_password']: raise HTTPException( status_code=400, detail='Nova senha e confirmação de senha não confere!') return v
class Session(BaseModel): current_user: CurrentUser @router.post('/api/session', response_model=Session) def create_session( params: SessionCreateRequest, ctx: NoLoginContext = Depends(), ): if account_name := userauth.authorize(params.username, params.password): with ctx.session.activate() as session: session.account_name = account_name user = ctx.db.query(models.obslog_user).filter_by( account_name=account_name).one_or_none() if user is None: user = models.obslog_user(account_name=account_name) ctx.db.add(user) ctx.db.commit() return Session(current_user=user) raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY) @router.get('/api/session', response_model=Session) def show_session(ctx: Context = Depends(), ): return Session(current_user=ctx.current_user) @router.delete('/api/session') def destroy_session(ctx: Context = Depends(), ): ctx.session.clear()
async def _create_from_yaml(yamlspec: UploadFile = File(...), uses_files: List[UploadFile] = File(()), pymodules_files: List[UploadFile] = File(())): """ Build a flow using [Flow YAML](https://docs.jina.ai/chapters/yaml/yaml.html#flow-yaml-sytanx) - Upload Flow yamlspec (`yamlspec`) - Yamls that Pods use (`uses_files`) (Optional) - Python modules (`pymodules_files`) that the Pods use (Optional) **yamlspec**: !Flow version: 1.0 with: restful: true pods: - name: encode uses: helloworld.encoder.yml parallel: 2 - name: index uses: helloworld.indexer.yml shards: 2 separated_workspace: true **uses_files**: `helloworld.encoder.yml` !MyEncoder metas: name: myenc workspace: /tmp/blah py_modules: components.py requests: on: [IndexRequest, SearchRequest]: - !Blob2PngURI {} - !EncodeDriver {} - !ExcludeQL with: fields: - buffer - chunks **uses_files**: `helloworld.indexer.yml` !CompoundIndexer components: - !NumpyIndexer with: index_filename: vec.gz metas: name: vecidx workspace: /tmp/blah - !BinaryPbIndexer with: index_filename: chunk.gz metas: name: chunkidx workspace: /tmp/blah metas: name: chunk_indexer workspace: /tmp/blah **pymodules_files**: `components.py` class MyEncoder(BaseImageEncoder): def __init__(self): ... """ with flow_store._session(): try: flow_id, host, port_expose = flow_store._create( config=yamlspec.file, files=list(uses_files) + list(pymodules_files)) except FlowYamlParseException: raise HTTPException(status_code=404, detail=f'Invalid yaml file.') except FlowStartException as e: raise HTTPException(status_code=404, detail=f'Flow couldn\'t get started: {e!r}') return { 'status_code': status.HTTP_200_OK, 'flow_id': flow_id, 'host': host, 'port': port_expose, 'status': 'started' }
expire = datetime.utcnow() + expires_delta jti = str(uuid4()) to_encode.update({"exp": expire}) to_encode.update({"jti": jti}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) token = TokenDataInDB( jti = jti, expire_at = expires_date, ) ret = insert_token(token) return encoded_jwt credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) async def get_current_user(token: str = Depends(oauth2_scheme)): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) print (payload) token_data = TokenDataInDB(**payload) if token_data.username is None: raise credentials_exception # Verify if token not is revoked if token_revoke(token_data): raise credentials_exception except JWTError:
def validate_provider(cls, v): from api import settings if v not in settings.notifiers: raise HTTPException(422, "Unsupported notificaton provider") return v
async def verify_key(x_key: str = Header(...)): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key