Skip to content

Commit

Permalink
Add example of usage with Tornado
Browse files Browse the repository at this point in the history
  • Loading branch information
rudyryk committed Sep 27, 2015
1 parent f0ed104 commit fae9f89
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions docs/peewee_async/examples.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,70 @@
Usage examples
==============

Using with Tornado
------------------

.. code-block:: python
import tornado.gen
import tornado.web
from tornado.platform.asyncio import AsyncIOMainLoop
import peewee
import asyncio
import peewee_async
# Set up asincio loop for Tornado
AsyncIOMainLoop().install()
loop = asyncio.get_event_loop()
# Create application
application = tornado.web.Application(debug=True)
application.listen(port=8888)
# Set up database connection
database = peewee_async.PooledPostgresqlDatabase('test')
application.db = database
# Define model, handler and run application:
class TestNameModel(peewee.Model):
name = peewee.CharField()
class Meta:
database = database
class TestHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def post(self):
name = self.get_argument('name')
obj = yield from peewee_async.create_object(TestNameModel, name=name)
self.write({'id': obj.id, 'name': obj.name})
@tornado.gen.coroutine
def get(self):
obj_id = self.get_argument('id')
try:
obj = yield from peewee_async.get_object(TestNameModel, TestNameModel.id == obj_id)
self.write({'id': obj.id, 'name': obj.name})
except TestNameModel.DoesNotExist:
raise tornado.web.HTTPError(404, "Object not found!")
application.add_handlers('', [
(r"/test", TestHandler)
])
# Create database table
TestNameModel.create_table(True)
database.close()
# Set up async connection and run application server
loop.run_until_complete(application.db.connect_async())
loop.run_forever()
Using both sync and async calls
-------------------------------

Expand Down

0 comments on commit fae9f89

Please sign in to comment.