当前位置: 首页>>代码示例>>Python>>正文


Python SqliteDatabase.create_tables方法代码示例

本文整理汇总了Python中peewee.SqliteDatabase.create_tables方法的典型用法代码示例。如果您正苦于以下问题:Python SqliteDatabase.create_tables方法的具体用法?Python SqliteDatabase.create_tables怎么用?Python SqliteDatabase.create_tables使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在peewee.SqliteDatabase的用法示例。


在下文中一共展示了SqliteDatabase.create_tables方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TestManage

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
class TestManage(unittest.TestCase):
    def setUp(self):
        self.db = SqliteDatabase('peewee.db')
        self.db.connect()

    def tearDown(self):
        self.db.close()

    def testCreate(self):
        self.db.create_tables(ALL_MODELS, safe=True)
开发者ID:CaveMike,项目名称:flask_rest,代码行数:12,代码来源:manage.py

示例2: init_models

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
def init_models(app):
    if app.config['TESTING']:
        database = SqliteDatabase(':memory:')
    else:
        database = SqliteDatabase('local.db')

    database_proxy.initialize(database)
    database.connect()
    database.create_tables([
        TodoItem,
    ], safe=True)
开发者ID:beetleman,项目名称:examle_python_website,代码行数:13,代码来源:models.py

示例3: SqliteDatabase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
import sqlite3
from peewee import Model, SqliteDatabase, DateTimeField, ForeignKeyField, FloatField, CharField
from datetime import datetime


DB = SqliteDatabase('finance-manager.db')
DB.connect()


class User(Model):
    username = CharField(primary_key=True)


    class Meta:
        database = DB


class Amount(Model):
    user = ForeignKeyField(User, backref='amount')
    amount = FloatField()
    date_time = DateTimeField()


    class Meta:
        database = DB

DB.create_tables([User, Amount])
DB.close()
开发者ID:katadoka,项目名称:Simple-Website,代码行数:30,代码来源:modelsorm.py

示例4: TestBase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
class TestBase(unittest.TestCase):
    def populate_database(self):
        self.db = SqliteDatabase('peewee.db')
        self.db.connect()

        self.db.create_tables(model.ALL_MODELS, safe=True)

        for m in model.ALL_MODELS:
            m.delete().execute()

        self.db.close()

        # Config
        release = model.Config.create(app_api_key=APP_API_KEY, messaging_api_key=MESSAGING_API_KEY)

        admin_user = model.User.create_user(name='Administrator', description='Administrator', email='[email protected]', username=TEST_USER, password=TEST_PASSWORD)

        # Groups
        admin = model.Group.create(name=TEST_USER, owner=admin_user)
        user = model.Group.create(name='user', owner=admin_user)
        guest = model.Group.create(name='guest', owner=admin_user)

        admin.add_user(admin_user)

        # Users
        model.Device.create(user=admin, name='d2', resource='work', type='computer', dev_id='a')

        chloe = model.User.create_user(name='Chloe', username='chloe', password=TEST_PASSWORD)
        d = chloe.create_device(name='d2', resource='work', type='computer', dev_id='a')
        chloe.create_device(name='d0', resource='home', type='phone', dev_id='b')
        chloe.create_device(name='d3', resource='home', type='laptop', dev_id='c')
        chloe.create_device(name='d1', resource='work', type='phone', dev_id='d')
        model.UserToGroup.create(user=chloe, group=guest)

        sunshine = model.User.create_user(name='Sunshine', username='sunshine', password=TEST_PASSWORD)
        sunshine.create_device(name='d5', resource='work', type='phone', dev_id='e')
        model.UserToGroup.create(user=sunshine, group=user)
        model.UserToGroup.create(user=sunshine, group=guest)
        p = model.Publication.create(user=sunshine, topic='Life and Times of Sunshine', description='', publish_group=guest, subscribe_group=guest)
        model.Message.create(user=sunshine, to_publication=p, subject='First post!')
        model.Message.create(user=sunshine, to_publication=p, subject='Eating breakfast')
        model.Message.create(user=sunshine, to_publication=p, subject='Time for a nap')

        guinness = model.User.create_user(name='Guinness', username='guinness', password=TEST_PASSWORD)
        guinness.create_device(name='d7', resource='work', type='phone', dev_id='g')
        model.UserToGroup.create(user=guinness, group=guest)

        felix = model.User.create_user(name='Felix', username='felix', password=TEST_PASSWORD)
        felix.create_device(name='d6', resource='work', type='phone', dev_id='f')
        model.UserToGroup.create(user=felix, group=guest)
        model.Subscription.create(user=felix, publication=p)
        model.Message.create(user=felix, to_publication=p, subject='boring...')
        model.Message.create(user=felix, to_user=sunshine, subject='hi sunshine')
        model.Message.create(user=felix, to_device=d, subject='hi chloe')
        model.Message.create(user=felix, to_user=chloe, subject='hi chloe again')

        ducky = model.User.create_user(name='Ducky', username='ducky', password=TEST_PASSWORD)
        ducky.create_device(name='d8', resource='work', type='phone', dev_id='h')
        model.UserToGroup.create(user=ducky, group=admin)
        model.UserToGroup.create(user=ducky, group=user)
        model.UserToGroup.create(user=ducky, group=guest)

    def setUp(self):
        self.app = app.test_client()
        self.populate_database()

    def request(self, method, url, auth=None, json_data=None, **kwargs):
        headers = kwargs.get('headers', {})

        if auth:
            # Add the auth header if credentials are specified.
            headers['Authorization'] = 'Basic %s' % b64encode(bytes(auth[0] + ':' + auth[1], 'utf-8')).decode('ascii')

        if json:
            headers['Content-Type'] = 'application/json'
            kwargs['data'] = json.dumps(obj=json_data)
            #print(kwargs['data'])

        kwargs['headers'] = headers
        #print(kwargs['headers'])

        return self.app.open(url, method=method, **kwargs)
开发者ID:CaveMike,项目名称:flask_rest,代码行数:84,代码来源:test.py

示例5: SqliteDatabase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
from peewee import SqliteDatabase, Model, \
    CharField, IntegerField, DateField, BlobField

db = SqliteDatabase(':memory:', threadlocals=True)

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

class Vehicle(BaseModel):
    description = CharField(null=False)
    cylinder = IntegerField(null=False)
    brand = CharField(null=False)
    year = DateField(formats="%Y")
    owner = CharField(null=False)
    photo = BlobField(null=True)

db.connect()
db.create_tables([Vehicle])
开发者ID:RodericDay,项目名称:Carmack,代码行数:21,代码来源:models.py

示例6: SqliteDatabase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
pw = SqliteDatabase('peewee-simple.db')


class Book(Model):
    title = CharField(null=True, unique=True)
    year_published = IntegerField()

    class Meta:
        database = pw


class BookResource(ModelResource):
    class Meta:
        name = 'book'
        model = Book

    class Schema:
        year_published = fields.Integer(minimum=1400)


api = Api(app, default_manager=PeeweeManager)
api.add_resource(BookResource)

if not isfile('peewee-simple.db'):
    pw.connect()
    pw.create_tables([Book])

if __name__ == '__main__':
    app.run()
开发者ID:kolanos,项目名称:potion,代码行数:31,代码来源:peewee_simple.py

示例7: open

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
    def open(self, *args, **kwargs):
        cmd = [s.replace('\ ', ' ') for s in
               re.split(r'(?<!\\) ', self.command)] + list(args)
        print(str(cmd))
        ukwargs = self.DEFAULT_POPEN_ARGS.copy()
        if self.shell:
            ukwargs.update(self.SHELL_ALL_DEVNULL)
        ukwargs.update(kwargs)
        return Popen(cmd, **ukwargs)

    class Meta:
        database = os_db


# safely create FileCommand table, its const records are referenced in FileType
os_db.create_tables([FileCommand], safe=True)


class FileType(BaseModel):
    type = CharField()
    mime = CharField(null=True, default=None)
    command = ForeignKeyField(FileCommand, null=True, default=None)

    DIR = Record(id=1, type="Directory")
    PDF = Record(id=2, type="PDF", command=FileCommand.OPEN)
    TXT = Record(id=3, type="TXT", command=FileCommand.OPEN)
    XML = Record(id=4, type="XML", command=FileCommand.OPEN)
    ASP = Record(id=5, type="AS Project", command=FileCommand.ANDROID_STUDIO)

    OTH = Record(id=10, type="unknown file")
开发者ID:IARI,项目名称:asp_grader,代码行数:32,代码来源:models.py

示例8: SqliteDatabase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
from datetime import datetime
from peewee import SqliteDatabase, CharField, DateTimeField, Model

db = SqliteDatabase("clipboard.db")


class Paste(Model):
    text = CharField()
    date = DateTimeField()

    class Meta:
        database = db


db.create_tables([Paste])


def save_new_paste(text):
    paste = Paste(text=text, date=datetime.now())
    paste.save()


def get_lastest_paste():
    for paste in Paste.select().order_by(Paste.date.desc()):
        return paste.text


def get_pastes():
    return Paste.select().order_by(Paste.date.desc())

开发者ID:Arya04,项目名称:hello-world,代码行数:31,代码来源:db.py

示例9: Field

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
    name = Field(String, 10)
    age = Field(Int, 2)
    salary = Field(Float, 14, precision=4)

    class Meta:
        selector_string = u'01'
        database = db


class Address(PeeweeRecord):
    typ = Field(Int, 2)
    address = Field(String, 10, truncate=True)
    phone = Field(String, 20)

    class Meta:
        selector_string = u'02'
        database = db

# read sample file
engine = FixedEngine([Header, Address], selector_slice=(0, 2))

# connect to db
db.connect()

# create tables
db.create_tables([Header, Address])

# write fields to db using save
for r in engine.load('../samples/sample_utf8.txt'):
    r.save()
开发者ID:arielrossanigo,项目名称:pypfp,代码行数:32,代码来源:dump_to_db.py

示例10: SqliteDatabase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
database = SqliteDatabase('kongonline.sqlite', check_same_thread=False)
database.connect()


class Stats(Model):
    time_t = IntegerField(null=True)
    online = IntegerField(null=True)
    games = IntegerField(null=True)

    class Meta:
        database = database
        db_table = 'stats'


def write_info(time, online, games):
    Stats.create(time_t=time, online=online, games=games)


def get_last(num=10):
    ret = []
    for item in Stats.select().order_by(Stats.time_t.desc()).limit(num):
        time = dt.fromtimestamp(item.time_t).strftime('%y-%m-%d|%H:%M:%S')
        ret.append((time, item.online, item.games))
    return ret


def count_entries():
    return Stats.select().count()

database.create_tables((Stats,), safe=True)
开发者ID:mFoxRU,项目名称:kongonline,代码行数:32,代码来源:model.py

示例11: AgentBook

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
class AgentBook(object):

    def __init__(self, db):
        """ Initialize the manager for deferred messages and serialized
            information.

            db - absolute path to database file (sqlite)
        """
        self.db = SqliteDatabase(db)
        agent_book_proxy.initialize(self.db)
        self.db.create_tables([AgentInfo, AgentMessage], True)

    def delete_info(self, agent):
        """ Delete stored information for a given agent.

            agent - agent name
        """
        scoutlog.info('deleting stored information of agent %s' % agent)

        try:
            info = AgentInfo.get(AgentInfo.agent == agent)

        except AgentInfo.DoesNotExist:
            scoutlog.error('no information to delete for agent %s' % agent)
            return False

        info.delete_instance()
        return True

    def delete_messages(self, agent):
        """ Delete stored messages for a given agent.

            agent - agent name
        """
        scoutlog.info('deleting stored messages of agent %s' % agent)

        query = AgentMessage.delete().where(AgentMessage.agent == agent)
        query.execute()
        return True

    def get_info(self, agent):
        """ Return the stored information (if any).

            agent - agent name
        """
        scoutlog.info('obtaining stored information of agent %s' % agent)

        try:
            return AgentInfo.get(AgentInfo.agent == agent).info

        except AgentInfo.DoesNotExist:
            scoutlog.error('no information stored for agent %s' % agent)
            return None

    def get_messages(self, agent):
        """ Return all messages for a given agent.

            agent - agent name
        """
        scoutlog.info('obtaining stored stored messages for agent %s' % agent)

        try:
            return [a.message for a in AgentMessage.select().where(
                AgentMessage.agent == agent)]

        except:
            # Not found?
            scoutlog.warning('no messages for agent %s' % agent)
            return []

    def store_info(self, parser):
        """ Store serialized information for a given agent.

            parser - zoe MessageParser instance
        """
        dst = parser.get('agent')
        scoutlog.info('storing information of agent %s' % dst)

        new_map = parser._map.copy()

        # Prepare for direct dispatch
        new_map['dst'] = dst
        del new_map['agent']

        # Original tags removed! (should only have scout ones)
        new_map['tag'] = ['settle!', ]

        # Store message
        raw_msg = zoe.MessageBuilder(new_map).msg()

        try:
            AgentInfo.create(agent=dst, info=raw_msg)

        except IntegrityError as e:
            scoutlog.exception('failed to store information of agent %s' % dst)

    def store_message(self, parser):
        """ Store deferred messages. Convert special tags to their original
            counterparts.

#.........这里部分代码省略.........
开发者ID:rmed,项目名称:bachelor_thesis,代码行数:103,代码来源:book.py

示例12: ZoneBook

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
class ZoneBook(object):

    def __init__(self, db):
        """ Initialize the manager for agent locations and outpost resource
            storage.

            db - absolute path to database file (sqlite)
        """
        self.db = SqliteDatabase(db)
        zone_book_proxy.initialize(self.db)
        self.db.create_tables([OutpostZone, AgentZone], True)

    def get_agents(self):
        """ Return a list of agents.

            Note that this returns the object rather than just the name in
            case other information is wanted.
        """
        return list(AgentZone.select())

    def get_agent_location(self, name):
        """ Get the location for a given agent.

            Returns None if it does not exist.

            name - name of the agent
        """
        scoutlog.info('obtaining location of agent %s' % name)

        try:
            return AgentZone.get(AgentZone.name == name).location.name

        except Exception as e:
            scoutlog.warning('could not get location of agent %s' % name)
            return None

    def get_agents_in(self, outpost_id):
        """ Get the agents found in a given location.

            outpost_id - outpost id to search for
        """
        scoutlog.info('obtaining agents located in %s' % outpost_id)

        try:
            outpost = OutpostZone.get(OutpostZone.name == outpost_id)

        except OutpostZone.DoesNotExist as e:
            scoutlog.warning('outpost %s not found in zone book' % outpost_id)
            return []

        return outpost.agents

    def get_agent_names_in(self, outpost_id):
        """ Get the agent names found in a given location.

            outpost_id - outpost id to search for
        """
        scoutlog.info('obtaining agent names located in %s' % outpost_id)

        try:
            outpost = OutpostZone.get(OutpostZone.name == outpost_id)

        except OutpostZone.DoesNotExist as e:
            scoutlog.warning('outpost %s not found in zone book' % outpost_id)
            return []

        return [agent.name for agent in outpost.agents]

    def get_outposts(self):
        """ Return a list of outposts.

            Note that this returns the object rather than just the name in
            case other information is wanted.
        """
        return list(OutpostZone.select())


    def is_outpost_running(self, name):
        """ Check if an outpost is known to be running or not.

            Returns boolean value.

            name - name of the outpost
        """
        scoutlog.info('checking if outpost %s is currently running' % name)

        try:
            return OutpostZone.get(OutpostZone.name == name).is_running

        except OutpostZone.DoesNotExist as e:
            scoutlog.warning('outpost %s not found in zone book' % name)
            return None

    def move_agent(self, name, location):
        """ Move an agent to the given location.

            name     - name of the agent
            location - new location of the agent
        """
        scoutlog.info('moving agent %s to %s' % (name, location))
#.........这里部分代码省略.........
开发者ID:rmed,项目名称:bachelor_thesis,代码行数:103,代码来源:book.py

示例13: SqliteDatabase

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
from peewee import BooleanField, IntegerField, Model, SqliteDatabase, TextField

db = SqliteDatabase('gen/data.db')


class User(Model):
    user_id = IntegerField(unique=True)
    chat_id = IntegerField()
    first_name = TextField()
    last_name = TextField(null=True)
    is_member = BooleanField()  # Current status of user (member/left)

    class Meta:
        database = db


db.create_tables([User], safe=True)
开发者ID:arvego,项目名称:mm-randbot,代码行数:19,代码来源:models.py

示例14: Operation

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
class Operation(BaseModel):
    timestamp = DateTimeField(primary_key=True)
    user = ForeignKeyField(User, related_name="operations", null=True)
    chamber = ForeignKeyField(Chamber, related_name='chamber', null=True)
    action = CharField(null=True)
    locker = CharField(default='Dev Locker')

    def __repr__(self):
        return '<TRANSACTION> {}'.format(self.timestamp)

    @staticmethod
    @db.atomic()
    def add_operation(chamber=None, action=None, user=None):
        now = datetime.utcnow()
        op = Operation.create(timestamp=now, chamber=chamber,
                              action=action, user=user)
        op.save()
        return op

# this creates indexes, not sure why
tables = [User, Operation, Chamber]
db.create_tables(tables, True)


# ERASE TABLES
def drop_tables():
    try:
        db.drop_tables(tables)
    except:
        pass
开发者ID:gtalarico,项目名称:locker,代码行数:32,代码来源:model.py

示例15: get_user

# 需要导入模块: from peewee import SqliteDatabase [as 别名]
# 或者: from peewee.SqliteDatabase import create_tables [as 别名]
        database = db


def get_user(user_id):
    try:
        user = User.get(User.id == user_id)
    except User.DoesNotExist:
        user = User.get(User.id == 0)
    return user

if __name__ == "__main__":
    if User.table_exists():
        print("Database Already Exists")
        sys.exit()

    db.connect()
    db.create_tables([User])

    User.insert_many([
        {"id": 0, "name": "Invlid User", "langpair": "!!|!!"},
        {"id": 120755813, "name": "Boris", "langpair": "ru|en"},
        {"id": 93649293, "name": "Elizaveta", "langpair": "ru|en"},
        {"id": 77815902, "name": "James", "langpair": "en|ru"},
        {"id": 68382468, "name": "Jill", "langpair": "en|ru"},
        {"id": 82080280, "name": "Kyle", "langpair": "en|ru", "admin": True},
        {"id": 117778855, "name": "Mickey", "langpair": "en|ru"},
        {"id": 97384423, "name": "Nataly", "langpair": "__|__"},
        {"id": 96351689, "name": "Transbotor", "langpair": "!!|!!"},
    ]).execute()
    db.close()
开发者ID:KyleJamesWalker,项目名称:transbotor,代码行数:32,代码来源:brain.py


注:本文中的peewee.SqliteDatabase.create_tables方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。