Пример #1
0
def define_db(*args, **kwargs):
    set_sql_debug(app.debug, True)
    db = Database()
    db.bind(*args, **kwargs)
    define_entities(db)
    db.generate_mapping(create_tables=True)
    return db
Пример #2
0
def clean_core(args):
    major_version = '.'.join(get_distribution('CGRdb').version.split('.')[:-1])
    schema = args.name

    db_config = Database()
    LazyEntityMeta.attach(db_config, database='CGRdb_config')
    db_config.bind('postgres', **args.connection)
    db_config.generate_mapping()

    with db_session:
        config = db_config.Config.get(name=schema, version=major_version)
    if not config:
        raise KeyError('schema not exists or version incompatible')
    config = config.config

    for p in config['packages']:
        try:
            p = get_distribution(p)
            import_module(p.project_name)
        except (DistributionNotFound, VersionConflict):
            raise ImportError(
                f'packages not installed or has invalid versions: {p}')

    db = Database()
    LazyEntityMeta.attach(db, schema, 'CGRdb')
    db.bind('postgres', **args.connection)
    db.generate_mapping()

    with db_session:
        db.execute(f'TRUNCATE TABLE "{schema}"."MoleculeSearchCache", '
                   f'"{schema}"."ReactionSearchCache" RESTART IDENTITY')
Пример #3
0
def pony_setup(request, app, tmpdir, realdburl):

    pytest.importorskip("pony")
    from pony.orm import Database, Optional, Required, Set
    from pony.orm.core import SetInstance

    SetInstance.append = SetInstance.add
    db = Database()

    class Role(db.Entity):
        name = Required(str, unique=True)
        description = Optional(str, nullable=True)
        users = Set(lambda: User)

    class User(db.Entity):
        email = Required(str)
        fs_uniquifier = Required(str, nullable=False)
        username = Optional(str)
        security_number = Optional(int)
        password = Optional(str, nullable=True)
        last_login_at = Optional(datetime)
        current_login_at = Optional(datetime)
        tf_primary_method = Optional(str, nullable=True)
        tf_totp_secret = Optional(str, nullable=True)
        tf_phone_number = Optional(str, nullable=True)
        us_totp_secrets = Optional(str, nullable=True)
        us_phone_number = Optional(str, nullable=True)
        last_login_ip = Optional(str)
        current_login_ip = Optional(str)
        login_count = Optional(int)
        active = Required(bool, default=True)
        confirmed_at = Optional(datetime)
        roles = Set(lambda: Role)

        def has_role(self, name):
            return name in {r.name for r in self.roles.copy()}

    if realdburl:
        db_url, db_info = _setup_realdb(realdburl)
        pieces = urlsplit(db_url)
        db.bind(
            provider=pieces.scheme.split("+")[0],
            user=pieces.username,
            password=pieces.password,
            host=pieces.hostname,
            database=pieces.path[1:],
        )
    else:
        app.config["DATABASE"] = {"name": ":memory:", "engine": "pony.SqliteDatabase"}
        db.bind("sqlite", ":memory:", create_db=True)

    db.generate_mapping(create_tables=True)

    def tear_down():
        if realdburl:
            _teardown_realdb(db_info)

    request.addfinalizer(tear_down)

    return PonyUserDatastore(db, User, Role)
Пример #4
0
def update_core(args):
    major_version = '.'.join(get_distribution('CGRdb').version.split('.')[:-1])
    schema = args.name

    db_config = Database()
    LazyEntityMeta.attach(db_config, database='CGRdb_config')
    db_config.bind('postgres',
                   user=args.user,
                   password=args.password,
                   host=args.host,
                   database=args.base,
                   port=args.port)
    db_config.generate_mapping()

    with db_session:
        config = db_config.Config.get(name=schema, version=major_version)
    if not config:
        raise KeyError('schema not exists or version incompatible')
    config = config.config

    for p in config['packages']:
        try:
            p = get_distribution(p)
            import_module(p.project_name)
        except (DistributionNotFound, VersionConflict):
            raise ImportError(
                f'packages not installed or has invalid versions: {p}')

    db = Database()
    LazyEntityMeta.attach(db, schema, 'CGRdb')
    db.bind('postgres',
            user=args.user,
            password=args.password,
            host=args.host,
            database=args.base,
            port=args.port)
    db.generate_mapping()

    with db_session:
        db.execute(init_session.replace('{schema}', schema))
        db.execute(merge_molecules.replace('{schema}', schema))

        db.execute(insert_molecule.replace('{schema}', schema))
        db.execute(after_insert_molecule.replace('{schema}', schema))
        db.execute(delete_molecule.replace('{schema}', schema))

        db.execute(insert_reaction.replace('{schema}', schema))

        db.execute(search_similar_molecules.replace('{schema}', schema))
        db.execute(search_substructure_molecule.replace('{schema}', schema))
        db.execute(search_similar_reactions.replace('{schema}', schema))
        db.execute(search_substructure_reaction.replace('{schema}', schema))
        db.execute(
            search_substructure_fingerprint_molecule.replace(
                '{schema}', schema))
        db.execute(
            search_similar_fingerprint_molecule.replace('{schema}', schema))
        db.execute(search_reactions_by_molecule.replace('{schema}', schema))
        db.execute(search_mappingless_reaction.replace('{schema}', schema))
Пример #5
0
def _bind(db_file: Path, create_tables=False) -> Database:
    db = Database()
    _define_entities(db)

    db.bind(provider="sqlite", filename=str(db_file))
    db.generate_mapping(create_tables=create_tables)

    return db
Пример #6
0
def model():
    _db = Database()

    class TestModel(_db.Entity, NapMixin):
        pass

    _db.bind('sqlite', ':memory:')
    _db.generate_mapping(create_tables=True)
    return TestModel
Пример #7
0
def init_core(args):
    db = Database()
    LazyEntityMeta.attach(db, database='CGRdb_config')
    db.bind('postgres', **args.connection)
    db.generate_mapping(create_tables=True)

    with db_session:
        db.execute('CREATE EXTENSION IF NOT EXISTS intarray')
        db.execute('CREATE EXTENSION IF NOT EXISTS plpython3u')
Пример #8
0
def init_core(args):
    db = Database()
    LazyEntityMeta.attach(db, database='CGRdb_config')
    db.bind('postgres',
            user=args.user,
            password=args.password,
            host=args.host,
            database=args.base,
            port=args.port)
    db.generate_mapping(create_tables=True)
Пример #9
0
def index_core(args):
    major_version = '.'.join(get_distribution('CGRdb').version.split('.')[:-1])
    schema = args.name

    db_config = Database()
    LazyEntityMeta.attach(db_config, database='CGRdb_config')
    db_config.bind('postgres',
                   user=args.user,
                   password=args.password,
                   host=args.host,
                   database=args.base,
                   port=args.port)
    db_config.generate_mapping()

    with db_session:
        config = db_config.Config.get(name=schema, version=major_version)
    if not config:
        raise KeyError('schema not exists or version incompatible')
    config = config.config

    for p in config['packages']:
        try:
            p = get_distribution(p)
            import_module(p.project_name)
        except (DistributionNotFound, VersionConflict):
            raise ImportError(
                f'packages not installed or has invalid versions: {p}')

    db = Database()
    LazyEntityMeta.attach(db, schema, 'CGRdb')
    db.bind('postgres',
            user=args.user,
            password=args.password,
            host=args.host,
            database=args.base,
            port=args.port)
    db.generate_mapping()

    with db_session:
        db.execute(
            f'CREATE INDEX idx_moleculestructure__smlar ON "{schema}"."MoleculeStructure" USING '
            'GIST (fingerprint _int4_sml_ops)')
        db.execute(
            f'CREATE INDEX idx_moleculestructure__subst ON "{schema}"."MoleculeStructure" USING '
            'GIN (fingerprint gin__int_ops)')
        db.execute(
            f'CREATE INDEX idx_reactionindex__smlar ON "{schema}"."ReactionIndex" USING '
            'GIST (fingerprint _int4_sml_ops)')
        db.execute(
            f'CREATE INDEX idx_reactionindex__subst ON "{schema}"."ReactionIndex" USING '
            'GIN (fingerprint gin__int_ops)')
Пример #10
0
def create_core(**kwargs):
    schema = kwargs['name']
    user = DB_USER if kwargs['user'] is None else kwargs['user']
    password = DB_PASS if kwargs['pass'] is None else kwargs['pass']

    x = Database()
    load_tables(x, schema)

    if DEBUG:
        sql_debug(True)
        x.bind('sqlite', '../database.sqlite')
    else:
        x.bind('postgres', user=user, password=password, host=DB_HOST, database=DB_NAME)

    x.generate_mapping(create_tables=True)
Пример #11
0
    def db(self):
        db = Database()
        load_tables(db, 'cgrdb', None)

        db.bind('postgres',
                user='******',
                password='******',
                host=None,
                database=None)
        with db_session:
            db.execute('drop SCHEMA cgrdb CASCADE')
            db.execute('CREATE SCHEMA cgrdb')

        db.generate_mapping(create_tables=True)

        return db
Пример #12
0
def geef_chocoladeletters(familie: list):
    db = Database()
    db.bind(provider='sqlite', filename=':memory:', create_db=True)
    db.generate_mapping(create_tables=True)

    for familielid in familie:
        if isinstance(familielid, Familielid):
            persoon = Persoon(naam=familielid.naam,
                              geboortedatum=familielid.geboortedatum)
            cadeau_idee = 'chocoladeletter ' + familielid.naam[:1].upper()
            aanleiding = 'Sinterklaas'
            cadeau = Cadeau(aanleiding=aanleiding,
                            omschrijving=cadeau_idee,
                            datum=vandaag())

    commit()
Пример #13
0
    def load_schemas(cls):
        if not cls.__schemas:
            for schema in DB_DATA_LIST:
                x = Database()
                cls.__schemas[schema] = x
                cls.__databases[schema] = load_tables(x, schema)
                if DEBUG:
                    x.bind('sqlite', 'database.sqlite')
                else:
                    x.bind('postgres',
                           user=DB_USER,
                           password=DB_PASS,
                           host=DB_HOST,
                           database=DB_NAME)

                x.generate_mapping(create_tables=False)
Пример #14
0
class Client:
    db: Database
    mappings: List[str] = []

    def bind_db(self):
        self.db = Database()
        self.db.bind(
            provider="sqlite", filename=str(BASE_DIR / "db.sqlite3"), create_db=True
        )

    @property
    def Entity(self) -> Type[Entity]:
        return self.db.Entity

    def generate_mappings(self):
        from model import Profile, Message

        self.db.generate_mapping(create_tables=True)
Пример #15
0
class DatabaseTest(unittest.TestCase):
    def setUp(self):
        self.db = Database()

    def tearDown(self):
        self.db = None

    def test_database_connection(self):
        try:
            self.db.bind(
                provider="postgres",
                user="******",
                password="******",
                host="127.0.0.1",
                database="mealcare_dev",
            )
        except (Exception, psycopg2.Error) as error:
            self.fail(error)
Пример #16
0
def connect(fname: str = None,
            create_db: bool = False,
            create_tables: bool = False) -> Database:
    db = Database()
    define_entities(db)

    environment = os.environ.get('ENV', "DEVELOPMENT")
    if environment == "DEVELOPMENT":
        fname = fname if fname is not None else "rooms.sqlite"
        db.bind("sqlite", filename=fname, create_db=create_db)
        db.generate_mapping(create_tables=create_tables)
    else:
        db.bind(provider="mysql",
                host="publicdb",
                user="******",
                password="******",
                db="rooms_db")
        db.generate_mapping(create_tables=create_tables)
    return db
Пример #17
0
    def __init__(self, bindargs, tokenizer: Tokenizer):
        """
        :param bindargs: pony bind args such as {'provider':'sqlite', 'filename':':memory:'}
        :param tokenizer: A class implementing :class:`tokenizer.Tokenizer`
        """
        self.tokenizer = tokenizer
        # set_sql_debug(True)

        db = Database()
        self.db = db

        @db.on_connect(provider="sqlite")
        def sqlite_sync_off(db, connection):
            cursor = connection.cursor()
            cursor.execute("PRAGMA synchronous = OFF")
            cursor.execute("PRAGMA cache_size = 64000")
            cursor.execute("PRAGMA journal_mode = OFF")

        class Token(db.Entity):
            tok = Required(str, unique=True)
            doc_freq = Required(int)
            documents = Set("Document")

        class Document(db.Entity):
            # url = pony.orm.core.Index(Required(str))
            url_sha = PrimaryKey(str)
            url = Required(str, unique=True)
            filename = Required(str)
            mtime = Required(int)
            content = Optional(LongStr)
            content_sha = Optional(str)
            tokens = Set("Token")
            tokfreq = Required(bytes)

        self.Token = Token
        self.Document = Document
        db.bind(**bindargs)
        db.generate_mapping(create_tables=True)
        self.update()
Пример #18
0
def create_core(args):
    schema = args.name
    config = args.config and load(args.config) or {}
    db_config = Database()
    LazyEntityMeta.attach(db_config, database='CGRdb_config')
    db_config.bind('postgres', user=args.user, password=args.password, host=args.host, database=args.base,
                   port=args.port)
    db_config.generate_mapping()

    db = Database()
    LazyEntityMeta.attach(db, schema, 'CGRdb')
    db.bind('postgres', user=args.user, password=args.password, host=args.host, database=args.base, port=args.port)
    db.generate_mapping(create_tables=True)

    with db_session:
        db.execute('CREATE EXTENSION IF NOT EXISTS smlar')
        db.execute('CREATE EXTENSION IF NOT EXISTS intarray')
        db.execute('CREATE EXTENSION IF NOT EXISTS pg_cron')

    with db_session:
        db.execute(f'CREATE INDEX idx_smlar_molecule_structure ON "{schema}"."MoleculeStructure" USING '
                   'GIST (bit_array _int4_sml_ops)')
        db.execute(f'CREATE INDEX idx_smlar_reaction_index ON "{schema}"."ReactionIndex" USING '
                   'GIST (bit_array _int4_sml_ops)')
        db.execute(f'CREATE INDEX idx_subst_molecule_structure ON "{schema}"."MoleculeStructure" USING '
                   'GIN (bit_array gin__int_ops)')
        db.execute(f'CREATE INDEX idx_subst_reaction_index ON "{schema}"."ReactionIndex" USING '
                   'GIN (bit_array gin__int_ops)')

        db.execute(f"SELECT cron.schedule('0 3 * * *', $$$$\n"
                   f'DELETE FROM "{schema}"."MoleculeSearchCache"'
                   " WHERE date < CURRENT_TIMESTAMP - INTERVAL '1 day' $$$$)")
        db.execute(f"SELECT cron.schedule('0 3 * * *', $$$$\n"
                   f'DELETE FROM "{schema}"."ReactionSearchCache"'
                   " WHERE date < CURRENT_TIMESTAMP - INTERVAL '1 day' $$$$)")

    with db_session:
        db_config.Config(name=schema, config=config, version=major_version)
Пример #19
0
def load_schema(schema, *args, **kwargs):
    """
    Load schema from db with compatible version

    :param schema: schema name for loading
    """
    major_version = '.'.join(get_distribution('CGRdb').version.split('.')[:-1])

    db_config = Database()
    LazyEntityMeta.attach(db_config, database='CGRdb_config')
    db_config.bind('postgres', *args, **kwargs)
    db_config.generate_mapping()

    with db_session:
        config = db_config.Config.get(name=schema, version=major_version)
    if not config:
        raise KeyError('schema not exists')
    config = config.config

    for p in config['packages']:
        try:
            p = get_distribution(p)
            import_module(p.project_name)
        except (DistributionNotFound, VersionConflict):
            raise ImportError(
                f'packages not installed or has invalid versions: {p}')

    db = Database()
    LazyEntityMeta.attach(db, schema, 'CGRdb')
    db.bind('postgres', *args, **kwargs)
    db.generate_mapping()

    init = f'SELECT "{schema}".cgrdb_init_session(\'{dumps(config)}\')'
    db.cgrdb_init_session = db_session()(
        lambda: db.execute(init) and True or False)
    db.cgrdb_init_session()
    return db
Пример #20
0
class Application(object):
    instance = None

    @staticmethod
    def create(token):
        if Application.instance is None:
            Application.instance = Application(token)
            Application.instance.setup_db()
        return Application.instance

    def __init__(self, token):
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)

        self.handler = Handler(token)

    def setup_db(self):
        self.db = Database()
        self.db.bind('sqlite', 'db.sqlite', create_db=True)
        self.inject_models()
        self.inject_controllers()

    def inject_controllers(self):
        from telebotty.telebotty.controller import Controller

        for cl in get_classes('controllers'):
            if cl is not Controller and issubclass(cl, Controller):
                logging.log(logging.INFO, 'Control class is loaded %s' % cl)
                cl(self)

    def inject_models(self):
        for cl in get_classes('models'):
            if cl is not self.db.Entity and issubclass(cl, self.db.Entity):
                logging.log(logging.INFO, 'Entity class is loaded %s' % cl)

        self.db.generate_mapping(create_tables=True)
Пример #21
0
# database.py
from pony.orm import Database, PrimaryKey, Required, Optional

db = Database()


class Mahasiswa(db.Entity):
    id = PrimaryKey(int, auto=True)
    nik = Optional(int)
    name = Required(str)
    address = Optional(str)
    gender_id = Optional(int)


class Gender(db.Entity):
    gender_id = Optional(int)
    name = Required(str)


# connect to mysql
db.bind('mysql', host='localhost', user='******', passwd='', db='universitas')
Пример #22
0
# from pathlib import Path
import json
import pprint
import secrets
from datetime import datetime

db = Database()


class Sessions(db.Entity):
    sessionid = PrimaryKey(str)
    datetime = Required(datetime)
    jsonstr = Optional(str)


db.bind(provider='sqlite', filename='db/SessionsLog.db', create_db=False)
db.generate_mapping(create_tables=False)


def _getdict():
    with db_session:
        jsoninfo = Sessions[sessionID]
    value = jsoninfo.jsonstr
    if value is None or value == '':
        return ''
    value = json.loads(value)
    return value


def getSession(name):
    pydict = _getdict()
Пример #23
0
class Cinema(db.Entity):
    name = Required(str)
    city = Required(CinemaCity)
    rooms = Set("CinemaRoom")
    PrimaryKey(name, city)


class CinemaRoom(db.Entity):
    name = Required(str)
    cinema = Required(Cinema)
    shows = Set("Show")
    PrimaryKey(name, cinema)


class Show(db.Entity):
    movie = Required(Movie)
    room = Required(CinemaRoom)
    date = Required(datetime.datetime)
    PrimaryKey(movie, room, date)


db.bind(provider="postgres",
        user=config.POSTGRES_USER,
        password=config.POSTGRES_PASSWORD,
        host=config.POSTGRES_HOST,
        port=config.POSTGRES_PORT,
        database=config.POSTGRES_DB)

db.generate_mapping(create_tables=True)
Пример #24
0
                                      ping_interval=None)

        await ctx.server
        for wssocket in ctx.server.ws_server.sockets:
            socketname = wssocket.getsockname()
            if wssocket.family == socket.AF_INET6:
                logging.info(
                    f'Hosting game at [{get_public_ipv6()}]:{socketname[1]}')
            elif wssocket.family == socket.AF_INET:
                logging.info(
                    f'Hosting game at {get_public_ipv4()}:{socketname[1]}')
        while ctx.running:
            await asyncio.sleep(1)
        logging.info("Shutting down")

    import asyncio
    if ".." not in sys.path:
        sys.path.append("..")
    from MultiServer import Context, server
    from Utils import get_public_ipv4, get_public_ipv6
    import socket
    asyncio.run(main())


if __name__ == "__main__":
    multiprocessing.freeze_support()
    multiprocessing.set_start_method('spawn')
    db.bind(**app.config["PONY"])
    db.generate_mapping(create_tables=True)
    app.run(debug=True)
Пример #25
0
from flask import Flask
from pony.flask import Pony
from pony.orm import Database

app = Flask(__name__)
Pony(app)

db = Database()
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)

import views

db.generate_mapping(create_tables=True)
Пример #26
0
from pony.orm import Database, Required

db = Database()
db.bind(provider="sqlite", filename="weather.db", create_db=True)


class Weather(db.Entity):
    """Погода"""
    date = Required(str)
    temperature_day = Required(str)
    temperature_night = Required(str)
    day_description = Required(str)


db.generate_mapping(create_tables=True)
Пример #27
0
import sys
from datetime import (date, datetime)
from pony.orm import (Database, Required, Optional, Set, db_session, sql_debug, show, select, commit)

db = Database()

sql_debug(True)

class Task(db.Entity):
	
	task = Required(str)
	date_created = Required(date)
	date_of_completion = Optional(date)

db.bind('sqlite', filename='Jara.sqlite',create_db=True)
db.generate_mapping(create_tables=True)


def main():
    
    actions = {
    '1': action_find_all,
    '2': action_find_by_pk,
    '3': action_find_by_created,
    '4': action_find_by_date_of_completion,
    '5': action_add_task,
    '6': action_update_task,
    '7': action_add_date_of_completion,
    '8': action_add_date_of_completion,
    'm': action_show_menu,
    'q': action_exit
Пример #28
0
#!/usr/bin/env python
# coding=utf-8
# [email protected]
from datetime import datetime
from settings import SETTINGS
from pony.orm import Database, Required, Optional, PrimaryKey

db = Database()
db.bind('sqlite', SETTINGS['sqlite_file'], create_db=True)

class User(db.Entity):
    uuid = PrimaryKey(str, 36)
    wechat_uuid = Optional(str, 36)
    is_valid = Required(int, size=8)
    created_at = Required(datetime, sql_default='CURRENT_TIMESTAMP')


db.generate_mapping(create_tables=True)
Пример #29
0
#!/usr/bin/env python
from pony.orm import Database

db = Database()

from .post import Post

db.bind('sqlite', '../db.sqlite', create_db=True)
db.generate_mapping(create_tables=True)

__all__ = ('Post',)
Пример #30
0
    @staticmethod
    def get_fear(reaction):
        return fear.get_cgr_string(cgr_core.getCGR(reaction))

    @property
    def structure(self):
        products = []
        substrats = []
        for mr in self.molecules:
            molcont = nx.relabel_nodes(mr.molecule.structure, dict(mr.mapping))
            if mr.product:
                products.append(molcont)
            else:
                substrats.append(molcont)
        return ReactionContainer(products=products, substrats=substrats)


class ReactionsMolecules(db.Entity):
    id = PrimaryKey(int, auto=True)
    molecule = Required(Molecules)
    reaction = Required(Reactions)
    product = Required(bool)
    mapping = Required(Json)


db.bind("sqlite", "datatest.db")
db.generate_mapping(create_tables=True)
sql_debug(True)

Пример #31
0
# Copyright 2021 21CN Corporation Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""

# -*- coding: utf-8 -*-

from pony.orm import Database, set_sql_debug

from config import db_user, db_password, db_host, db_port, db_name

db = Database()
db.bind(provider='postgres',
        user=db_user,
        password=db_password,
        host=db_host,
        port=db_port,
        database=db_name)
set_sql_debug(True)
Пример #32
0
    name = Required(str)
    order = Optional('Order')


class OrderItem(db.Entity):
    """Товар (одна позиция) в заказе"""
    order = Required("Order")
    product = Optional('Product')
    amount = Required(int)  # 1 единица товара


class Menu:
    """Меню"""


db.bind(provider='sqlite', filename='shop.sqlite', create_db=True)
db.generate_mapping(create_tables=True)
sql_debug(True)


@db_session
def add_product():
    product_1 = Product(title='M200 "Intervention"',
                        description='Make your self a long joy',
                        price=11850,
                        unit='1')
    product_2 = Product(title='Mossberg 500',
                        description='For close relationships',
                        price=370.34,
                        unit='1')
    product_3 = Product(title='Ammo .408 Cheyenne Tactical',
Пример #33
0
from pony.orm import Database, Required, Json, select

from Settings import DB_CONFIG

db = Database()
db.bind(**DB_CONFIG)


class UserStates(db.Entity):
    """Состояние польхователя внутри сценария"""
    user_id = Required(str, unique=True)
    scenario_name = Required(str)
    step_name = Required(str)
    context = Required(Json)


class Registration(db.Entity):
    """Заявка на регистрацию"""
    name = Required(str)
    city_from = Required(str)
    city_to = Required(str)
    date = Required(str)


db.generate_mapping(create_tables=True)
Пример #34
0
from pony.orm import Database, sql_debug

from helpers import CommandFailure
from configstartup import config

DB_FILE = config['FILES'].get('DB')

db = Database()
db.bind('sqlite', DB_FILE, create_db=True)


class Table(object):
    @classmethod
    def get_or_err(cls, err=None, **kwargs):
        obj = cls.get(**kwargs)
        if obj is None:
            raise CommandFailure(cls.err if err is None else err)
        return obj

    @classmethod
    def create_or_update(cls, **kwargs):
        old_obj = cls.get(**dict((k, kwargs[k]) for k in cls._pk_columns_))
        if old_obj is None:
            return cls(**kwargs)
        for k, v in kwargs.items():
            if k not in cls._pk_columns_:
                setattr(old_obj, k, v)
        return old_obj

    @classmethod
    def delete_or_err(cls, err=None, **kwargs):
Пример #35
0
from pony.orm import Database

db = Database()
db.bind('sqlite', 'app.db')