Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /trisongz_lazyops /examples /v1 /lazyapi_rpc.py
| ## Based on the Original Example from fastapi-jsonprc | |
| from contextlib import asynccontextmanager | |
| from lazyops.lazyrpc import * | |
| from lazyops.lazydatabase import LazyDB, LazyDBConfig, PklDBCache | |
| from lazyops import get_logger | |
| logger = get_logger('LazyTest') | |
| # schemas | |
| class Balance(BaseModel): | |
| """Account balance""" | |
| amount: int = Field(..., example=100) | |
| currency: str = Field(..., example='USD') | |
| # errors | |
| class AuthError(BaseError): | |
| CODE = 7000 | |
| MESSAGE = 'Auth error' | |
| class AccountNotFound(BaseError): | |
| CODE = 6000 | |
| MESSAGE = 'Account not found' | |
| class NotEnoughMoney(BaseError): | |
| CODE = 6001 | |
| MESSAGE = 'Not enough money' | |
| class DataModel(BaseModel): | |
| balance: Balance | |
| # Initialize the Pickle DB Cache | |
| lazydbcache = PklDBCache(save_path='my_cache', cache_name='lazyrpc_cache') | |
| # Define a User Schema, many fields are already autogenerated, as seen below in the Seed Data | |
| user_schema_config = { | |
| 'user': { | |
| 'name': (str, ...), | |
| } | |
| } | |
| # Define schema(s) | |
| schema_config = { | |
| 'account': { | |
| 'account_id': (str, ...), | |
| 'owner': (str, ...), | |
| 'amount': (float, 0.00), | |
| 'currency': (str, 'USD') | |
| } | |
| } | |
| # Provide Init Seed Data | |
| seed_data = { | |
| 'user': [ | |
| {'username': 'joe_1', 'pw': 'secure1', 'role': 'admin', 'password': 'securepass1', 'name': 'Joe Schmoe'}, | |
| {'username': 'lucy_2', 'pw': 'secure2', 'role': 'regular', 'password': 'securepass2', 'name': 'Lucy Lu'}, | |
| {'username': 'lucky_3', 'pw': 'secure3', 'role': 'regular', 'password': 'securepass3', 'name': 'Lucky Duck'}, | |
| {'username': 'magic_4', 'pw': 'secure4', 'role': 'regular', 'password': 'securepass4', 'name': 'Magic Tragic'}, | |
| {'username': 'list_5', 'pw': 'secure5', 'role': 'regular', 'password': 'securepass5', 'name': 'List Smith'}, | |
| {'username': 'mad_6', 'pw': 'secure6', 'role': 'regular', 'password': 'securepass6', 'name': 'Mad Dad'}, | |
| ], | |
| 'account': [ | |
| {'account_id': 'user_1_1', 'owner': 'joe_1', 'amount': 5000.0}, | |
| {'account_id': 'user_2_1', 'owner': 'lucy_2', 'amount': 50000.0, 'currency': 'EUR'}, | |
| {'account_id': 'user_3_1', 'owner': 'lucky_3', 'amount': 5.0, 'currency': 'HKD'}, | |
| {'account_id': 'user_4_1', 'owner': 'magic_4', 'amount': 50.0}, | |
| {'account_id': 'user_5_1', 'owner': 'list_5', 'amount': 500.0}, | |
| {'account_id': 'user_6_1', 'owner': 'mad_6', 'amount': 55.0}, | |
| ] | |
| } | |
| # Create the Config | |
| lazydbconfig = LazyDBConfig(dbschema=schema_config, seeddata=seed_data, userconfigs=user_schema_config, autosave=True) | |
| # Initialize the DB | |
| lazydb = LazyDB(lazydbcache, lazydbconfig) | |
| def get_user_by_token(auth_token) -> lazydb.user_schema: | |
| user = lazydb._db['user'].get(uid=int(auth_token)) | |
| logger.info(f'Got User: {user.dict()}') | |
| return user | |
| def get_account_by_id(account_id) -> lazydb.account_schema: | |
| return lazydb.account_get(props={'account_id': account_id}) | |
| # dependencies | |
| # this will become the header-parameter of lazyrpc method that uses this dependency | |
| # In prod, this would be a token that is autogenerated for the user, but here we can just | |
| # use the user-id which is sequential, 0 -> n | |
| def get_auth_user(auth_token: str = Header(None, alias='user-id-or-token')) -> lazydb.user_schema: | |
| if not auth_token: | |
| raise AuthError | |
| try: | |
| return get_user_by_token(auth_token) | |
| except KeyError: | |
| raise AuthError | |
| # this will become the parameter of the lazyrpc method that uses this dependency | |
| def get_account(account_id: str = Body(..., example='user_1_1'), user: lazydb.user_schema = Depends(get_auth_user)) -> lazydb.account_schema: | |
| try: | |
| account = get_account_by_id(account_id) | |
| except KeyError: | |
| raise AccountNotFound | |
| if not account or account.owner != user.username: | |
| raise AccountNotFound | |
| return account | |
| # LazyRPC middlewares | |
| async def logging_middleware(ctx: JsonRpcContext): | |
| logger.info('Request: %r', ctx.raw_request) | |
| try: | |
| yield | |
| finally: | |
| logger.info('Response: %r', ctx.raw_response) | |
| # LazyRPC entrypoint | |
| common_errors = [AccountNotFound, AuthError] | |
| common_errors.extend(Entrypoint.default_errors) | |
| # Swagger shows for entrypoint common parameters gathered by dependencies and common_dependencies: | |
| # - json-rpc-parameter 'account_id' | |
| # - header parameter 'user-id-or-token' | |
| api_v1 = Entrypoint( | |
| '/api/v1/lazyrpc', | |
| errors=common_errors, | |
| middlewares=[logging_middleware], | |
| # this dependencies called once for whole json-rpc batch request | |
| dependencies=[Depends(get_auth_user)], | |
| # this dependencies called separately for every json-rpc request in batch request | |
| common_dependencies=[Depends(get_account)], | |
| ) | |
| # LazyRPC methods of this entrypoint | |
| # Can be wrapped up in a class | |
| class TestRPCDBAPI: | |
| # this json-rpc method has one json-rpc-parameter 'account_id' and one header parameter 'user-id-or-token' | |
| def get_balance(account: lazydb.account_schema = Depends(get_account)) -> Balance: | |
| return Balance(amount=account.amount, currency=account.currency,) | |
| # this json-rpc method has two json-rpc-parameters 'account_id', 'amount' and one header parameter 'user-id-or-token' | |
| def withdraw(account: lazydb.account_schema = Depends(get_account), amount: int = Body(..., gt=0, example=10)) -> Balance: | |
| if account.amount - amount < 0: | |
| raise NotEnoughMoney(data={'balance': TestRPCDBAPI.get_balance(account)}) | |
| account.amount -= amount | |
| return TestRPCDBAPI.get_balance(account) | |
| def get_user(account: lazydb.account_schema = Depends(get_account), user_id: int = Body(...)) -> lazydb.user_schema: | |
| logger.info(user_id) | |
| return lazydb.user_get(uid=user_id) | |
| # LazyRPC API Init | |
| app = LazyJRPC() | |
| app.bind_entrypoint(api_v1) | |
| async def shutdown_event(): | |
| logger.info('Shutting Down. Saving DB Cache State') | |
| lazydb.save_db() | |
| # We'll use this to test the API in lazyapi_rpc_bench.py | |
| async def get_user(user_id: int) -> lazydb.user_schema: | |
| return lazydb.user_get(uid=user_id) | |
| if __name__ == '__main__': | |
| import uvicorn | |
| logger.info('You can run lazyapi_rpc_bench.py now') | |
| uvicorn.run(app, port=5000, debug=True, access_log=False) | |
Xet Storage Details
- Size:
- 6.39 kB
- Xet hash:
- 66f096a541567913ee9aa0c074b14d0adfffe6829a62e5a103fe225a360e0133
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.