Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update readme and examples #271

Merged
merged 2 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Overview
* Requires Python 3.8+
* Has support for PostgreSQL via [aiopg](https://github.com/aio-libs/aiopg)
* Has support for MySQL via [aiomysql](https://github.com/aio-libs/aiomysql)
* Single point for high-level async API
* Asynchronous analogues of peewee sync methods with prefix aio_
* Drop-in replacement for sync code, sync will remain sync
* Basic operations are supported
* Transactions support is present, yet not heavily tested
Expand Down Expand Up @@ -53,15 +53,15 @@ import peewee_async

# Nothing special, just define model and database:

database = peewee_async.PostgresqlDatabase(
database = peewee_async.PooledPostgresqlDatabase(
database='db_name',
user='user',
host='127.0.0.1',
port='5432',
password='password',
)

class TestModel(peewee.Model):
class TestModel(peewee_async.AioModel):
text = peewee.CharField()

class Meta:
Expand All @@ -73,17 +73,13 @@ TestModel.create_table(True)
TestModel.create(text="Yo, I can do it sync!")
database.close()

# Create async models manager:

objects = peewee_async.Manager(database)

# No need for sync anymore!

database.set_allow_sync(False)

async def handler():
await objects.create(TestModel, text="Not bad. Watch this, I'm async!")
all_objects = await objects.execute(TestModel.select())
await TestModel.aio_create(text="Not bad. Watch this, I'm async!")
all_objects = await TestModel.select().aio_execute()
for obj in all_objects:
print(obj.text)

Expand All @@ -92,7 +88,7 @@ loop.run_until_complete(handler())
loop.close()

# Clean up, can do it sync again:
with objects.allow_sync():
with database.allow_sync():
TestModel.drop_table(True)

# Expected output:
Expand Down
14 changes: 6 additions & 8 deletions examples/aiohttp_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from secrets import token_hex
from datetime import datetime
from aiohttp import web
from peewee import Model, CharField, TextField, DateTimeField
from peewee_async import PooledPostgresqlDatabase, Manager
from peewee import CharField, TextField, DateTimeField
from peewee_async import PooledPostgresqlDatabase, AioModel

logger = logging.getLogger(__name__)

Expand All @@ -19,14 +19,12 @@
max_connections=10,
)

objects = Manager(database)

app = web.Application()

routes = web.RouteTableDef()


class Post(Model):
class Post(AioModel):
title = CharField(unique=True)
key = CharField(unique=True, default=lambda: token_hex(8))
text = TextField()
Expand All @@ -48,7 +46,7 @@ def add_post(title, text):
async def get_post_endpoint(request):
query = dict(request.query)
post_id = query.pop('p', 1)
post = await objects.get_or_none(Post, id=post_id)
post = await Post.aio_get_or_none(id=post_id)
if post:
return web.Response(text=post.text)
else:
Expand All @@ -68,10 +66,10 @@ async def update_post_endpoint(request):
except Exception as exc:
return web.Response(text=str(exc), status=400)

post = await objects.get_or_none(Post, id=post_id)
post = await Post.aio_get_or_none(id=post_id)
if post:
post.text = text
await objects.update(post)
await post.aio_save()
return web.Response(text=post.text)
else:
return web.Response(text="Not found", status=404)
Expand Down
19 changes: 12 additions & 7 deletions examples/tornado_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,17 @@
# Set up database and manager
database = peewee_async.PooledPostgresqlDatabase('test')


# Define model
class TestNameModel(peewee.Model):
class TestNameModel(peewee_async.AioModel):
name = peewee.CharField()
class Meta:
database = database

def __str__(self):
return self.name


# Create table, add some instances
TestNameModel.create_table(True)
TestNameModel.get_or_create(id=1, defaults={'name': "TestNameModel id=1"})
Expand All @@ -45,7 +47,8 @@ def __str__(self):
AsyncIOMainLoop().install()
app = tornado.web.Application(debug=True)
app.listen(port=8888)
app.objects = peewee_async.Manager(database)
app.database = database


# Add handlers
class RootHandler(tornado.web.RequestHandler):
Expand All @@ -56,7 +59,7 @@ class RootHandler(tornado.web.RequestHandler):
"""
async def post(self):
name = self.get_argument('name')
obj = await self.application.objects.create(TestNameModel, name=name)
obj = await TestNameModel.aio_create(name=name)
self.write({
'id': obj.id,
'name': obj.name
Expand All @@ -70,14 +73,15 @@ async def get(self):
return

try:
obj = await self.application.objects.get(TestNameModel, id=obj_id)
obj = await TestNameModel.aio_get(id=obj_id)
self.write({
'id': obj.id,
'name': obj.name,
})
except TestNameModel.DoesNotExist:
raise tornado.web.HTTPError(404, "Object not found!")


class CreateHandler(tornado.web.RequestHandler):
async def get(self):
loop = asyncio.get_event_loop()
Expand All @@ -95,12 +99,13 @@ async def get(self):

async def get_or_create(self):
obj_id = self.get_argument('id', None)
async with self.application.objects.atomic():
obj, created = await self.application.objects.get_or_create(
TestNameModel, id=obj_id,
async with self.application.database.aio_atomic():
obj, created = await TestNameModel.aio_get_or_create(
id=obj_id,
defaults={'name': "TestNameModel id=%s" % obj_id})
return obj


app.add_handlers('', [
(r"/", RootHandler),
(r"/create", CreateHandler),
Expand Down
Loading