async def startup() -> None: logger.debug("In startup") # await database.connect() redis = await aioredis.create_redis_pool(settings.cache_url, encoding="utf-8") FastAPICache.init(RedisBackend(redis), prefix="api-cache", coder=PydanticCoder)
async def startup(): update_loggers() redis = aioredis.from_url(config.REDIS_HOST, encoding="utf8", decode_responses=True) FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache") logger.info("initialization successful")
async def startup(): """Start up FastAPI server""" settings = get_settings() app.state.graph = TccmGraph(settings) app.state.graph.connect() redis = aioredis.from_url(url=settings.redis_url, encoding="utf8", decode_responses=True) FastAPICache.init(backend=RedisBackend(redis), prefix="fastapi-cache")
def default_key_builder( func, namespace: Optional[str] = "", request: Optional[Request] = None, response: Optional[Response] = None, args: Optional[tuple] = None, kwargs: Optional[dict] = None, ): from fastapi_cache import FastAPICache prefix = FastAPICache.get_prefix() cache_key = f"{prefix}:{namespace}:{func.__module__}:{func.__name__}:{args}:{kwargs}" return cache_key
async def inner(*args, **kwargs): nonlocal coder nonlocal expire nonlocal key_builder copy_kwargs = kwargs.copy() request = copy_kwargs.pop("request", None) response = copy_kwargs.pop("response", None) if (request and request.headers.get("Cache-Control") == "no-store") or not FastAPICache.get_enable(): return await func(*args, **kwargs) coder = coder or FastAPICache.get_coder() expire = expire or FastAPICache.get_expire() key_builder = key_builder or FastAPICache.get_key_builder() backend = FastAPICache.get_backend() cache_key = key_builder(func, namespace, request=request, response=response, args=args, kwargs=copy_kwargs) ttl, ret = await backend.get_with_ttl(cache_key) if not request: if ret is not None: return coder.decode(ret) ret = await func(*args, **kwargs) await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) return ret if request.method != "GET": return await func(request, *args, **kwargs) if_none_match = request.headers.get("if-none-match") if ret is not None: if response: response.headers["Cache-Control"] = f"max-age={ttl}" etag = f"W/{hash(ret)}" if if_none_match == etag: response.status_code = 304 return response response.headers["ETag"] = etag return coder.decode(ret) ret = await func(*args, **kwargs) await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) return ret
async def startup(): FastAPICache.init(InMemoryBackend(), prefix="fastapi-cache")
async def get_metrics(organization_id: int, fields: str, db: Session = Depends(get_db)) -> Any: """ Get Trees properties metrics""" backend = FastAPICache.get_backend() coder = FastAPICache.get_coder() key = f'trees_metrics_{organization_id}_{fields}' ret = await backend.get(key) if ret is None: requested_fields = fields.split(",") ratio = crud.tree.get_properties_completion_ratio( db, organization_id, requested_fields) aggregates = crud.tree.get_properties_aggregates( db, organization_id, requested_fields) mostRepresented = [ item for item in aggregates["canonicalName"] if item["value"] != " " ][:6] for index, item in enumerate(mostRepresented): canonical_name = item["value"].replace(" x ", " ").replace("‹", "i") item["value"] = canonical_name response_eol_search = requests.get( f'https://eol.org/api/search/1.0.json?q={canonical_name}') if response_eol_search.status_code == 200 and len( response_eol_search.json()["results"]) > 0: id = response_eol_search.json()["results"][0]["id"] response_eol_pages = requests.get( f'https://eol.org/api/pages/1.0/{id}.json?details=true&images_per_page=10' ) if response_eol_pages.status_code == 200: json = response_eol_pages.json() if "dataObjects" in json["taxonConcept"] and len( json["taxonConcept"]["dataObjects"]) > 0: mostRepresented[index]["thumbnail"] = json[ "taxonConcept"]["dataObjects"][0][ "eolThumbnailURL"] else: response_wikispecies = requests.get( f'https://species.wikimedia.org/api/rest_v1/page/summary/{canonical_name.replace(" ", "_")}' ) if response_wikispecies.status_code == 200 and "thumbnail" in response_wikispecies.json( ): mostRepresented[index][ "thumbnail"] = response_wikispecies.json( )["thumbnail"]["source"] canonicalNameTotalCount = sum(item["total"] for item in aggregates["canonicalName"]) metrics = schemas.tree.Metrics( canonicalNameTotalCount=canonicalNameTotalCount, mostRepresented=mostRepresented, ratio=ratio, aggregates=aggregates, ) await backend.set(key, coder.encode(metrics), 60000000) return metrics return coder.decode(ret)
async def startup(): redis = await aioredis.create_redis_pool(os.getenv("REDIS_URL", "redis://localhost"), encoding="utf8") FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
async def shutdown(): print('close') await database.disconnect() FastAPICache.get_backend().close() await FastAPICache.get_backend().wait_closed()
async def startup(): await database.connect() redis = await aioredis.create_redis_pool( "redis://*****:*****@127.0.0.1:63790/2", encoding="utf8") FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
def init(config): backend = InMemoryBackend() FastAPICache.init(backend, expire=config.CACHE_DEFAULT_TIMEOUT) return FastAPICache
async def startup(): backend = InMemoryBackend() FastAPICache.init(backend, prefix="in-memory-cache")
async def startup(): redis = aioredis.from_url(url="redis://localhost") FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
async def handle_startup(): """Setup redis cache and client session for weather API requests""" redis = await aioredis.create_redis_pool(settings.REDIS_URL, encoding="utf8") FastAPICache.init(RedisBackend(redis), prefix="weather-app-cache") app.client_session = aiohttp.ClientSession()