Skip to content

Commit e20dad1

Browse files
committed
Minor docs and examples updates
1 parent 90dceb3 commit e20dad1

File tree

2 files changed

+7
-118
lines changed

2 files changed

+7
-118
lines changed

docs/peewee_async/tornado.rst

Lines changed: 5 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -9,129 +9,17 @@ The complete working example is provided below. And here are some general notes:
99

1010
1. **Be aware of current asyncio event loop!**
1111

12-
In the provided example we use the default event loop everywhere, and that's OK. But if you see your application got silently stuck, that's most probably that some task is started on different loop and will never complete as long as that loop is not running.
12+
In the provided example we use the default event loop everywhere, and that's OK. But if you see your application got silently stuck, that's most probably that some task is started on the different loop and will never complete as long as that loop is not running.
1313

1414
2. Tornado request handlers **does not** start asyncio tasks by default.
1515

16-
The ``CreateHandler`` demostrates that, ``current_task()`` returns ``None`` until taks is run explicitly.
16+
The ``CreateHandler`` demostrates that, ``current_task()`` returns ``None`` until task is run explicitly.
1717

1818
3. Transactions **must** run within task context.
1919

2020
All transaction operations have to be done within task. So if you need to run a transaction from Tornado handler, you have to wrap your call into task with ``create_task()`` or ``ensure_future()``.
2121

22-
**Also note:** if you spawn an extra task during transaction, it will run outside of transaction.
22+
**Also note:** if you spawn an extra task during a transaction, it will run outside of that transaction.
2323

24-
.. code-block:: python
25-
26-
import tornado.web
27-
import logging
28-
import peewee
29-
import asyncio
30-
import peewee_async
31-
32-
# Set up database and manager
33-
database = peewee_async.PooledPostgresqlDatabase('test')
34-
35-
# Define model
36-
class TestNameModel(peewee.Model):
37-
name = peewee.CharField()
38-
class Meta:
39-
database = database
40-
41-
def __str__(self):
42-
return self.name
43-
44-
# Create table, add some instances
45-
TestNameModel.create_table(True)
46-
TestNameModel.get_or_create(id=1, defaults={'name': "TestNameModel id=1"})
47-
TestNameModel.get_or_create(id=2, defaults={'name': "TestNameModel id=2"})
48-
TestNameModel.get_or_create(id=3, defaults={'name': "TestNameModel id=3"})
49-
database.close()
50-
51-
# Set up Tornado application on asyncio
52-
from tornado.platform.asyncio import AsyncIOMainLoop
53-
AsyncIOMainLoop().install()
54-
app = tornado.web.Application(debug=True)
55-
app.listen(port=8888)
56-
app.objects = peewee_async.Manager(database)
57-
58-
# Add handlers
59-
class RootHandler(tornado.web.RequestHandler):
60-
"""Accepts GET and POST methods.
61-
62-
POST: create new instance, `name` argument is required
63-
GET: get instance by id, `id` argument is required
64-
"""
65-
async def post(self):
66-
name = self.get_argument('name')
67-
obj = await self.application.objects.create(TestNameModel, name=name)
68-
self.write({
69-
'id': obj.id,
70-
'name': obj.name
71-
})
72-
73-
async def get(self):
74-
obj_id = self.get_argument('id', None)
75-
76-
if not obj_id:
77-
self.write("Please provide the 'id' query argument, i.e. ?id=1")
78-
return
79-
80-
try:
81-
obj = await self.application.objects.get(TestNameModel, id=obj_id)
82-
self.write({
83-
'id': obj.id,
84-
'name': obj.name,
85-
})
86-
except TestNameModel.DoesNotExist:
87-
raise tornado.web.HTTPError(404, "Object not found!")
88-
89-
class CreateHandler(tornado.web.RequestHandler):
90-
async def get(self):
91-
loop = asyncio.get_event_loop()
92-
task1 = asyncio.Task.current_task()
93-
task2 = loop.create_task(self.get_or_create())
94-
obj = await task2
95-
self.write({
96-
'task1': task1 and id(task1),
97-
'task2': task2 and id(task2),
98-
'obj': str(obj),
99-
'text': "'task1' should be null, "
100-
"'task2' should be not null, "
101-
"'obj' should be newly created object",
102-
})
103-
104-
async def get_or_create(self):
105-
obj_id = self.get_argument('id', None)
106-
async with self.application.objects.atomic():
107-
obj, created = await self.application.objects.get_or_create(
108-
TestNameModel, id=obj_id,
109-
defaults={'name': "TestNameModel id=%s" % obj_id})
110-
return obj
111-
112-
app.add_handlers('', [
113-
(r"/", RootHandler),
114-
(r"/create", CreateHandler),
115-
])
116-
117-
# Setup verbose logging
118-
log = logging.getLogger('')
119-
log.addHandler(logging.StreamHandler())
120-
log.setLevel(logging.DEBUG)
121-
122-
# Run loop
123-
print("""Run application server http://127.0.0.1:8888
124-
125-
Try GET urls:
126-
http://127.0.0.1:8888?id=1
127-
http://127.0.0.1:8888/create?id=100
128-
129-
Try POST with name=<some text> data:
130-
http://127.0.0.1:8888
131-
132-
^C to stop server""")
133-
loop = asyncio.get_event_loop()
134-
try:
135-
loop.run_forever()
136-
except KeyboardInterrupt:
137-
print(" server stopped")
24+
.. literalinclude:: ../../examples/tornado_sample.py
25+
:start-after: # Start example

examples/tornado_sample.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
Copyright (c) 2016, Alexey Kinëv <[email protected]>
1313
1414
"""
15+
# Start example [marker for docs]
1516
import tornado.web
1617
import logging
1718
import peewee
@@ -78,7 +79,7 @@ async def get(self):
7879
class CreateHandler(tornado.web.RequestHandler):
7980
async def get(self):
8081
loop = asyncio.get_event_loop()
81-
task1 = asyncio.Task.current_task()
82+
task1 = asyncio.Task.current_task() # Just to demonstrate it's None
8283
task2 = loop.create_task(self.get_or_create())
8384
obj = await task2
8485
self.write({

0 commit comments

Comments
 (0)