我应该如何使用上下文管理器来执行特定的peewee模型任务?

时间:2018-09-10 08:43:21

标签: peewee

我已经实现了以下代码:

from peewee import Model, MySQLDatabase, CharField

from contextlib import contextmanager

@contextmanager 
def get_database(): 
    return MySQLDatabase("films", user="root", host="localhost", port=3306)


class BasePeeweeModel(Model): 
    class Meta: database = db

class Films(BasePeeWeeModel): 
    code = CharField() 
    name = CharField()


try: 
    db.create_tables([Films]) 
except OperationalError: 
    print "Films able already exists"

with get_database() as db: 
     fobj = Films() 
     fobj.code = "LJ" 
     fobj.name = "Le Jatte" 
     fobj.save()

我希望能够在完成表任务后显式关闭数据库连接!

0 个答案:

没有答案
相关问题