Skip to content

Commit

Permalink
Merge pull request #19 from madkote/dev_annotated
Browse files Browse the repository at this point in the history
Annotated support
  • Loading branch information
madkote authored Mar 24, 2023
2 parents 0ac5d9b + 25ef520 commit a331354
Show file tree
Hide file tree
Showing 13 changed files with 76 additions and 44 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# Changes
## 0.12.0 (2023-03-24)
- `[feature]` `Annotated` support
## 0.11.0 (2022-09-19)
- `[feature]` `redis-py` replaces `aioredis`
## 0.10.0 (2022-07-07)
Expand Down
20 changes: 9 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ import fastapi
import fastapi_plugins

from fastapi_plugins.memcached import MemcachedSettings
from fastapi_plugins.memcached import MemcachedClient
from fastapi_plugins.memcached import depends_memcached
from fastapi_plugins.memcached import memcached_plugin
from fastapi_plugins.memcached import memcached_plugin, TMemcachedPlugin

import asyncio
import aiojobs
Expand Down Expand Up @@ -134,9 +132,9 @@ app = fastapi_plugins.register_middleware(fastapi.FastAPI(lifespan=lifespan))

@app.get("/")
async def root_get(
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis),
conf: pydantic.BaseSettings=fastapi.Depends(fastapi_plugins.depends_config), # noqa E501
logger: logging.Logger=fastapi.Depends(fastapi_plugins.depends_logging)
cache: fastapi_plugins.TRedisPlugin,
conf: fastapi_plugins.TConfigPlugin,
logger: fastapi_plugins.TLoggerPlugin
) -> typing.Dict:
ping = await cache.ping()
logger.debug('root_get', extra=dict(ping=ping, api_name=conf.api_name))
Expand All @@ -146,9 +144,9 @@ async def root_get(
@app.post("/jobs/schedule/<timeout>")
async def job_post(
timeout: int=fastapi.Query(..., title='the job sleep time'),
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis),
scheduler: aiojobs.Scheduler=fastapi.Depends(fastapi_plugins.depends_scheduler), # noqa E501
logger: logging.Logger=fastapi.Depends(fastapi_plugins.depends_logging)
cache: fastapi_plugins.TRedisPlugin,
scheduler: fastapi_plugins.TSchedulerPlugin,
logger: fastapi_plugins.TLoggerPlugin
) -> str:
async def coro(job_id, timeout, cache):
await cache.set(job_id, 'processing')
Expand Down Expand Up @@ -179,7 +177,7 @@ async def job_post(
@app.get("/jobs/status/<job_id>")
async def job_get(
job_id: str=fastapi.Query(..., title='the job id'),
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis),
cache: fastapi_plugins.TRedisPlugin,
) -> typing.Dict:
status = await cache.get(job_id)
if status is None:
Expand All @@ -193,7 +191,7 @@ async def job_get(
@app.post("/memcached/demo/<key>")
async def memcached_demo_post(
key: str=fastapi.Query(..., title='the job id'),
cache: MemcachedClient=fastapi.Depends(depends_memcached),
cache: fastapi_plugins.TMemcachedPlugin,
) -> typing.Dict:
await cache.set(key.encode(), str(key + '_value').encode())
value = await cache.get(key.encode())
Expand Down
2 changes: 1 addition & 1 deletion fastapi_plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

__author__ = 'madkote <madkote(at)bluewin.ch>'
__version__ = '.'.join(str(x) for x in VERSION)
__copyright__ = 'Copyright 20213, madkote'
__copyright__ = 'Copyright 2023, madkote'

# TODO: provide a generic cache type (redis, memcached, in-memory)
# and share some settings. Module/Sub-Pack cache
Expand Down
6 changes: 5 additions & 1 deletion fastapi_plugins/_redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@
from .plugin import Plugin

from .control import ControlHealthMixin
from .utils import Annotated

__all__ = [
'RedisError', 'RedisType', 'RedisSettings', 'RedisPlugin',
'redis_plugin', 'depends_redis'
'redis_plugin', 'depends_redis', 'TRedisPlugin'
]


Expand Down Expand Up @@ -218,3 +219,6 @@ async def depends_redis(
conn: starlette.requests.HTTPConnection
) -> aioredis.Redis:
return await conn.app.state.REDIS()


TRedisPlugin = Annotated[typing.Any, fastapi.Depends(depends_redis)]
6 changes: 5 additions & 1 deletion fastapi_plugins/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@
from .plugin import PluginError
from .plugin import PluginSettings
from .plugin import Plugin
from .utils import Annotated

__all__ = [
'ControlEnviron', 'ControlHealthCheck', 'ControlHealth',
'ControlHealthError', 'ControlHeartBeat', 'ControlVersion',
#
'ControlError', 'ControlHealthMixin', 'ControlSettings', 'Controller',
'ControlPlugin', 'control_plugin', 'depends_control'
'ControlPlugin', 'control_plugin', 'depends_control', 'TControlPlugin'
]


Expand Down Expand Up @@ -361,3 +362,6 @@ async def depends_control(
conn: starlette.requests.HTTPConnection
) -> Controller:
return await conn.app.state.PLUGIN_CONTROL()


TControlPlugin = Annotated[Controller, fastapi.Depends(depends_control)]
7 changes: 6 additions & 1 deletion fastapi_plugins/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@
from .plugin import Plugin

from .control import ControlHealthMixin
from .utils import Annotated

__all__ = [
'LoggingError', 'LoggingStyle', 'LoggingHandlerType', 'LoggingSettings',
'LoggingPlugin', 'log_plugin', 'log_adapter', 'depends_logging'
'LoggingPlugin', 'log_plugin', 'log_adapter', 'depends_logging',
'TLoggerPlugin'
]


Expand Down Expand Up @@ -241,3 +243,6 @@ async def depends_logging(
conn: starlette.requests.HTTPConnection
) -> logging.Logger:
return await conn.app.state.PLUGIN_LOGGER()


TLoggerPlugin = Annotated[logging.Logger, fastapi.Depends(depends_logging)]
8 changes: 6 additions & 2 deletions fastapi_plugins/memcached.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@
from .plugin import Plugin

from .control import ControlHealthMixin

from .utils import Annotated

__all__ = [
'MemcachedError', 'MemcachedSettings', 'MemcachedClient',
'MemcachedPlugin', 'memcached_plugin', 'depends_memcached'
'MemcachedPlugin', 'memcached_plugin', 'depends_memcached',
'TMemcachedPlugin'
]


Expand Down Expand Up @@ -122,3 +123,6 @@ async def depends_memcached(
conn: starlette.requests.HTTPConnection
) -> MemcachedClient:
return await conn.app.state.MEMCACHED()


TMemcachedPlugin = Annotated[MemcachedClient, fastapi.Depends(depends_memcached)] # noqa E501
7 changes: 5 additions & 2 deletions fastapi_plugins/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
from .plugin import Plugin

from .control import ControlHealthMixin

from .utils import Annotated
from .version import VERSION

__all__ = [
'SchedulerError', 'SchedulerSettings', 'SchedulerPlugin',
'scheduler_plugin', 'depends_scheduler'
'scheduler_plugin', 'depends_scheduler', 'TSchedulerPlugin'
# 'MadnessScheduler'
]
__author__ = 'madkote <madkote(at)bluewin.ch>'
Expand Down Expand Up @@ -140,3 +140,6 @@ async def depends_scheduler(
conn: starlette.requests.HTTPConnection
) -> aiojobs.Scheduler:
return await conn.app.state.AIOJOBS_SCHEDULER()


TSchedulerPlugin = Annotated[aiojobs.Scheduler, fastapi.Depends(depends_scheduler)] # noqa E501
5 changes: 5 additions & 0 deletions fastapi_plugins/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@

from .plugin import PluginError
from .plugin import Plugin
from .utils import Annotated
from .version import VERSION

__all__ = [
'ConfigError', 'ConfigPlugin', 'depends_config', 'config_plugin',
'TConfigPlugin',
#
'register_config',
'register_config_docker', 'register_config_local', 'register_config_test',
Expand Down Expand Up @@ -180,3 +182,6 @@ async def depends_config(
conn: starlette.requests.HTTPConnection
) -> pydantic.BaseSettings:
return await conn.app.state.PLUGIN_CONFIG()


TConfigPlugin = Annotated[pydantic.BaseSettings, fastapi.Depends(depends_config)] # noqa E501
12 changes: 12 additions & 0 deletions fastapi_plugins/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# fastapi_plugins.utils

from __future__ import absolute_import

import sys

if sys.version_info >= (3, 9):
from typing import Annotated # noqa
else:
from typing_extensions import Annotated # noqa
2 changes: 1 addition & 1 deletion fastapi_plugins/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
# -*- coding: utf-8 -*-
# fastapi_plugins.version

VERSION = (0, 11, 0)
VERSION = (0, 12, 0)

__version__ = '.'.join(str(x) for x in VERSION)
31 changes: 14 additions & 17 deletions scripts/demo_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
import typing
import uuid

import aiojobs
import aioredis
import fastapi
import pydantic
import starlette.status
Expand All @@ -31,10 +29,9 @@
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # noqa E501
import fastapi_plugins

from fastapi_plugins.memcached import MemcachedSettings
from fastapi_plugins.memcached import MemcachedClient
from fastapi_plugins.memcached import depends_memcached
from fastapi_plugins.memcached import memcached_plugin
from fastapi_plugins.memcached import (
MemcachedSettings, memcached_plugin, TMemcachedPlugin
)


class OtherSettings(pydantic.BaseSettings):
Expand Down Expand Up @@ -102,9 +99,9 @@ async def lifespan(app: fastapi.FastAPI):

@app.get("/")
async def root_get(
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis),
conf: pydantic.BaseSettings=fastapi.Depends(fastapi_plugins.depends_config), # noqa E501
logger: logging.Logger=fastapi.Depends(fastapi_plugins.depends_logging)
cache: fastapi_plugins.TRedisPlugin,
conf: fastapi_plugins.TConfigPlugin,
logger: fastapi_plugins.TLoggerPlugin
) -> typing.Dict:
ping = await cache.ping()
logger.debug('root_get', extra=dict(ping=ping, api_name=conf.api_name))
Expand All @@ -113,10 +110,10 @@ async def root_get(

@app.post("/jobs/schedule/<timeout>")
async def job_post(
timeout: int=fastapi.Query(..., title='the job sleep time'),
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis),
scheduler: aiojobs.Scheduler=fastapi.Depends(fastapi_plugins.depends_scheduler), # noqa E501
logger: logging.Logger=fastapi.Depends(fastapi_plugins.depends_logging)
cache: fastapi_plugins.TRedisPlugin,
scheduler: fastapi_plugins.TSchedulerPlugin,
logger: fastapi_plugins.TLoggerPlugin,
timeout: int=fastapi.Query(..., title='the job sleep time')
) -> str:
async def coro(job_id, timeout, cache):
await cache.set(job_id, 'processing')
Expand Down Expand Up @@ -146,8 +143,8 @@ async def coro(job_id, timeout, cache):

@app.get("/jobs/status/<job_id>")
async def job_get(
job_id: str=fastapi.Query(..., title='the job id'),
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis),
cache: fastapi_plugins.TRedisPlugin,
job_id: str=fastapi.Query(..., title='the job id')
) -> typing.Dict:
status = await cache.get(job_id)
if status is None:
Expand All @@ -160,8 +157,8 @@ async def job_get(

@app.post("/memcached/demo/<key>")
async def memcached_demo_post(
key: str=fastapi.Query(..., title='the job id'),
cache: MemcachedClient=fastapi.Depends(depends_memcached),
cache: TMemcachedPlugin,
key: str=fastapi.Query(..., title='the job id')
) -> typing.Dict:
await cache.set(key.encode(), str(key + '_value').encode())
value = await cache.get(key.encode())
Expand Down
12 changes: 5 additions & 7 deletions tests/test_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import typing
import uuid

import aiojobs
import redis.asyncio as aioredis
import fastapi
import pytest
import starlette.testclient
Expand Down Expand Up @@ -46,9 +44,9 @@ async def lifespan(app: fastapi.FastAPI):

@app.post('/jobs/schedule')
async def job_post(
timeout: int=fastapi.Query(..., title='the job sleep time'),
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis), # noqa E501
scheduler: aiojobs.Scheduler=fastapi.Depends(fastapi_plugins.depends_scheduler), # noqa E501
cache: fastapi_plugins.TRedisPlugin,
scheduler: fastapi_plugins.TSchedulerPlugin,
timeout: int=fastapi.Query(..., title='the job sleep time')
) -> str:
async def coro(job_id, timeout, cache):
await cache.set(job_id, 'processing')
Expand All @@ -70,8 +68,8 @@ async def coro(job_id, timeout, cache):

@app.get('/jobs/status')
async def job_get(
job_id: str=fastapi.Query(..., title='the job id'),
cache: aioredis.Redis=fastapi.Depends(fastapi_plugins.depends_redis), # noqa E501
cache: fastapi_plugins.TRedisPlugin,
job_id: str=fastapi.Query(..., title='the job id')
) -> typing.Dict:
status = await cache.get(job_id)
if status is None:
Expand Down

0 comments on commit a331354

Please sign in to comment.