def get_mysql(mysql1):
    mysql2 = eval(mysql1)
    database = PooledMySQLDatabase(database=mysql2['db'],
                                   max_connections=300,
                                   **{
                                       'host': mysql2['host'],
                                       'port': int(mysql2['port']),
                                       'user': mysql2['user'],
                                       'passwd': mysql2['pass'],
                                       'charset': 'utf8'
                                   })
    database.connect()
    database.close()
Ejemplo n.º 2
0
class Conexao(object):
    def conecta(self):
        # self.DbHost = DbHost
        # self.DbName = DbName
        # self.DbUser = DbUser
        # self.DbPassword = DbPassword
        # self.conecta = conecta
        # self.erro = erro
        # self.dbhandler = dbhandler

        # Caminho absoluto config.ini
        self.path = os.path.abspath(os.path.dirname(sys.argv[0]))
        config = configparser.ConfigParser()
        config.sections()

        # Buscando Dados config.ini
        if config.read(os.path.join(self.path, 'config.ini')):
            self.DbHost = config['DEFAULT']['DbHost']
            self.DbName = config['DEFAULT']['DbName']
            self.DbUser = config['DEFAULT']['DbUser']
            self.DbPassword = config['DEFAULT']['DbPassword']

        # Realizando a conexao com o DB
        i = 0
        try:
            self.dbhandler = PooledMySQLDatabase(self.DbName,
                                                 user=self.DbUser,
                                                 password=self.DbPassword,
                                                 host=self.DbHost)
            self.dbhandler.connect()

            print("Sucesso")
            print(i)
            i += 1
            with self.dbhandler.connection_context():
                self.prepare_database()

        except:
            self.erro = "err"

    def prepare_database(self):

        try:
            tabelas = CriarTabelas()
            tabelas.teste = "andre"
            tabelas.tabelas()

        except InternalError as err:
            print("INrter")
Ejemplo n.º 3
0
class Db(object):
    fn = peewee.fn
    JOIN_LEFT_OUTER = peewee.JOIN_LEFT_OUTER

    def __init__(self, kw):
        self.config = kw
        self.load_database()
        self.Model = self.get_model_class()

    def load_database(self):
        self.database = PooledMySQLDatabase(self.config.pop('db'),
                                            threadlocals=True,
                                            **self.config)

    def get_model_class(self):
        class BaseModel(_model):
            def __str__(self):
                r = {}
                for k in self._data.keys():
                    try:
                        r[k] = str(getattr(self, k))
                    except:
                        r[k] = simplejson.dumps(getattr(self, k))
                return str(r)

            class Meta:
                database = self.database

        return BaseModel

    def connect(self):
        self.database.connect()

    def close(self):
        try:
            self.database.close()
        except:
            pass

    @property
    def handle(self):
        return self.database
Ejemplo n.º 4
0
    def check():

        try:
            # 使用连接池
            database = PooledMySQLDatabase(database=config.rp_db['db'],
                                           max_connections=300,
                                           **{
                                               'host': config.rp_db['host'],
                                               'port':
                                               int(config.rp_db['port']),
                                               'user': config.rp_db['user'],
                                               'passwd': config.rp_db['pass'],
                                               'charset': 'utf8'
                                           })
            database.connect()
            database.close()
        except Exception as Err:
            print('***** reading_pro_db database error')
            return False
        print("***** reading_pro_db database ok")
        return True
Ejemplo n.º 5
0
from peewee import *
from playhouse.pool import PooledMySQLDatabase
from os import path
import json
from datetime import date, datetime

f = open(path.join(path.dirname(path.dirname(__file__)), 'config.json'), 'r')
config = json.load(f)
f.close()

db = PooledMySQLDatabase(
    max_connections=None,
    stale_timeout=300,  # 5 minutes.
    **config,
)
db.connect(reuse_if_open=True)


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


class Status(BaseModel):
    id = IntegerField(primary_key=True)
    card_id = CharField(18)
    target_temp = IntegerField()
    cur_temp = FloatField()
    speed = IntegerField()
    energy = FloatField()
    amount = FloatField()
Ejemplo n.º 6
0
# -*-coding:utf-8 -*-

from peewee import Model, CharField
from playhouse.pool import PooledMySQLDatabase

mysql_db = PooledMySQLDatabase("tornado_auth",
                               user='******',
                               password='******',
                               host='127.0.0.1',
                               port=3306,
                               max_connections=20,
                               stale_timeout=300)


class AuthenticationModel(Model):
    class Meta:
        database = mysql_db


class User(AuthenticationModel):
    username = CharField(unique=True, null=False)
    password = CharField(null=False)
    salt = CharField()


mysql_db.connect()
mysql_db.create_tables([
    User,
], safe=True)
Ejemplo n.º 7
0
    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    class Meta:
        table_name = 'UserTable'


class SwordFishTable(BaseModel):
    article_id = CharField(max_length=128)
    title = CharField()
    origin_url = CharField(max_length=2048)
    collected_time = DateTimeField(
        default=datetime.utcnow().astimezone(timezone(timedelta(hours=8))))

    class Meta:
        table_name = 'SwordFishTable'


ALL_TABLES = [
    CompanyTable, CategoryTable, ArticleTable, UserTable, SwordFishTable
]

if __name__ == '__main__':
    MYSQL_DB_POOL.connect()
    MYSQL_DB.connect()
Ejemplo n.º 8
0
    # check if the download was successful
    if not os.path.isfile("/download/" + dest_dir + "/" + dest_dir +
                          "_fix.csv"):
        print "ERROR: no data downloaded - there may be no data for the range"
        sys.exit()

    useful_fields = dict((k, 2) for k in column_names)

    # creates a column_info string, that is used in the sql query
    # to specify which columns should be ignored
    columns = 0

    files = sorted(glob.glob('/download/' + dest_dir + '/' +
                             '*-chunked_*.csv'))

    db.connect()
    print "Successfully connected to the MySQL database as '" + database_user + "'"

    for file in files:

        print "Opening CSV"
        with open(file, encoding="utf-8") as f:
            for line in f:
                print line
                line = line.split("\t")
                columns = len(line)
                for i in xrange(0, len(line)):
                    if ("gbif_" + line[i]) in useful_fields:
                        useful_fields["gbif_" + line[i]] = i
                break
        s = ""
Ejemplo n.º 9
0
# encoding=utf-8
from playhouse.pool import PooledMySQLDatabase


db = PooledMySQLDatabase(
    'any_time',
    max_connections=32,
    stale_timeout=300,  # 5 minutes.
    host="192.168.100.243",
    user="******",
    passwd="abcd.1234")

db.connect()