コード例 #1
0
ファイル: user.py プロジェクト: chinatian/python-orm
 def get_user_id(cls, field_name, field_value):
     db_conf, tb_shard = models.get_db_table(field_value)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (cls.__tablename__, tb_shard,)
         sql = 'SELECT `user_id` FROM `%s` WHERE `field_name`=%%s AND `field_value`=%%s' % (tb_name,)
         row = cnn.get(sql, field_name, field_value)
         return row.user_id
     finally:
         cnn.close()
コード例 #2
0
ファイル: base.py プロジェクト: chinatian/python-orm
 def get(cls, id):
     db_conf, tb_shard = get_db_table(id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (cls.__tablename__, tb_shard,)
         sql = 'SELECT * FROM `%s` WHERE `%s`=%%s' % (tb_name, cls.__pk__,)
         row = cnn.get(sql, id)
         return cls(**row)
     finally:
         cnn.close()
コード例 #3
0
 def __init__(self):
     Connection.__init__(self)
     self.url = ''
     self.type_name = ''
     self.symbols = []
     self.pattern = Template('(?<!\w)('
                             '${fullNameLower}|'
                             '${fullNameTitle}|'
                             '${symbolLower}|'
                             '${symbolUpper}|'
                             ')(?!\w)')
コード例 #4
0
 def get_friends(cls, user_id):
     """返回好友列表"""
     db_conf, tb_shard = models.get_db_table(user_id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (cls.__tablename__, tb_shard,)
         sql = 'SELECT `id`, `user_id`, `friend_id`, `created_at` FROM `%s` WHERE `user_id`=%%s' % (tb_name,)
         iter = cnn.iter(sql, user_id)
         return [cls(**row) for row in iter]
     finally:
         cnn.close()
コード例 #5
0
ファイル: base.py プロジェクト: chinatian/python-orm
 def delete(self):
     """删除当前对象"""
     cls = self.__class__
     id = getattr(self, cls.__pk__)
     db_conf, tb_shard = get_db_table(id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (cls.__tablename__, tb_shard,)
         sql = 'DELETE FROM `%s` WHERE `%s`=%%s' % (tb_name, cls.__pk__,)
         return cnn.execute(sql, id)
     finally:
         cnn.close()
コード例 #6
0
 def set_syntax_tree(self):
     Connection.set(self,
                    query_params={
                        'tablename': 'entity_syntax',
                        'fields': {
                            'entity_id': self.id,
                            'pos': pos,
                            'word': word,
                            'distance_measure_string':
                            distance_measure_string
                        }
                    })
コード例 #7
0
 def get_user_id(cls, field_name, field_value):
     db_conf, tb_shard = models.get_db_table(field_value)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (
             cls.__tablename__,
             tb_shard,
         )
         sql = 'SELECT `user_id` FROM `%s` WHERE `field_name`=%%s AND `field_value`=%%s' % (
             tb_name, )
         row = cnn.get(sql, field_name, field_value)
         return row.user_id
     finally:
         cnn.close()
コード例 #8
0
ファイル: test.py プロジェクト: arkdchst/technoatom-2020
def connection():
    connection = Connection(password='******', db_name='test')
    connection.drop_db()
    connection.connect()

    yield connection

    connection.drop_db()
コード例 #9
0
 def get(cls, id):
     db_conf, tb_shard = get_db_table(id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (
             cls.__tablename__,
             tb_shard,
         )
         sql = 'SELECT * FROM `%s` WHERE `%s`=%%s' % (
             tb_name,
             cls.__pk__,
         )
         row = cnn.get(sql, id)
         return cls(**row)
     finally:
         cnn.close()
コード例 #10
0
 def __init__(self, name, number, vendor, payment_id, balance=None):
     self.name = name
     self.number = number
     self.vendor = vendor
     self.connection = Connection()
     self.balance = balance
     self.payment_id = payment_id
コード例 #11
0
    def __init__(self, title, date, description, url, metadata={}):
        Connection.__init__(self)
        url_parts = urlparse(url)

        self.id = 0
        self.title = title
        self.date = date
        self.url = url
        self.source = url_parts.netloc
        self.metadata = metadata
        self.description = description
        # self.scrape_meta_tags(['description'])
        self.syntax_tree = {}
        # self.construct_syntax_tree()

        self.set()
コード例 #12
0
 def delete(self):
     """删除当前对象"""
     cls = self.__class__
     id = getattr(self, cls.__pk__)
     db_conf, tb_shard = get_db_table(id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (
             cls.__tablename__,
             tb_shard,
         )
         sql = 'DELETE FROM `%s` WHERE `%s`=%%s' % (
             tb_name,
             cls.__pk__,
         )
         return cnn.execute(sql, id)
     finally:
         cnn.close()
コード例 #13
0
ファイル: base.py プロジェクト: chinatian/python-orm
 def update(self):
     """修改当前对象"""
     cls = self.__class__
     id = getattr(self, cls.__pk__)
     db_conf, tb_shard = get_db_table(id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (cls.__tablename__, tb_shard,)
         attrs = self.__dict__
         sql = 'UPDATE `%s` SET %s WHERE `%s`=%%s' % (
                 tb_name,
                 ', '.join(['%s=%%s' % x for x in attrs if x != cls.__pk__]),
                 cls.__pk__,
             )
         parameters = [attrs[x] for x in attrs if x != cls.__pk__]
         parameters.append(getattr(self, cls.__pk__))
         return cnn.execute(sql, *parameters)
     finally:
         cnn.close()
コード例 #14
0
ファイル: base.py プロジェクト: chinatian/python-orm
    def insert(self):
        """插入当前对象"""
        cls = self.__class__
        if cls.__shard_field__:
            db_conf, tb_shard = get_db_table(getattr(self, cls.__shard_field__))
        else:
            print cls.__insert_counter__
            db_conf, tb_shard = get_db_table(cls.__insert_counter__)
            cls.__insert_counter__ = cls.__insert_counter__ + 1
            if cls.__insert_counter__ >= settings.DB_TABLES_LEN:
                cls.__insert_counter__ = 0
        cnn = Connection(*db_conf)
        print 'db = %s ' % db_conf[1]
        try:
            tb_name = '%s_%d' % (cls.__tablename__, tb_shard,)

            sql = "UPDATE `seq` SET `id`=LAST_INSERT_ID(`id`+%d) WHERE `tb`=%%s" % settings.DB_TABLES_LEN
            print sql % tb_name 
            id = cnn.execute(sql, tb_name)
            print 'lastid %d' % id
            setattr(self, cls.__pk__, id)
            attrs = self.__dict__
           
            sql = "INSERT INTO `%s` (%s) VALUES (%s)" % (
                    tb_name,
                    ', '.join(map(lambda x: '`%s`' % x, attrs)),
                    ', '.join(['%s' for _ in attrs]),
                )
            print sql
            parameters = [attrs[x] for x in attrs]
            cnn.execute(sql, *parameters)
			
            return getattr(self, cls.__pk__)
        finally:
            cnn.close()
コード例 #15
0
 def update(self):
     """修改当前对象"""
     cls = self.__class__
     id = getattr(self, cls.__pk__)
     db_conf, tb_shard = get_db_table(id)
     cnn = Connection(*db_conf)
     try:
         tb_name = '%s_%d' % (
             cls.__tablename__,
             tb_shard,
         )
         attrs = self.__dict__
         sql = 'UPDATE `%s` SET %s WHERE `%s`=%%s' % (
             tb_name,
             ', '.join(['%s=%%s' % x for x in attrs if x != cls.__pk__]),
             cls.__pk__,
         )
         parameters = [attrs[x] for x in attrs if x != cls.__pk__]
         parameters.append(getattr(self, cls.__pk__))
         return cnn.execute(sql, *parameters)
     finally:
         cnn.close()
コード例 #16
0
    def set_relationship(self, entity, search_text):
        for coin in self.symbols:
            # Compile regex
            regex = re.compile(
                self.pattern.substitute(
                    fullNameLower=coin.full_name.lower(),
                    fullNameTitle=coin.full_name.title(),
                    symbolLower=coin.symbol.lower(),
                    symbolUpper=coin.symbol.upper()
                ),
                re.S
            )
            # Search provided text for symbols
            result = regex.search(search_text)

            if (result):
                # set relationship between entity_id and symbol_id, if found
                Connection.set(self, query_params={
                    'tablename': 'entity_symbol_lookup',
                    'fields': {
                        'entity_id': entity.id,
                        'symbol_id': coin.symbol_id,
                    }
                })
コード例 #17
0
def main():
    conn = Connection()
    try:
        with start_transaction(conn) as tx:
            x = 1 + 1
            raise ValueError
            y = x + 2
            print("transaction 0 =", x, y)
    except ValueError:
        print("OOPS Transaction failed")

    try:
        with start_transaction(conn) as tx:
            x = 1 + 1

            y = x + 2
            print("transaction 0 =", x, y)
    except ValueError:
        print("OOPS Transaction failed")
コード例 #18
0
 def set(self):
     entity_id = Connection.set(
         self,
         query_params={
             'tablename': 'entity',
             'returning': ['entity_id'],
             'fields': {
                 'title': self.title,
                 'url': self.url,
                 'publish_date': self.date,
                 'description': self.description,
                 'meta_data': json.dumps(self.metadata),
                 'syntax_tree': json.dumps(self.syntax_tree),
                 'entity_type_id':
                 0,  # @todo make this a real entity type ID
             }
         })
     print entity_id[0]
     self.id = entity_id[0]
コード例 #19
0
    def get(self, feed_type_id):
        fields = ['feed_id', 'url', 'feed_type_id', 'symbol_type_id']
        # get all available feeds of provided type
        feeds = Connection.get(self,
                               query_params={
                                   'tablename':
                                   'feed',
                                   'fields':
                                   fields,
                                   'where_stmt': [{
                                       'key': 'feed_type_id',
                                       'value': feed_type_id
                                   }]
                               })

        # loop feeds, create a new feed class,
        # and associate with a symbol type class for use in entity processing
        for feed in feeds:
            values = dict(zip(fields, list(feed)))
            new_feed = Feed(**values)
            new_feed.symbol_type_class = self.symbol_type_class_mapping[
                new_feed.symbol_type_id]
            self.feeds.append(new_feed)
コード例 #20
0
    def insert(self):
        """插入当前对象"""
        cls = self.__class__
        if cls.__shard_field__:
            db_conf, tb_shard = get_db_table(getattr(self,
                                                     cls.__shard_field__))
        else:
            print cls.__insert_counter__
            db_conf, tb_shard = get_db_table(cls.__insert_counter__)
            cls.__insert_counter__ = cls.__insert_counter__ + 1
            if cls.__insert_counter__ >= settings.DB_TABLES_LEN:
                cls.__insert_counter__ = 0
        cnn = Connection(*db_conf)
        print 'db = %s ' % db_conf[1]
        try:
            tb_name = '%s_%d' % (
                cls.__tablename__,
                tb_shard,
            )

            sql = "UPDATE `seq` SET `id`=LAST_INSERT_ID(`id`+%d) WHERE `tb`=%%s" % settings.DB_TABLES_LEN
            print sql % tb_name
            id = cnn.execute(sql, tb_name)
            print 'lastid %d' % id
            setattr(self, cls.__pk__, id)
            attrs = self.__dict__

            sql = "INSERT INTO `%s` (%s) VALUES (%s)" % (
                tb_name,
                ', '.join(map(lambda x: '`%s`' % x, attrs)),
                ', '.join(['%s' for _ in attrs]),
            )
            print sql
            parameters = [attrs[x] for x in attrs]
            cnn.execute(sql, *parameters)

            return getattr(self, cls.__pk__)
        finally:
            cnn.close()
コード例 #21
0
    def get(self, symbol_type_id):
        fields = [
            'symbol_id',
            'symbol_type_id',
            'symbol',
            'name',
            'full_name',
            'meta',
        ]
        symbols = Connection.get(self,
                                 query_params={
                                     'tablename':
                                     'symbol',
                                     'fields':
                                     fields,
                                     'where_stmt': [{
                                         'key': 'symbol_type_id',
                                         'value': symbol_type_id
                                     }]
                                 })

        for symbol in symbols:
            values = dict(zip(fields, list(symbol)))
            self.symbols.append(Symbol(**values))
コード例 #22
0
    def __init__(self):
        Connection.__init__(self)
        exchanges = self.get_exchanges()
        for exchange in exchanges:
            source = self.request_source(exchange[2])
            symbol_exchange_rates = json.loads(source)
            for sym in symbol_exchange_rates:
                # TODO: Load correct endpoint field names by exchange
                args = {
                    'tablename':
                    'symbol',
                    'conditional':
                    'AND',
                    'where_stmt': [{
                        'key': 'symbol',
                        'value': sym['symbol'],
                        'operator': '='
                    }, {
                        'key': 'symbol_type_id',
                        'value': exchange[1],
                        'operator': '='
                    }]
                }
                exists = Connection.exists(self, args)
                # Add symbol to table if it does not exist.
                if (not exists):
                    Connection.set(self,
                                   query_params={
                                       'tablename': 'symbol',
                                       'fields': {
                                           'symbol_type_id': exchange[1],
                                           'symbol': sym['symbol'],
                                           'name': sym['id'],
                                           'meta': '',
                                           'full_name': sym['name']
                                       }
                                   })

                # Get our symbol id
                # TODO: We need to grab this symbol id from an object cache.
                # See https://trello.com/c/nivVoxpF
                symbol_id = Connection.get(self,
                                           query_params={
                                               'tablename':
                                               'symbol',
                                               'where_stmt': [{
                                                   'key':
                                                   'symbol',
                                                   'value':
                                                   sym['symbol'],
                                                   'operator':
                                                   '='
                                               }, {
                                                   'key':
                                                   'symbol_type_id',
                                                   'value':
                                                   exchange[1],
                                                   'operator':
                                                   '='
                                               }],
                                               'fields': ['symbol_id']
                                           })

                # Insert most recent exchange rate.
                if (sym['last_updated']):
                    Connection.set(
                        self,
                        query_params={
                            'tablename': 'symbol_exchange_rate_lookup',
                            'fields': {
                                'exchange_id':
                                exchange[0],
                                'symbol_id':
                                symbol_id[0][0],
                                'rate':
                                sym['price_usd'],
                                'date':
                                Connection.convert_timestamp_to_datetime(
                                    self, sym['last_updated'])
                            }
                        })
コード例 #23
0
 def __init__(self):
     SymbolType.__init__(self)
     Connection.__init__(self)
     self.get(self.symbol_type_id)
コード例 #24
0
ファイル: log.py プロジェクト: bachlee89/payment-gateways
 def __init__(self):
     self.config = Config()
     self.path = self.config.get_base_dir('var') + 'log/'
     self.time = Time()
     self.email_transport = EmailTransport()
     self.connection = Connection()
コード例 #25
0
def init_database():
    connect = Connection()
    is_db_empty = connect.create_connection(alias)
    if is_db_empty:
        insert_all_models_data()
コード例 #26
0
 def __init__(self):
     self.connection = Connection()
コード例 #27
0
 def __init__(self, connection: Connection):
     self.connection = connection.connect()
     print('Connected to database Successfully')
     self.cursor = self.connection.cursor()
コード例 #28
0
 def __init__(self):
     self.graph = Connection.get_instance().get_connection()
コード例 #29
0
ファイル: payment.py プロジェクト: bachlee89/payment-gateways
 def __init__(self, status=1):
     self.status = status
     self.connection = Connection()
コード例 #30
0
 def __init__(self):
     self.graph = Connection.get_instance().get_connection()
     self.nodes = NodeMatcher(self.graph)
     PlacesController.__instance = self
コード例 #31
0
ファイル: Main.py プロジェクト: gershomlapaix/auto_bell
def main():
    Migration(Connection(cwd)).run_migrations()
コード例 #32
0
ファイル: main.py プロジェクト: les-is-more/decorator_sample
#!/usr/local/bin/python3

import string, os
from db.connection import Connection
from db.schema import account_schema
from utils.consprint import ConsolePrinter
from utils.router import Router
Connection(':memory:').createTable(**account_schema)
kwargs_keys = [
    "name", "age", "password", "coins", "user_type", "coin_limit",
    "initial_bet", "reward"
]


# define the router decorator
class Session:
    __consoleMainOptions = ['PLAY', 'QUIT']

    def __init__(self):
        self.currMod = 'intro'

    @Router.default('home')
    def Introduction(self):
        modTitle = "MINI-CASINO"
        modDesc = "Welcome to the {}! This is an experimental game, accessed through the terminal. The game can only played with an account, so please sign up or login using account.".format(
            moduleTitle.title())
        modKeyMap = {}
        return input('Press Letter: ')

    @Router.special('register')
    def Registration(self):
コード例 #33
0
 def __init__(self):
     Connection.__init__(self)
     self.feeds = []