Skip to content

Instantly share code, notes, and snippets.

@anjianshi
Last active November 25, 2019 05:11
Show Gist options
  • Save anjianshi/0cfb8bee7d7e8a7dd9c6 to your computer and use it in GitHub Desktop.
Save anjianshi/0cfb8bee7d7e8a7dd9c6 to your computer and use it in GitHub Desktop.
Use peewee-async with Tornado
import tornado.gen
import tornado.web
from tornado.platform.asyncio import AsyncIOMainLoop
from tornado.options import define, options, parse_command_line
import peewee
import asyncio
import peewee_async
import logging
# ===== Options =====
define("debug", default=False, type=bool)
parse_command_line()
# ===== Application =====
AsyncIOMainLoop().install()
application = tornado.web.Application(debug=options.debug)
application.listen(port=8888)
# ===== Database =====
if options.debug:
logger = logging.getLogger('peewee')
logger.setLevel(logging.DEBUG)
application.db = peewee_async.PostgresqlDatabase("an")
asyncio.get_event_loop().run_until_complete(application.db.connect_async())
# ===== Models =====
class User(peewee.Model):
name = peewee.CharField(null=False, unique=True)
password = peewee.CharField(null=False)
class Meta:
db_table = "customer"
database = application.db
# ===== Handlers =====
class LoginHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def post(self):
name = self.get_argument("name")
password = self.get_argument("password")
try:
user = yield from peewee_async.get_object(User, User.name == name, User.password == password)
self.write("success")
except User.DoesNotExist:
self.write("failed")
# ===== routes =====
application.add_handlers(".*$", [
(r"/login", LoginHandler)
])
# ===== start event loop =====
asyncio.get_event_loop().run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment