aidbox-python-sdk


Nameaidbox-python-sdk JSON
Version 0.1.13 PyPI version JSON
download
home_pageNone
SummaryAidbox SDK for python
upload_time2024-11-01 23:24:50
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT License Copyright (c) 2019 Ilya Beda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords fhir
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![build status](https://github.com/Aidbox/aidbox-python-sdk/actions/workflows/build.yaml/badge.svg)](https://github.com/Aidbox/aidbox-python-sdk/actions/workflows/build.yaml)
[![pypi](https://img.shields.io/pypi/v/aidbox-python-sdk.svg)](https://pypi.org/project/aidbox-python-sdk/)
[![Supported Python version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/release/python-390/)

# aidbox-python-sdk

1. Create a python 3.9+ environment `pyenv `
2. Set env variables and activate virtual environment `source activate_settings.sh`
2. Install the required packages with `pipenv install --dev`
3. Make sure the app's settings are configured correctly (see `activate_settings.sh` and `aidbox_python_sdk/settings.py`). You can also
 use environment variables to define sensitive settings, eg. DB connection variables (see example `.env-ptl`)
4. You can then run example with `python example.py`.

# Getting started

## Minimal application

main.py
```python
from aidbox_python_sdk.main import create_app as _create_app
from aidbox_python_sdk.settings import Settings
from aidbox_python_sdk.sdk import SDK


settings = Settings(**{})
sdk = SDK(settings, resources={}, seeds={})


def create_app():
    app = await _create_app(SDK)
    return app


async def create_gunicorn_app() -> web.Application:
    return create_app()
```

## Register handler for operation
```python
import logging
from aiohttp import web
from aidbox_python_sdk.types import SDKOperation, SDKOperationRequest

from yourappfolder import sdk 


@sdk.operation(
    methods=["POST", "PATCH"],
    path=["signup", "register", {"name": "date"}, {"name": "test"}],
    timeout=60000  ## Optional parameter to set a custom timeout for operation in milliseconds
)
def signup_register_op(_operation: SDKOperation, request: SDKOperationRequest):
    """
    POST /signup/register/21.02.19/testvalue
    PATCH /signup/register/22.02.19/patchtestvalue
    """
    logging.debug("`signup_register_op` operation handler")
    logging.debug("Operation data: %s", operation)
    logging.debug("Request: %s", request)
    return web.json_response({"success": "Ok", "request": request["route-params"]})

```

## Usage of AppKeys

To access Aidbox Client, SDK, settings, DB Proxy the `app` (`web.Application`) is extended by default with the following app keys that are defined in `aidbox_python_sdk.app_keys` module:

```python
from aidbox_python_sdk import app_keys as ak
from aidbox_python_sdk.types import SDKOperation, SDKOperationRequest

@sdk.operation(["POST"], ["example"])
async def update_organization_op(_operation: SDKOperation, request: SDKOperationRequest):
    app = request.app
    client = app[ak.client] # AsyncAidboxClient
    sdk = app[ak.sdk] # SDK
    settings = app[ak.settings] # Settings
    db = app[ak.db] # DBProxy
    return web.json_response()
```

## Usage of FHIR Client

FHIR Client is not plugged in by default, however, to use it you can extend the app by adding new AppKey

app/app_keys.py
```python
from fhirpy import AsyncFHIRClient

fhir_client: web.AppKey[AsyncFHIRClient] = web.AppKey("fhir_client", AsyncFHIRClient)
```

main.py
```python
from collections.abc import AsyncGenerator

from aidbox_python_sdk.main import create_app as _create_app
from aidbox_python_sdk.settings import Settings
from aidbox_python_sdk.sdk import SDK
from aiohttp import BasicAuth, web
from fhirpy import AsyncFHIRClient

from app import app_keys as ak

settings = Settings(**{})
sdk = SDK(settings, resources={}, seeds={)

def create_app():
    app = await _create_app(SDK)
    app.cleanup_ctx.append(fhir_clients_ctx)
    return app


async def create_gunicorn_app() -> web.Application:
    return create_app()


async def fhir_clients_ctx(app: web.Application) -> AsyncGenerator[None, None]:
    app[ak.fhir_client] = await init_fhir_client(app[ak.settings], "/fhir")

    yield


async def init_fhir_client(settings: Settings, prefix: str = "") -> AsyncFHIRClient:
    basic_auth = BasicAuth(
        login=settings.APP_INIT_CLIENT_ID,
        password=settings.APP_INIT_CLIENT_SECRET,
    )

    return AsyncFHIRClient(
        f"{settings.APP_INIT_URL}{prefix}",
        authorization=basic_auth.encode(),
        dump_resource=lambda x: x.model_dump(),
    )
```

After that, you can use `app[ak.fhir_client]` that has the type `AsyncFHIRClient` everywhere where the app is available.


## Usage of request_schema
```python
from aidbox_python_sdk.types import SDKOperation, SDKOperationRequest

schema = {
    "required": ["params", "resource"],
    "properties": {
        "params": {
            "type": "object",
            "required": ["abc", "location"],
            "properties": {"abc": {"type": "string"}, "location": {"type": "string"}},
            "additionalProperties": False,
        },
        "resource": {
            "type": "object",
            "required": ["organizationType", "employeesCount"],
            "properties": {
                "organizationType": {"type": "string", "enum": ["profit", "non-profit"]},
                "employeesCount": {"type": "number"},
            },
            "additionalProperties": False,
        },
    },
}


@sdk.operation(["POST"], ["Organization", {"name": "id"}, "$update"], request_schema=schema)
async def update_organization_op(_operation: SDKOperation, request: SDKOperationRequest):
    location = request["params"]["location"]
    return web.json_response({"location": location})
```

### Valid request example
```shell
POST /Organization/org-1/$update?abc=xyz&location=us

organizationType: non-profit
employeesCount: 10
```



            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "aidbox-python-sdk",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "fhir",
    "author": null,
    "author_email": "\"beda.software\" <aidbox-python-sdk@beda.software>",
    "download_url": "https://files.pythonhosted.org/packages/90/94/65d56e4af66096315d0d5d71eaea41c109b7d9f1944e6a697aca20b6a4e2/aidbox_python_sdk-0.1.13.tar.gz",
    "platform": null,
    "description": "[![build status](https://github.com/Aidbox/aidbox-python-sdk/actions/workflows/build.yaml/badge.svg)](https://github.com/Aidbox/aidbox-python-sdk/actions/workflows/build.yaml)\n[![pypi](https://img.shields.io/pypi/v/aidbox-python-sdk.svg)](https://pypi.org/project/aidbox-python-sdk/)\n[![Supported Python version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/release/python-390/)\n\n# aidbox-python-sdk\n\n1. Create a python 3.9+ environment `pyenv `\n2. Set env variables and activate virtual environment `source activate_settings.sh`\n2. Install the required packages with `pipenv install --dev`\n3. Make sure the app's settings are configured correctly (see `activate_settings.sh` and `aidbox_python_sdk/settings.py`). You can also\n use environment variables to define sensitive settings, eg. DB connection variables (see example `.env-ptl`)\n4. You can then run example with `python example.py`.\n\n# Getting started\n\n## Minimal application\n\nmain.py\n```python\nfrom aidbox_python_sdk.main import create_app as _create_app\nfrom aidbox_python_sdk.settings import Settings\nfrom aidbox_python_sdk.sdk import SDK\n\n\nsettings = Settings(**{})\nsdk = SDK(settings, resources={}, seeds={})\n\n\ndef create_app():\n    app = await _create_app(SDK)\n    return app\n\n\nasync def create_gunicorn_app() -> web.Application:\n    return create_app()\n```\n\n## Register handler for operation\n```python\nimport logging\nfrom aiohttp import web\nfrom aidbox_python_sdk.types import SDKOperation, SDKOperationRequest\n\nfrom yourappfolder import sdk \n\n\n@sdk.operation(\n    methods=[\"POST\", \"PATCH\"],\n    path=[\"signup\", \"register\", {\"name\": \"date\"}, {\"name\": \"test\"}],\n    timeout=60000  ## Optional parameter to set a custom timeout for operation in milliseconds\n)\ndef signup_register_op(_operation: SDKOperation, request: SDKOperationRequest):\n    \"\"\"\n    POST /signup/register/21.02.19/testvalue\n    PATCH /signup/register/22.02.19/patchtestvalue\n    \"\"\"\n    logging.debug(\"`signup_register_op` operation handler\")\n    logging.debug(\"Operation data: %s\", operation)\n    logging.debug(\"Request: %s\", request)\n    return web.json_response({\"success\": \"Ok\", \"request\": request[\"route-params\"]})\n\n```\n\n## Usage of AppKeys\n\nTo access Aidbox Client, SDK, settings, DB Proxy the `app` (`web.Application`) is extended by default with the following app keys that are defined in `aidbox_python_sdk.app_keys` module:\n\n```python\nfrom aidbox_python_sdk import app_keys as ak\nfrom aidbox_python_sdk.types import SDKOperation, SDKOperationRequest\n\n@sdk.operation([\"POST\"], [\"example\"])\nasync def update_organization_op(_operation: SDKOperation, request: SDKOperationRequest):\n    app = request.app\n    client = app[ak.client] # AsyncAidboxClient\n    sdk = app[ak.sdk] # SDK\n    settings = app[ak.settings] # Settings\n    db = app[ak.db] # DBProxy\n    return web.json_response()\n```\n\n## Usage of FHIR Client\n\nFHIR Client is not plugged in by default, however, to use it you can extend the app by adding new AppKey\n\napp/app_keys.py\n```python\nfrom fhirpy import AsyncFHIRClient\n\nfhir_client: web.AppKey[AsyncFHIRClient] = web.AppKey(\"fhir_client\", AsyncFHIRClient)\n```\n\nmain.py\n```python\nfrom collections.abc import AsyncGenerator\n\nfrom aidbox_python_sdk.main import create_app as _create_app\nfrom aidbox_python_sdk.settings import Settings\nfrom aidbox_python_sdk.sdk import SDK\nfrom aiohttp import BasicAuth, web\nfrom fhirpy import AsyncFHIRClient\n\nfrom app import app_keys as ak\n\nsettings = Settings(**{})\nsdk = SDK(settings, resources={}, seeds={)\n\ndef create_app():\n    app = await _create_app(SDK)\n    app.cleanup_ctx.append(fhir_clients_ctx)\n    return app\n\n\nasync def create_gunicorn_app() -> web.Application:\n    return create_app()\n\n\nasync def fhir_clients_ctx(app: web.Application) -> AsyncGenerator[None, None]:\n    app[ak.fhir_client] = await init_fhir_client(app[ak.settings], \"/fhir\")\n\n    yield\n\n\nasync def init_fhir_client(settings: Settings, prefix: str = \"\") -> AsyncFHIRClient:\n    basic_auth = BasicAuth(\n        login=settings.APP_INIT_CLIENT_ID,\n        password=settings.APP_INIT_CLIENT_SECRET,\n    )\n\n    return AsyncFHIRClient(\n        f\"{settings.APP_INIT_URL}{prefix}\",\n        authorization=basic_auth.encode(),\n        dump_resource=lambda x: x.model_dump(),\n    )\n```\n\nAfter that, you can use `app[ak.fhir_client]` that has the type `AsyncFHIRClient` everywhere where the app is available.\n\n\n## Usage of request_schema\n```python\nfrom aidbox_python_sdk.types import SDKOperation, SDKOperationRequest\n\nschema = {\n    \"required\": [\"params\", \"resource\"],\n    \"properties\": {\n        \"params\": {\n            \"type\": \"object\",\n            \"required\": [\"abc\", \"location\"],\n            \"properties\": {\"abc\": {\"type\": \"string\"}, \"location\": {\"type\": \"string\"}},\n            \"additionalProperties\": False,\n        },\n        \"resource\": {\n            \"type\": \"object\",\n            \"required\": [\"organizationType\", \"employeesCount\"],\n            \"properties\": {\n                \"organizationType\": {\"type\": \"string\", \"enum\": [\"profit\", \"non-profit\"]},\n                \"employeesCount\": {\"type\": \"number\"},\n            },\n            \"additionalProperties\": False,\n        },\n    },\n}\n\n\n@sdk.operation([\"POST\"], [\"Organization\", {\"name\": \"id\"}, \"$update\"], request_schema=schema)\nasync def update_organization_op(_operation: SDKOperation, request: SDKOperationRequest):\n    location = request[\"params\"][\"location\"]\n    return web.json_response({\"location\": location})\n```\n\n### Valid request example\n```shell\nPOST /Organization/org-1/$update?abc=xyz&location=us\n\norganizationType: non-profit\nemployeesCount: 10\n```\n\n\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2019 Ilya Beda  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "Aidbox SDK for python",
    "version": "0.1.13",
    "project_urls": {
        "documentation": "https://github.com/Aidbox/aidbox-python-sdk#readme",
        "homepage": "https://github.com/Aidbox/aidbox-python-sdk",
        "repository": "https://github.com/Aidbox/aidbox-python-sdk.git"
    },
    "split_keywords": [
        "fhir"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fe1686c331f65fd436f1248ddc8af9ea45166fee38b21c46f7c343606d75db94",
                "md5": "39b68ca3d19867ad0e061e1d7f062067",
                "sha256": "9429ead6dd52fcb89a20fea823bc12d52bb359c96282b8631c2bad8ac5cc6528"
            },
            "downloads": -1,
            "filename": "aidbox_python_sdk-0.1.13-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "39b68ca3d19867ad0e061e1d7f062067",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 17530,
            "upload_time": "2024-11-01T23:24:49",
            "upload_time_iso_8601": "2024-11-01T23:24:49.057697Z",
            "url": "https://files.pythonhosted.org/packages/fe/16/86c331f65fd436f1248ddc8af9ea45166fee38b21c46f7c343606d75db94/aidbox_python_sdk-0.1.13-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "909465d56e4af66096315d0d5d71eaea41c109b7d9f1944e6a697aca20b6a4e2",
                "md5": "865feafda267022c4182fa0a360e1136",
                "sha256": "3219a8f582c2be83b06fa8dd867731c23b41f3250e3024bb96148cbdae365d19"
            },
            "downloads": -1,
            "filename": "aidbox_python_sdk-0.1.13.tar.gz",
            "has_sig": false,
            "md5_digest": "865feafda267022c4182fa0a360e1136",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 17635,
            "upload_time": "2024-11-01T23:24:50",
            "upload_time_iso_8601": "2024-11-01T23:24:50.422826Z",
            "url": "https://files.pythonhosted.org/packages/90/94/65d56e4af66096315d0d5d71eaea41c109b7d9f1944e6a697aca20b6a4e2/aidbox_python_sdk-0.1.13.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-01 23:24:50",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Aidbox",
    "github_project": "aidbox-python-sdk#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aidbox-python-sdk"
}
        
Elapsed time: 8.87022s