Exemple #1
0
    def __init__(self, db=None):
        if not db:
            db = CONFIG.get('env', {}).get('env', None)
        if db == 'root':
            self.db = CONFIG.get('db_root')
        elif db == 'test':
            self.db = CONFIG.get('db_test')
        elif db == 'analysis':
            self.db = CONFIG.get('db_analysis')
        else:
            self.db = CONFIG.get('db')
        self.redis_config = CONFIG.get('redis')

        logger.debug('db setting: ' + str(self.db))

        self.database = peewee.MySQLDatabase(self.db.get('database'),
                                             host=self.db.get('host'),
                                             port=self.db.get('port', 3306),
                                             user=self.db.get('user'),
                                             passwd=self.db.get('passwd'),
                                             charset=self.db.get('charset'))
        self.database_async = peewee_async.MySQLDatabase(
            self.db.get('database'),
            host=self.db.get('host'),
            port=self.db.get('port', 3306),
            user=self.db.get('user'),
            password=self.db.get('passwd'),
            charset=self.db.get('charset'))
        self.pool = PooledMySQLDatabase(self.db.get('database'),
                                        host=self.db.get('host'),
                                        port=self.db.get('port', 3306),
                                        user=self.db.get('user'),
                                        passwd=self.db.get('passwd'),
                                        max_connections=self.db.get(
                                            'max_connections', 10))
        self.pool_async = peewee_async.PooledMySQLDatabase(
            self.db.get('database'),
            host=self.db.get('host'),
            port=self.db.get('port', 3306),
            user=self.db.get('user'),
            password=self.db.get('passwd'),
            charset=self.db.get('charset'),
            max_connections=self.db.get('max_connections', 10))

        # redis_pool_async = aioredis.create_redis_pool(
        #     (config['redis']['host'], config['redis']['port']),
        #     minsize=config['redis']['minsize'],
        #     maxsize=config['redis']['maxsize'],
        #     loop=asyncio.get_event_loop()
        # )
        logger.debug('redis setting: ' + str(self.redis_config))
        self.redis = redis.ConnectionPool(
            host=self.redis_config['host'],
            port=self.redis_config['port'],
            password=self.redis_config['password'],
            db=self.redis_config['db'],
            max_connections=self.redis_config['maxsize'],
            decode_responses=True)
Exemple #2
0
    def __init__(self,
                 table_prefix=None,
                 use_async=True,
                 create_table=True,
                 multiplexing_conn=False):
        """
        初始化

        Parameters:
            table_prefix - 表名前缀,由扫描目标的 host + "_" + str(port) 组成
            use_async - 是否开启数据库连接的异步查询功能,默认为True
            create_table - 数据表不存在时是否创建,默认为True
            multiplexing_conn - 是否复用连接,为True时,相同的Model的实例会使用同一个连接, 为int时使用该int大小的连接池, 默认为False

        Raises:
            create_table为Fasle且目标数据表不存在时,引发exceptions.TableNotExist
        """
        self.use_async = use_async
        try:
            if multiplexing_conn:
                database = BaseModel.mul_database
            else:
                if self.use_async:
                    database = peewee_async.MySQLDatabase(**self.connect_para)
                else:
                    database = peewee.MySQLDatabase(**self.connect_para)
                database.connect()

            # table_prefix 为None则不建立数据表实例,仅用于调用基类方法
            if table_prefix is not None:
                self._model = self._create_model(database, table_prefix)
                if not self._model.table_exists():
                    if create_table:
                        try:
                            database.create_tables([self._model])
                            Logger().debug("Create table {}_{}".format(
                                table_prefix, self.__class__.__name__))
                            if self.__class__.__name__ == "NewRequestModel":
                                Communicator().update_target_list_status()
                        except peewee.InternalError:
                            pass
                    else:
                        raise exceptions.TableNotExist

            self.database = database
        except exceptions.TableNotExist as e:
            self._handle_exception(
                "Table with prefix {} not found!".format(table_prefix), e)
        except Exception as e:
            self._handle_exception("Mysql Connection Fail!", e)
Exemple #3
0
def assign_new_db():
    global database
    global database_proxy
    database = peewee_async.MySQLDatabase(database=database_conn['name'],
                                          host=database_conn['host'],
                                          user=database_conn['user'],
                                          password=database_conn['password'])
    database_proxy.initialize(database)

    UserModel.create_table(True)
    SubscribtionModel.create_table(True)
    ReportModel.create_table(True)
    ContactModel.create_table(True)
    KeyValueModel.create_table(True)
Exemple #4
0
    def __init__(self,
                 table_prefix=None,
                 use_async=True,
                 create_table=True,
                 multiplexing_conn=False):
        """
        初始化

        Parameters:
            table_prefix - 表名前缀,由扫描目标的 host + "_" + str(port) 组成
            use_async - 是否开启数据库连接的异步查询功能,默认为True
            create_table - 数据表不存在时是否创建,默认为True
            multiplexing_conn - 是否复用连接,为True时,相同的Model的实例会使用同一个连接,默认为False

        Raises:
            create_table为Fasle且目标数据表不存在时,引发exceptions.TableNotExist
        """
        self.use_async = use_async
        try:
            if multiplexing_conn:
                database = self.mul_database
            else:
                if self.use_async:
                    database = peewee_async.MySQLDatabase(**self.connect_para)
                else:
                    database = peewee.MySQLDatabase(**self.connect_para)
                database.connect()

            # table_prefix 为None则不建立数据表实例,仅用于调用基类方法
            if table_prefix is not None:
                self._model = self._create_model(database, table_prefix)
                if create_table:
                    try:
                        database.create_tables([self._model])
                    except peewee.InternalError:
                        pass
                elif not self._model.table_exists():
                    raise exceptions.TableNotExist

            self.database = database
        except exceptions.TableNotExist as e:
            raise e
        except Exception as e:
            Logger().critical("Mysql Connection Fail!", exc_info=e)
            raise exceptions.DatabaseError
Exemple #5
0
    def __new__(cls,
                table_prefix=None,
                use_async=True,
                create_table=True,
                multiplexing_conn=False):
        """
        初始化数据库连接,构造peewee model实例

        Parameters:
            table_prefix - 表名前缀,由扫描目标的 host + "_" + str(port) 组成
            use_async - 是否开启数据库连接的异步查询功能,默认为True
            create_table - 数据表不存在时是否创建,默认为True
            multiplexing_conn - 是否复用连接,为True时,相同的Model的实例会使用同一个连接,默认为False

        Raises:
            create_table为Fasle且目标数据表不存在时,引发exceptions.TableNotExist
        """
        cls.connect_para = {
            "database": Config().get_config("database.db_name"),
            "host": Config().get_config("database.host"),
            "port": Config().get_config("database.port"),
            "user": Config().get_config("database.username"),
            "password": Config().get_config("database.password")
        }

        if not hasattr(cls, "db_created"):
            conn = pymysql.connect(
                host=Config().get_config("database.host"),
                port=Config().get_config("database.port"),
                user=Config().get_config("database.username"),
                passwd=Config().get_config("database.password"))
            sql = "CREATE DATABASE IF NOT EXISTS {} default charset utf8mb4 COLLATE utf8mb4_general_ci;".format(
                Config().get_config("database.db_name"))
            cursor = conn.cursor()
            cursor._defer_warnings = True
            cursor.execute(sql)
            conn.close()
            cls.db_created = True

        if multiplexing_conn and not hasattr(cls, "mul_database"):
            cls.mul_database = peewee_async.MySQLDatabase(**cls.connect_para)
            cls.mul_database.connect()

        instance = super(BaseModel, cls).__new__(cls)
        return instance
Exemple #6
0
        }
    }
}


DATABASES = {
    "host": "127.0.0.1",
    "user": "******",
    "password": "******",
    "database": "tornado_api",
    "port": 3306
}


sync_db = peewee.MySQLDatabase(**DATABASES)
async_db = peewee_async.MySQLDatabase(**DATABASES)


# 微信开发配置
WECHAT_MCHID = '微信支付平台商户号'
WECHAT_KEY = '微信支付平台秘钥'
WECHAT_PAY_NOTIFY_URL = '微信支付异步通知url'
WECHAT_MINI_APPID = '微信小程序appid'  
WECHAT_MINI_SECRET = '微信小程序secret'
WECHAT_APP_APPID = '微信开放平台APP_appid'
WECHAT_APP_SECRET = '微信开放平台APP_secret'
# 微信企业付款相关证书
# CERT_PATH = os.path.join(BASE_DIR, 'utils/cert/apiclient_cert.pem')
# CERT_KEY_PATH = os.path.join(BASE_DIR, 'utils/cert/apiclient_key.pem')

Exemple #7
0
            LoraDevice.is_alive: 1
        }).where(LoraDevice.device_name == '3634374710300059'))
        q.execute()
        # app.objects.create(LoraDevice, device_name='3634374710300059', data=DATA)
        del DATA
        # logging.info('mqtt59保存数据')


# 全局变量

TCP_CONNECTION = {}
database = peewee_async.MySQLDatabase(
    'tornado_db', **{
        'charset': 'utf8',
        'use_unicode': True,
        'host': 'localhost',
        'port': 3306,
        'user': '******',
        'password': '******'
    })
# database.set_allow_sync(False)
# tornado 运行初始化端口 指定端口 --port == xxx
define("port", default=9004, help="run on the given port", type=int)
settings = {
    'debug': True,
    'template_path': 'templates',
    'static_path': "static",
    "xsrf_cookies": False
}
AsyncIOMainLoop().install()
app = web.Application(
Exemple #8
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module Description: 
@Time    : 2017/12/11 16:56
@Author  : fengweiqian
"""
import asyncio
import peewee
import peewee_async

database = peewee_async.MySQLDatabase('mooc',
                                      user="******",
                                      password="******",
                                      host='fengweiqian.tech',
                                      port=3306)


class UserBase(peewee.Model):
    id = peewee.IntegerField()
    name = peewee.CharField()
    nickname = peewee.CharField()
    phone = peewee.IntegerField()
    email = peewee.CharField()
    password = peewee.CharField()
    itime = peewee.TimestampField()

    class Meta:
        database = database

Exemple #9
0
# -*- coding: utf-8 -*-

"""
@author: Jim
@project: tornado_learning
@time: 2019/8/19 11:20
@desc:
"""

from __future__ import annotations

import peewee_async
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

settings = {
    "debug": True,
    "template_path": "templates",
    "secret_key": "ZGGA#Mp4yL4w5CDa",
    "jwt_expire": 7*24*3600,
    "MEDIA_ROOT": os.path.join(BASE_DIR, "media"),
}

database = peewee_async.MySQLDatabase(
    'tornado_learning', host="127.0.0.1", port=3306, user="******", password="******"
)
Exemple #10
0
import os

import peewee_async

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
settings = {
    "static_path": "/Users/zhuxuanyu/python_xuexi/tornado_luntan/media",
    "static_url_prefix": "/media/",
    "template_path": "templates",
    "secret_key": "ZGGA#Mp4yL4w5CDu",
    "jwt_expire": 7 * 24 * 3600,
    "MEDIA_ROOT": os.path.join(BASE_DIR, "media"),
    "SITE_URL": "http://127.0.0.1:8000",
    "db": {
        "host": "127.0.0.1",
        "user": "******",
        "password": "******",
        "name": "tornado_luntan",
        "port": 3306
    },
    "redis": {
        "host": "127.0.0.1"
    }
}

database = peewee_async.MySQLDatabase('tornado_luntan',
                                      host="127.0.0.1",
                                      port=3306,
                                      user="******",
                                      password="******")
Exemple #11
0
import logging

import peewee_async
import aioredis

import settings
from emailManager import EmailManager

_db = peewee_async.MySQLDatabase(database=settings.DB_NAME,
                                 host=settings.DB_HOST,
                                 port=settings.DB_PORT,
                                 user=settings.DB_USER,
                                 password=settings.DB_PASSWORD,
                                 charset=settings.DB_CHARSET)
_db.set_allow_sync(settings.ALLOW_SYNC)
_objects = peewee_async.Manager(_db)

_logger = logging.getLogger(settings.LOG_NAME)
_logger.setLevel(getattr(logging, settings.LOG_LEVEL))
_sHandle = logging.StreamHandler()
_sHandle.setLevel(getattr(logging, settings.LOG_LEVEL))
_sHandle.setFormatter(logging.Formatter(settings.LOG_FORMATTER))
_logger.addHandler(_sHandle)
if hasattr(settings, "LOG_FILE"):
    fHandle = logging.FileHandler(settings.LOG_FILE)
    fHandle.setLevel(getattr(logging, settings.LOG_LEVEL))
    fHandle.setFormatter(logging.Formatter(settings.LOG_FORMATTER))
    _logger.addHandler(fHandle)

_emailManager = EmailManager(host=settings.EMAIL_HOST,
                             port=settings.EMAIL_PORT,
Exemple #12
0
    def __new__(cls,
                table_prefix=None,
                use_async=True,
                create_table=True,
                multiplexing_conn=False):
        """
        初始化数据库连接,构造peewee model实例

        Parameters:
            table_prefix - 表名前缀,由扫描目标的 host + "_" + str(port) 组成
            use_async - 是否开启数据库连接的异步查询功能,默认为True
            create_table - 数据表不存在时是否创建,默认为True
            multiplexing_conn - 是否复用连接,为True时,相同的Model的实例会使用同一个连接,默认为False

        Raises:
            create_table为Fasle且目标数据表不存在时,引发exceptions.TableNotExist
        """
        cls.connect_para = {
            "database": Config().get_config("database.db_name"),
            "host": Config().get_config("database.host"),
            "port": Config().get_config("database.port"),
            "user": Config().get_config("database.username"),
            "password": Config().get_config("database.password")
        }

        if not hasattr(cls, "db_created"):
            conn = pymysql.connect(
                host=Config().get_config("database.host"),
                port=Config().get_config("database.port"),
                user=Config().get_config("database.username"),
                passwd=Config().get_config("database.password"))

            cursor = conn.cursor()
            cursor._defer_warnings = True

            sql = "select @@version"
            cursor.execute(sql)
            version = cursor.fetchone()
            charset = "utf8"
            try:
                if version is not None:
                    version = version[0].split(".")
                    if int(version[0]) > 5 or (int(version[0]) == 5
                                               and int(version[1]) > 5):
                        charset = "utf8mb4"
            except Exception:
                pass

            sql = "CREATE DATABASE IF NOT EXISTS {dbname} default charset {charset} COLLATE {charset}_general_ci;".format(
                dbname=Config().get_config("database.db_name"),
                charset=charset)

            cursor.execute(sql)
            cursor.close()
            conn.commit()
            conn.close()
            cls.db_created = True

        if multiplexing_conn:
            with BaseModel.mul_lock:
                if not hasattr(BaseModel, "mul_database"):
                    BaseModel.mul_database = peewee_async.MySQLDatabase(
                        **cls.connect_para)
                    BaseModel.mul_database.connect()
                    BaseModel.mul_database_timeout = time.time() + 60
                elif time.time() > BaseModel.mul_database_timeout:
                    BaseModel.mul_database.close()
                    BaseModel.mul_database = peewee_async.MySQLDatabase(
                        **cls.connect_para)
                    BaseModel.mul_database.connect()
                    BaseModel.mul_database_timeout = time.time() + 60

        instance = super(BaseModel, cls).__new__(cls)
        return instance
Exemple #13
0
from datetime import datetime

import peewee_async
import peewee

from settings import DB_NAME, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_CHARSET

_database = peewee_async.MySQLDatabase(DB_NAME, host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASSWORD,
                                       charset=DB_CHARSET)
objects = peewee_async.Manager(_database)
_database.set_allow_sync(False)


class NovelModel(peewee.Model):
    name = peewee.CharField(verbose_name="小说名称", unique=True)
    add_time = peewee.DateTimeField(verbose_name="添加时间", default=datetime.now)

    class Meta:
        database = _database
        table_name = "tb_novel"


class ChapterModel(peewee.Model):
    novel = peewee.ForeignKeyField(NovelModel, backref="chapters")
    name = peewee.CharField(verbose_name="章节名称")
    add_time = peewee.DateTimeField(verbose_name="添加时间", default=datetime.now)

    class Meta:
        database = _database
        table_name = "tb_chapter"
        constraints = [peewee.SQL("CONSTRAINT uc_novel_name UNIQUE (novel_id,name)")]
Exemple #14
0
import os

import peewee_async

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
settings = {
   
}

database = peewee_async.MySQLDatabase(
    'CMDB_dev', host="10.132.2.43", port=3306, user="******", password="******"
)

Exemple #15
0
from datetime import datetime

import peewee
import peewee_async

db = peewee.MySQLDatabase("peewee_test",
                          host="localhost",
                          port=3306,
                          user="******",
                          password="******",
                          charset="utf8")

async_db = peewee_async.MySQLDatabase("peewee_test",
                                      host="localhost",
                                      port=3306,
                                      user="******",
                                      password="******",
                                      charset="utf8")
objects = peewee_async.Manager(async_db)
async_db.set_allow_sync(False)


class Supplier(peewee.Model):
    name = peewee.CharField(max_length=100, verbose_name="名称", index=True)
    address = peewee.CharField(max_length=100, verbose_name="联系地址")
    phone = peewee.CharField(max_length=11, verbose_name="联系电话")

    class Meta:
        table_name = "tb_supplier"
        database = db
import peewee_async
import os


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

settings = {
    "appid": "2016092100558978",
    "private_key_path": os.path.join(BASE_DIR, 'apps/utils/pay/private_2048.txt'),
    "ali_pub_key_path": os.path.join(BASE_DIR, 'apps/utils/pay/alipay_key.txt'),
    "jwt_expire": 7*24*3600,
    "secret_key": "bfV4YhRg5Z6e5eMR",
    "redis": {
        "host": "127.0.0.1"
    }
}

mysql_db = peewee_async.MySQLDatabase("GameShop2", host="127.0.0.1", port=3306, user="******", password="******")
Exemple #17
0
import peewee_async

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Settings = {
    "static_path": "D:/work/RtForum/static",
    "static_url_prefix": "/static/",
    "templates": "templates",
    "jwt_expire": 7 * 24 * 3600,
    "db": {
        "host": "127.0.0.1",
        "user": "******",
        "password": "******",
        "name": "rt_forum",
        "port": "3306"
    },
    "redis": {
        "host": "127.0.0.1",
    },
    "secret_key": "E1hUMCqdqaTY3kQC",
    "MEDIA_ROOT": os.path.join(BASE_DIR, "media"),
    "SITE_URL": "http://127.0.0.1:8888",
}
MOBILE_REGEX = r"^1[358]\d{9}$|^1[48]7\d{8}$|^176\d{8}$"
ApiKey = "xxx"
DataBase = peewee_async.MySQLDatabase("rt_forum",
                                      host="127.0.0.1",
                                      user="******",
                                      password="******",
                                      port=3306)
Exemple #18
0
import asyncio
from peewee import CharField, Model
import peewee_async

database = peewee_async.MySQLDatabase('test', charset='utf8mb4')
# database = peewee_async.MySQLDatabase('test', user='******', password='******',
#                          host='127.0.0.1', port=3316, charset='utf8mb4')


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


class User(BaseModel):
    text = CharField()


User.create_table(True)
User.create(text="apple")
database.close()
Exemple #19
0
import peewee_async

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

settings = {
    'SITE_URL': "http://127.0.0.1:8082",
    'static_path': os.path.join(BASE_DIR, 'statics'),
    'MEDIA_ROOT': os.path.join(BASE_DIR, 'media'),
    'static_url_prefix': '/statics/',
    'template_path': 'templates',
    "secret_key": "ZGGA#SJHKS$S6Si",
    "jwt_expire": 7*24*3600,
    'db': {
        'host': '127.0.0.1',
        'user': '******',
        'password': '******',
        'name': 'lehuforum',
        'port': 3306
    },
    'redis': {
        'host': '127.0.0.1',
        'port': 6379
    }
}


database = peewee_async.MySQLDatabase(
    database=settings['db']['name'], host=settings['db']['host'], port=settings['db']['port'], user=settings['db']['user'],
    password=settings['db']['password']
)
import peewee
import peewee_async
from encryption_decryption import generate_keys

database = peewee_async.MySQLDatabase('octopus', user='******', password='******', host='db', port=3306)

PRIVATE_KEY, PUBLIC_KEY = generate_keys()


class WordsModel(peewee.Model):
    text_with_salt = peewee.FixedCharField(primary_key=True, max_length=255)
    enc_text = peewee.TextField()
    freq = peewee.IntegerField()

    class Meta:
        database = database
        indexes = (
            (('text_with_salt',), True),
        )


class UrlsModel(peewee.Model):
    url_with_salt = peewee.FixedCharField(unique=True, max_length=255)
    url = peewee.FixedCharField(unique=True, max_length=255)
    sentiment_analysis = peewee.FixedCharField(max_length=10)

    class Meta:
        database = database
        indexes = (
            (('url_with_salt', 'url'), True),
        )
Exemple #21
0
import os

import peewee_async

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
settings = {
    "static_path": "C:/projects/tornado_overview/chapter03/static",
    "static_url_prefix": "/static/",
    "template_path": "templates",
    "secret_key":"ZGGA#Mp4yL4w5CDu",
    "jwt_expire":7*24*3600,
    "MEDIA_ROOT": os.path.join(BASE_DIR, "media"),
    "SITE_URL":"http://127.0.0.1:8888",
    "db": {
        "host": "127.0.0.1",
        "user": "******",
        "password": "******",
        "name": "message",
        "port": 3306
    },
    "redis":{
        "host":"127.0.0.1"
    }
}

database = peewee_async.MySQLDatabase(
    'mxforum', host="127.0.0.1", port=3306, user="******", password="******"
)
Exemple #22
0
import peewee_async
import peewee as pw
from settings import DB_HOST,DB_PORT, DB_LOGIN, DB_PASSWD, DB_NAME,\
    ADMIN_LOGIN, ADMIN_PASSWD, ADMIN_EMAIL

db = peewee_async.MySQLDatabase(host=DB_HOST, port=DB_PORT,
                                user=DB_LOGIN, password=DB_PASSWD,
                                database=DB_NAME, )


class BaseMySQLModel(pw.Model):
    """A base model that will use our MySQL database"""
    class Meta:
        database = db


__all__ = [BaseMySQLModel, ]

# Connect to our database.
db.connect()

from auth.models import UserMySQL
from chat.models import RoomMySQL, MessageMySQL

# Only create the tables if they do not exist.
db.create_tables([UserMySQL, RoomMySQL, MessageMySQL, ], safe=True)

user = UserMySQL(login=ADMIN_LOGIN, password=ADMIN_PASSWD, email=ADMIN_EMAIL, is_admin=True)
user.create_user()
Exemple #23
0
    return other.make_blob()


def HEICDecode(heicBlob, _format='jpg'):
    heic = WandImage(blob=heicBlob)
    heic.format = _format
    if _format in ['jpg', 'jpeg']:
        library.MagickSetCompressionQuality(heic.wand, 100)
    return heic.make_blob()


#db = MySQLDatabase('MediaWarehouse', user='******', password='******', **{'charset': 'utf8', 'use_unicode': True})
db = peewee_async.MySQLDatabase('MediaWarehouse',
                                user='******',
                                password='******',
                                **{
                                    'charset': 'utf8',
                                    'use_unicode': True
                                })


class LongBlogField(BlobField):
    field_type = 'LONGBLOB'


class Media(Model):
    id = UUIDField(primary_key=True)
    extension = CharField()
    mainDescription = CharField(default="")
    additionalData = TextField(default=None, null=True)
    created = DateTimeField(default=datetime.datetime.now)
Exemple #24
0
import asyncio
from _datetime import datetime

from peewee import *
from peewee import Model
import peewee_async

from werkzeug.security import check_password_hash, generate_password_hash

# 数据库连接
db = peewee_async.MySQLDatabase("tornado",
                                host="127.0.0.1",
                                port=3306,
                                user="******",
                                password="******")
objects = peewee_async.Manager(db)
db.set_allow_sync(False)


# 基类
class BaseModel(Model):
    create_time = DateTimeField(default=datetime.now, verbose_name="创建时间")

    class Meta:
        database = db


class User(BaseModel):
    username = CharField(max_length=50, verbose_name="姓名", index=True)
    _password = CharField(column_name='password',
                          max_length=50,
import os

import peewee_async
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
settings = {
    "secret_key": "ZGGA#Mp4yL4w5CDu",
    "redis": {
        "host": "127.0.0.1",
        "port": 6379,
        "password": "******"
    },
    "MEDIA_ROOT": os.path.join(BASE_DIR, "media"),
    "jwt_expire": 7 * 24 * 3600,
    "SITE_URL": "http://127.0.0.1:8888",
}

database = peewee_async.MySQLDatabase(
    'xyforum', host="118.24.115.8", port=3306, user="******", password="******"
)
import sys
import asyncio

import peewee
import peewee_async

db = peewee_async.MySQLDatabase('sanic_testdb',
                                user='******',
                                password='',
                                host='127.0.0.1',
                                port=3306)


# 定义表
class Person(peewee.Model):
    name = peewee.CharField()

    class Meta:
        database = db  # 指定数据库


objects = peewee_async.Manager(db)

Person.create_table(True)


async def handler():
    await objects.create(Person, name='Bob')


loop = asyncio.get_event_loop()
Exemple #27
0
    def __new__(cls,
                table_prefix=None,
                use_async=True,
                create_table=True,
                multiplexing_conn=False):
        """
        初始化数据库连接,构造peewee model实例

        Parameters:
            table_prefix - 表名前缀,由扫描目标的 host + "_" + str(port) 组成
            use_async - 是否开启数据库连接的异步查询功能,默认为True
            create_table - 数据表不存在时是否创建,默认为True
            multiplexing_conn - 是否复用连接,为True时,相同的Model的实例会使用同一个连接,默认为False

        Raises:
            create_table为Fasle且目标数据表不存在时,引发exceptions.TableNotExist
        """
        try:
            cls.connect_para = {
                "database": Config().get_config("database.db_name"),
                "host": Config().get_config("database.host"),
                "port": Config().get_config("database.port"),
                "user": Config().get_config("database.username"),
                "password": Config().get_config("database.password"),
                "charset": "utf8mb4"
            }

            if not hasattr(cls, "db_created"):
                conn = pymysql.connect(
                    host=Config().get_config("database.host"),
                    port=Config().get_config("database.port"),
                    user=Config().get_config("database.username"),
                    passwd=Config().get_config("database.password"),
                    charset="utf8mb4")

                cursor = conn.cursor()
                cursor._defer_warnings = True

                sql = "CREATE DATABASE IF NOT EXISTS {dbname} default charset {charset} COLLATE {charset}_general_ci;".format(
                    dbname=Config().get_config("database.db_name"),
                    charset="utf8mb4")

                cursor.execute(sql)
                cursor.close()
                conn.commit()
                conn.close()
                cls.db_created = True

            if multiplexing_conn is True:
                with BaseModel.mul_lock:
                    if not hasattr(BaseModel, "mul_database"):
                        BaseModel.mul_database = peewee_async.MySQLDatabase(
                            **cls.connect_para)
                        BaseModel.mul_database.connect()
                        BaseModel.mul_database_timeout = time.time() + 60
                    elif time.time() > BaseModel.mul_database_timeout:
                        BaseModel.mul_database.close()
                        BaseModel.mul_database = peewee_async.MySQLDatabase(
                            **cls.connect_para)
                        BaseModel.mul_database.connect()
                        BaseModel.mul_database_timeout = time.time() + 60
            elif isinstance(multiplexing_conn, int):
                with BaseModel.mul_lock:
                    if not hasattr(BaseModel, "mul_database"):
                        BaseModel.mul_database = peewee_async.PooledMySQLDatabase(
                            **cls.connect_para,
                            max_connections=multiplexing_conn)
        except Exception as e:
            cls._handle_exception("Mysql Connection Fail!", e)

        instance = super(BaseModel, cls).__new__(cls)
        return instance
Exemple #28
0
# Application配置参数
settings = dict(
    template_path=os.path.join(BASE_ROOT, "templates"),
    static_path=os.path.join(BASE_ROOT, "static"),
    cookie_secret="FhLXI+BRRomtuaGRRomtuaG47hoRRomtuaG47hoI=",
    xsrf_cookies=False,
    login_url='/login',
    debug=True
)

# Redis配置参数
redis_options = dict(
    host="192.168.1.252",
    port=6379,
    password="******"
)

# 密码加密密钥
passwd_hash_key = "BRRomtuaGRRomtuaG47hoRRomtuaG47hoI+BBx2WQ="

# MySQL数据库
database = peewee_async.MySQLDatabase(
    'demo', host="127.0.0.1", port=3306, user="******", password="******"
)
async_database = Manager(database)

# 日志配置
log_path = os.path.join(os.path.dirname(__file__), "logs/log")
log_level = "debug"
Exemple #29
0
from tornado import web
import tornado.ioloop
from Note.urls import urlpattern
from Note.settings import settings
import peewee_async

if __name__ == "__main__":
    app = web.Application(urlpattern, debug=True, **settings)
    app.listen(8888)

    database = peewee_async.MySQLDatabase(**settings['db'])
    app.objects = peewee_async.Manager(database)  # 之后通过此协程的商品对数据库操作
    database.set_allow_sync(False)

    tornado.ioloop.IOLoop.current().start()
Exemple #30
0
from datetime import datetime
from peewee import *
import peewee_async

# db = MySQLDatabase('message', host="192.168.10.69", port=3306, user="******", password="******")

db = peewee_async.MySQLDatabase(
    'message',
    user='******',
    host='192.168.10.69',
    port=3306,
    password='******'
)


# Create async models manager:

objects = peewee_async.Manager(db)

# No need for sync anymore!

db.set_allow_sync(False)

class BaseModel(Model):
    add_time = DateTimeField(default=datetime.now, verbose_name="添加时间")

    class Meta:
        database = db


class Supplier(BaseModel):