Skip to content
This repository has been archived by the owner on Mar 24, 2024. It is now read-only.

Commit

Permalink
release
Browse files Browse the repository at this point in the history
  • Loading branch information
lsbardel committed Jul 27, 2022
1 parent 53cb14a commit d1de6eb
Show file tree
Hide file tree
Showing 5 changed files with 6 additions and 202 deletions.
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,12 @@ sentry-sdk = "^1.4.3"
python-dotenv = "^0.20.0"
openapi-spec-validator = "^0.3.1"
pytest-cov = "^3.0.0"
pytest-aiohttp = "^1.0.4"
pytest-mock = "^3.6.1"
isort = "^5.10.1"
types-simplejson = "^3.17.5"
types-python-dateutil = "^2.8.11"
factory-boy = "^3.2.1"
pytest-asyncio = "^0.19.0"

[tool.poetry.extras]
dev = ["aiodns", "PyJWT", "colorlog", "phonenumbers", "cchardet"]
Expand Down
199 changes: 1 addition & 198 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,201 +10,4 @@
Asynchronous web middleware for [aiohttp][] and serving Rest APIs with [OpenAPI][] v 3
specification and with optional [PostgreSql][] database bindings.

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

**Table of Contents**

- [Installation](#installation)
- [Development](#development)
- [Features](#features)
- [Web App](#web-app)
- [OpenAPI Documentation](#openapi-documentation)
- [Database Integration](#database-integration)
- [Websockets](#websockets)
- [RPC protocol](#rpc-protocol)
- [Publish/Subscribe](#publishsubscribe)
- [Environment Variables](#environment-variables)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Installation

```
pip install aio-openapi
```

## Development

Clone the repository and create a virtual environment `venv`.

Install dependencies by running the install script

```
make install
```

To run tests

```
make test
```

By default tests are run against a database with the following connection string `postgresql+asyncpg://postgres:postgres@localhost:5432/openapi`. To use a different DB, create a `.env` file with
a different connection string, for example:

```
DATASTORE=postgresql+asyncpg://postgres:postgres@localhost:6432/openapi
```

## Features

- Asynchronous web routes with [aiohttp](https://aiohttp.readthedocs.io/en/stable/)
- Data validation, serialization and unserialization with python [dataclasses](https://docs.python.org/3/library/dataclasses.html)
- [OpenApi][] v 3 auto documentation
- [SqlAlchemy][] expression language
- Asynchronous DB interaction with [asyncpg][]
- Migrations with [alembic][]
- SqlAlchemy tables as python dataclasses
- Support [click][] command line interface
- Optional [sentry](https://sentry.io) middleware

## Web App

To create an openapi RESTful application follow this schema (lets call the file `main.py`)

```python
from openapi.rest import rest

def create_app():
return rest(
openapi=dict(
title='A REST API',
...
),
base_path='/v1',
allowed_tags=[...],
validate_docs=True,
setup_app=setup_app,
commands=[...]
)


def setup_app(app):
app.router.add_routes(...)
return app


if __name__ == '__main__':
create_app().main()
```

The `create_app` function creates the [aiohttp][] server application by invoking the `rest` function.
This function adds the [click][] command in the `cli` mapping entry and add
documentation for routes which support OpenAPI docs.
The `setup_app` function is used to actually setup the custom application, usually by adding middleware, routes,
shutdown callbacks, database integration and so forth.

## OpenAPI Documentation

The library provide tools for creating OpenAPI v 3 compliant endpoints and
auto-document them.

An example from test `tests/example` directory

```python
from typing import List

from aiohttp import web

from openapi.db.path import SqlApiPath
from openapi.spec import op


routes = web.RouteTableDef()


@routes.view('/tasks')
class TasksPath(SqlApiPath):
"""
---
summary: Create and query Tasks
tags:
- name: Task
description: Task tag description
"""
table = 'tasks'

@op(query_schema=TaskOrderableQuery, response_schema=List[Task])
async def get(self) -> web.Response:
"""
---
summary: Retrieve Tasks
description: Retrieve a list of Tasks
responses:
200:
description: Authenticated tasks
"""
paginated = await self.get_list()
return paginated.json_response()

@op(response_schema=Task, body_schema=TaskAdd)
async def post(self) -> web.Response:
"""
---
summary: Create a Task
description: Create a new Task
responses:
201:
description: the task was successfully added
422:
description: Failed validation
"""
data = await self.create_one()
return self.json_response(data, status=201)
```

## Database Integration

This library provides integration with [asyncpg][], an high performant asynchronous
connector with [PostgreSql][] database.
To add the database extension simply use the `get_db` function in the applicatiuon `setup_app` function:

```python
from aiohttp import web

from openapi.db import get_db

def setup_app(app: web.Application) -> None:
db = get_db(app)
meta = db.metadata

```

This will enable database connection and command line tools (most of them from [alembic][]):

```
python main.py db --help
```

The database container is available at the `db` app key:

```python
app['db']
```

## Environment Variables

Several environment variables are used by the library to support testing and deployment.

- `DATASTORE`: PostgreSql connection string (same as [SqlAlchemy][] syntax)
- `DBPOOL_MIN_SIZE`: minimum size of database connection pool (default is 10)
- `DBPOOL_MAX_SIZE`: maximum size of database connection pool (default is 10)

[aiohttp]: https://aiohttp.readthedocs.io/en/stable/
[openapi]: https://www.openapis.org/
[postgresql]: https://www.postgresql.org/
[sqlalchemy]: https://www.sqlalchemy.org/
[click]: https://github.com/pallets/click
[alembic]: http://alembic.zzzcomputing.com/en/latest/
[asyncpg]: https://github.com/MagicStack/asyncpg
See the [tutorial](https://aio-openapi.readthedocs.io/en/latest/tutorial.html) for a quick introduction.
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ warn_return_any=False
warn_no_return=True

[tool:pytest]
asyncio_mode = auto
testpaths = tests
filterwarnings= default
ignore:::.*raven_aiohttp.*
Expand Down
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ async def cli2(clear_db: CrudDB) -> TestClient:


@pytest.fixture
async def test_app(cli: TestClient) -> Application:
def test_app(cli: TestClient) -> Application:
return cli.app


@pytest.fixture
async def db(test_app: Application) -> CrudDB:
def db(test_app: Application) -> CrudDB:
return test_app["db"]

0 comments on commit d1de6eb

Please sign in to comment.