Skip to content

Commit fae9f89

Browse files
committed
Add example of usage with Tornado
1 parent f0ed104 commit fae9f89

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

docs/peewee_async/examples.rst

+64
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,70 @@
11
Usage examples
22
==============
33

4+
Using with Tornado
5+
------------------
6+
7+
.. code-block:: python
8+
9+
import tornado.gen
10+
import tornado.web
11+
from tornado.platform.asyncio import AsyncIOMainLoop
12+
import peewee
13+
import asyncio
14+
import peewee_async
15+
16+
# Set up asincio loop for Tornado
17+
AsyncIOMainLoop().install()
18+
loop = asyncio.get_event_loop()
19+
20+
# Create application
21+
application = tornado.web.Application(debug=True)
22+
application.listen(port=8888)
23+
24+
# Set up database connection
25+
database = peewee_async.PooledPostgresqlDatabase('test')
26+
application.db = database
27+
28+
# Define model, handler and run application:
29+
30+
31+
class TestNameModel(peewee.Model):
32+
name = peewee.CharField()
33+
class Meta:
34+
database = database
35+
36+
37+
class TestHandler(tornado.web.RequestHandler):
38+
@tornado.gen.coroutine
39+
def post(self):
40+
name = self.get_argument('name')
41+
obj = yield from peewee_async.create_object(TestNameModel, name=name)
42+
self.write({'id': obj.id, 'name': obj.name})
43+
44+
@tornado.gen.coroutine
45+
def get(self):
46+
obj_id = self.get_argument('id')
47+
try:
48+
obj = yield from peewee_async.get_object(TestNameModel, TestNameModel.id == obj_id)
49+
self.write({'id': obj.id, 'name': obj.name})
50+
except TestNameModel.DoesNotExist:
51+
raise tornado.web.HTTPError(404, "Object not found!")
52+
53+
54+
application.add_handlers('', [
55+
(r"/test", TestHandler)
56+
])
57+
58+
59+
# Create database table
60+
TestNameModel.create_table(True)
61+
database.close()
62+
63+
# Set up async connection and run application server
64+
loop.run_until_complete(application.db.connect_async())
65+
loop.run_forever()
66+
67+
468
Using both sync and async calls
569
-------------------------------
670

0 commit comments

Comments
 (0)