Skip to content

Commit

Permalink
Example for aiohttp server cleaned up + README.md added
Browse files Browse the repository at this point in the history
  • Loading branch information
rudyryk committed May 5, 2024
1 parent dbf3163 commit 430a3cf
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 66 deletions.
6 changes: 3 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ version: '3.3'

services:
postgres:
image: postgres:16.2-alpine3.19
image: postgres
ports:
- '5432:5432'
- ${POSTGRES_PORT:-5432}:5432
command: postgres -c log_statement=all
environment:
- POSTGRES_PASSWORD=postgres
Expand All @@ -14,7 +14,7 @@ services:
mysql:
image: mysql
ports:
- '3306:3306'
- ${MYSQL_PORT:-3306}:3306
environment:
- MYSQL_ROOT_PASSWORD=mysql
- MYSQL_DATABASE=mysql
18 changes: 0 additions & 18 deletions examples/Dockerfile

This file was deleted.

54 changes: 54 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
Examples for peewee-async
=========================

To run the examples install dependencies first:

```bash
pip install -r examples/requirements.txt
```

Also please run database service and provide credentials in environment variables.
Feel free to use development database services with the default credentials, e.g:

```bash
docker compose up postgres
```

## Example for `aiohttp` server

The example `aiohttp_example.py` is using older interface with `Manager` class. The `Manager`
will be deprecated in v1.0 but we aim to support it until that milestone.

Define database connection settings if needed, environment variables used:

- `POSTGRES_DB`
- `POSTGRES_USER`
- `POSTGRES_PASSWORD`
- `POSTGRES_HOST`
- `POSTGRES_PORT`

Run this command to create example tables in the database:

```bash
python -m examples.aiohttp_example
```

Run this command to start an example application:

```bash
gunicorn --bind 127.0.0.1:8080 --log-level INFO --access-logfile - \
--worker-class aiohttp.GunicornWebWorker --reload \
examples.aiohttp_example:app
```

Application should be up and running:

```bash
curl 'http://127.0.0.1:8080/?p=1'
```

the output should be:

```
This is a first post
```
36 changes: 18 additions & 18 deletions examples/aiohttp_example.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import json
import logging
import os
# from asyncio import sleep as async_sleep
from secrets import token_hex
from datetime import datetime
from aiohttp import web
Expand All @@ -11,9 +10,13 @@
logger = logging.getLogger(__name__)

database = PooledPostgresqlDatabase(
'examples', user='postgres', password='postgres',
host='db-postgres', port=5432,
min_connections=10, max_connections=100,
os.environ.get('POSTGRES_DB', 'postgres'),
user=os.environ.get('POSTGRES_USER', 'postgres'),
password=os.environ.get('POSTGRES_PASSWORD', 'postgres'),
host=os.environ.get('POSTGRES_HOST', '127.0.0.1'),
port=int(os.environ.get('POSTGRES_PORT', 5432)),
min_connections=2,
max_connections=10,
)

objects = Manager(database)
Expand All @@ -36,11 +39,6 @@ def __str__(self):
return self.title


def create_tables():
with database:
database.create_tables([Post], safe=True)


def add_post(title, text):
with database.atomic():
Post.create(title=title, text=text)
Expand Down Expand Up @@ -87,18 +85,20 @@ async def update_post_endpoint(request):
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)

# Initialize database
create_tables()
print("Initialize tables and add some random posts...")

try:
with database:
database.create_tables([Post], safe=True)
print("Tables are created.")
except Exception as exc:
print("Error creating tables: {}".format(exc))

# Add some random posts
try:
add_post("Hello, world", "This is a first post")
add_post("Hello, world 2", "This is a second post")
add_post("42", "What is this all about?")
add_post("Let it be!", "Let it be, let it be, let it be, let it be")
except Exception as e:
print("Error adding posts: {}".format(e))

# Run application server
port = os.environ.get('HTTP_PORT', 10080)
app.run(port=port, host='0.0.0.0')
print("Done.")
except Exception as exc:
print("Error adding posts: {}".format(exc))
26 changes: 0 additions & 26 deletions examples/docker-compose.yaml

This file was deleted.

1 change: 0 additions & 1 deletion examples/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ fastapi==0.111.0
uvicorn==0.29.0
tornado==6.4
aiohttp==3.9.5
uvicorn==0.29.0
gunicorn==22.0.0

aiopg~=1.4.0
Expand Down

0 comments on commit 430a3cf

Please sign in to comment.