Initial commit
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
from slowapi import Limiter, _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
from starlette.requests import Request
|
||||
|
||||
from config import conf
|
||||
from core.app import app
|
||||
|
||||
|
||||
def get_unique_identification(request: Request) -> str:
|
||||
return request.client.host or "127.0.0.1"
|
||||
|
||||
|
||||
limiter = Limiter(key_func=get_unique_identification, storage_uri=conf.database.get('limiter_redis').url)
|
||||
app.state.limiter = limiter
|
||||
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
||||
@@ -0,0 +1,14 @@
|
||||
import motor.motor_asyncio
|
||||
from pymongo.collection import Collection
|
||||
|
||||
from core.utils.mongo import get_mongo_url, get_mongo_db
|
||||
|
||||
|
||||
def use_client(connection_name: str = None):
|
||||
return motor.motor_asyncio.AsyncIOMotorClient(get_mongo_url(connection_name))
|
||||
|
||||
|
||||
def use_collection(collection: str, db: str = None, connection_name: str = None) -> Collection:
|
||||
if not db:
|
||||
db = get_mongo_db(connection_name)
|
||||
return use_client(connection_name)[db][collection]
|
||||
@@ -0,0 +1,34 @@
|
||||
import json
|
||||
|
||||
import aioredis
|
||||
from aioredis import Redis
|
||||
from aioredis.client import ExpiryT
|
||||
|
||||
from core.config import DatabaseConfig
|
||||
|
||||
|
||||
def redis_db(db: DatabaseConfig) -> Redis:
|
||||
# Redis client bound to pool of connections (auto-reconnecting).
|
||||
redis = aioredis.from_url(
|
||||
db.url,
|
||||
encoding="utf-8",
|
||||
decode_responses=True,
|
||||
db=int(db.db) or 0
|
||||
)
|
||||
return redis
|
||||
|
||||
|
||||
async def redis_set(key: str, value: any, db: DatabaseConfig, ex=ExpiryT):
|
||||
redis_c = redis_db(db)
|
||||
await redis_c.set(key, json.dumps(value), ex=ex)
|
||||
await redis_c.close()
|
||||
return True
|
||||
|
||||
|
||||
async def redis_get(key: str, db: DatabaseConfig):
|
||||
redis_c = redis_db(db)
|
||||
_return = await redis_c.get(key)
|
||||
await redis_c.close()
|
||||
if not _return or isinstance(_return, (int, float, complex)):
|
||||
return _return
|
||||
return json.loads(_return)
|
||||
Reference in New Issue
Block a user