def __init__(self, connection=None): self.app = None self.database = peewee.Proxy() self.connection = connection or self.default_connection self.serializer = Serializer() self.threadpool = concurrent.futures.ThreadPoolExecutor( max_workers=self.max_connections)
def load_db(): db_proxy = peewee.Proxy() if 'HEROKU' in os.environ: from six.moves.urllib.parse import urlparse, uses_netloc uses_netloc.append('postgres') url = urlparse(os.environ["DATABASE_URL"]) db_kwargs = {'database': url.path[1:], 'user': url.username, 'password': url.password, 'host': url.hostname, 'port': url.port} db = peewee.PostgresqlDatabase(**db_kwargs) else: default_pragmas = {'journal_mode': 'wal', 'foreign_keys': 1, 'ignore_check_constraints': 0} db = peewee.SqliteDatabase(conf.DB_PATH, pragmas=default_pragmas) db_proxy.initialize(db) return db, db_proxy
def test_proxy_database(self): loop = asyncio.new_event_loop() database = peewee.Proxy() TestModel._meta.database = database objects = peewee_async.Manager(database, loop=loop) @asyncio.coroutine def test(objects): text = "Test %s" % uuid.uuid4() yield from objects.create(TestModel, text=text) config = dict(defaults) for k in list(config.keys()): config[k].update(overrides.get(k, {})) database.initialize(db_classes[k](**config[k])) TestModel.create_table(True) loop.run_until_complete(test(objects)) loop.run_until_complete(objects.close()) TestModel.drop_table(True) loop.close()
def test_proxy_database(self): loop = asyncio.new_event_loop() database = peewee.Proxy() TestModel._meta.database = database objects = peewee_async.Manager(database, loop=loop) async def test(objects): text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) await objects.get(TestModel, text=text) for key in DB_CLASSES: params = DB_DEFAULTS.get(key) or {} params.update(DB_OVERRIDES.get(key) or {}) database.initialize(DB_CLASSES[key](**params)) TestModel.create_table(True) loop.run_until_complete(test(objects)) loop.run_until_complete(objects.close()) TestModel.drop_table(True) loop.close()
# coding: utf8 from __future__ import unicode_literals import peewee as orm from pathlib import Path import ujson from ..util import PRODIGY_HOME, TASK_HASH_ATTR, INPUT_HASH_ATTR, log from ..util import get_config, get_entry_points, convert_blob, get_display_name DB_PROXY = orm.Proxy() _DB = None def get_db(): """Get access to the shared database instance that was previously connected""" global _DB return _DB def set_db(instance): """Set the shared database instance. Mostly useful for testing.""" global _DB if _DB is not None: disconnect() _DB = instance def disconnect(): """Disconnect the shared database instance and revert it back to None type""" global _DB
import logging from datetime import datetime import peewee as pw from flask import Flask, request, g from flask_babel import Babel from flask_bcrypt import Bcrypt from flask_bootstrap import Bootstrap from flask_login import LoginManager, current_user from flask_mail import Mail from flask_moment import Moment from configure import configure_app db = pw.Proxy() bcrypt = Bcrypt() login_manager = LoginManager() mail = Mail() babel = Babel() moment = Moment() login_manager.login_view = 'users.login' login_manager.login_message_category = 'info' def create_app(application=None, default_settings='cajitos_site.settings'): application = Flask(__name__, instance_relative_config=True) application.config.from_object(default_settings) with application.app_context():
def __init__(self, connection=None): self.app = None self.database = peewee.Proxy() self.connection = connection or self.default_connection self.serializer = Serializer()
class Meta: primary_key = False database = peewee.Proxy() table_name = rel_table indexes = ()
# -*- coding: utf-8 -*- from __future__ import print_function import hashlib import datetime import peewee as pw database_proxy = pw.Proxy() def wrap_handler(func): def wrapped(*args, **kwargs): database_proxy.connect(reuse_if_open=True) try: return func(*args, **kwargs) except: database_proxy.close() raise return wrapped @wrap_handler def database_wrapper(next_handler, *args, **kwargs): if not next_handler: return next_handler return next_handler(*args, **kwargs) def hash_pass(login, password): return hashlib.sha512(login + password + login).hexdigest()
class Meta: primary_key = False database = peewee.Proxy() db_table = rel_table
class Meta: database = peewee.Proxy() table_name = 'migration_history'
def __init__(self, **options): """Initialize the plugin.""" super().__init__(**options) self.database = peewee.Proxy() self.models = Struct()
import logging import peewee from peewee_async import Manager logger = logging.getLogger('peewee') logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) database = peewee.Proxy() class BaseModel(peewee.Model): peewee.PostgresqlDatabase.interpolation = '%s' pee = Manager(database) data = list() error = (peewee.IntegrityError, peewee.InternalError, peewee.NotSupportedError) class Meta: database = database @classmethod async def db_get(cls, **kwargs): try: result = await cls.pee.get(cls, **kwargs) except peewee.DoesNotExist: result = None return result @classmethod async def db_create(cls, **kwargs):
def __init__(self, database=None): self.database = database proxy = pw.Proxy() CasbinRule._meta.database = proxy proxy.initialize(database)
# -*- coding: utf-8 -*- import os import sys import json import logging import six import peewee from playhouse import db_url import habibi.exc DB_PROXY = peewee.Proxy() LOG = logging.getLogger(__name__) def connect_to_db(url): """Connect to DB specified in url, create tables for all habibi models. :type url: str :param url: Database url connection string. :return: database` object :return type: peewee.Database """ database = db_url.connect(url) database.register_fields({'json': 'json'}) DB_PROXY.initialize(database) for model in SCALR_ENTITIES:
import peewee cwe_db_proxy = peewee.Proxy() class VULNERABILITIES_CWE(peewee.Model): class Meta: database = cwe_db_proxy ordering = ("cwe_id", ) table_name = "vulnerabilities_cwe" id = peewee.PrimaryKeyField(null=False, ) cwe_id = peewee.TextField(default="", ) name = peewee.TextField(default="", ) status = peewee.TextField(default="", ) weaknesses = peewee.TextField(default="", ) description_summary = peewee.TextField(default="", ) def __unicode__(self): return "vulnerabilities_cwe" def __str__(self): return str(self.cwe_id) @property def to_json(self): return dict( id=self.id, cwe_id=self.cwe_id, name=self.name, status=self.status,
# -*- coding: utf-8 -*- """Database objects. The application needs to setup some path and select configurtion dependent databases. For example initialization of data_db depends on existing profile db and active profile object. So we use a proxies to deffer init to a later runtime state. See models.__init__.py for initialization functions. """ import peewee profile_db = peewee.Proxy() data_db = peewee.Proxy()
class Meta: database = peewee.Proxy()
class Meta: database = peewee.Proxy() db_table = 'migration_history'
import peewee dbp = peewee.Proxy() class BaseModel(peewee.Model): class Meta: database = dbp class UserTable(BaseModel): date = peewee.CharField() t_day = peewee.CharField() t_night = peewee.CharField() desc = peewee.CharField()
#coding=utf8 from datetime import datetime import peewee from utils import dbpath proxy_db = peewee.Proxy() def init_close_db(old_func): def new_func(*args, **kwargs): # the db file can't be accessed by others #db = peewee.SqliteDatabase(dbpath, check_same_thread=True) #db = peewee.SqliteDatabase(dbpath, check_same_thread=False) #db = peewee.SqliteDatabase(dbpath, threadlocals=False) # OK, together with this proxy db = peewee.SqliteDatabase(dbpath, threadlocals=True) proxy_db.initialize(db) r = old_func(*args, **kwargs) proxy_db.initialize(None) return r return new_func class XmlItem(object): def __init__(self, name): self.name = name.strip() self.score = 0 self.create_time = datetime.now() self.access_time = datetime.now()
def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app)
class Meta: database = peewee.Proxy() primary_key = False indexes = () constraints = [] table_name = name
For more on the peewee model API see: https://peewee.readthedocs.io/en/latest/peewee/models.html """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import peewee as pw # The databaseProxy is used to dynamically changed the # backing database and needs to be set to an actual # database instance to use these models. databaseProxy = pw.Proxy() class SqliteDatabase(pw.SqliteDatabase): def __init__(self, *_, **__): super(SqliteDatabase, self).__init__(*_, **__) class UnknownField(object): def __init__(self, *_, **__): pass class BaseModel(pw.Model): attributes = pw.TextField(null=True)
""" This module provides the app's data store using Peewee with SQLite. At the bottom there is a simple schema migration system. """ import json from datetime import datetime import peewee as pw from playhouse import signals from vorta.utils import slugify DB = pw.Proxy() class JSONField(pw.TextField): """ Class to "fake" a JSON field with a text field. Not efficient but works nicely. From: https://gist.github.com/rosscdh/f4f26758b0228f475b132c688f15af2b """ def db_value(self, value): """Convert the python value for storage in the database.""" return value if value is None else json.dumps(value) def python_value(self, value): """Convert the database value to a pythonic value.""" return value if value is None else json.loads(value)
# # 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. """Low-level database primitives. Moved here to prevent bleeding db-specific stuff into the higher-level interface.""" import datetime import enum import hotline.chatroom import peewee db = peewee.Proxy() class BaseModel(peewee.Model): class Meta: database = db class SerializableField(peewee.TextField): def __init__(self, cls, *args, **kwargs): self._cls = cls super().__init__(*args, **kwargs) def db_value(self, value): return value.serialize()
import peewee proxy = peewee.Proxy() class Metadatos(peewee.Model): class Meta: database = proxy indexes = ((('catalogo_id', 'dataset_id', 'distribucion_id', 'serie_id'), True), ) catalogo_id = peewee.CharField(max_length=64) dataset_id = peewee.CharField(max_length=128) distribucion_id = peewee.CharField(max_length=128) serie_id = peewee.CharField(max_length=128, primary_key=True) indice_tiempo_frecuencia = peewee.CharField(max_length=8) serie_titulo = peewee.TextField() serie_unidades = peewee.TextField() serie_descripcion = peewee.TextField() distribucion_titulo = peewee.TextField() distribucion_descripcion = peewee.TextField() distribucion_url_descarga = peewee.TextField() dataset_responsable = peewee.TextField() dataset_fuente = peewee.TextField() dataset_titulo = peewee.TextField() dataset_descripcion = peewee.TextField() dataset_tema = peewee.TextField()
import peewee as pw import datetime as dt import marshmallow as ma proxy = pw.Proxy() class Role(pw.Model): name = pw.CharField(255, default='user') class Meta: database = proxy class User(pw.Model): created = pw.DateTimeField(default=dt.datetime.now) name = pw.CharField(255) title = pw.CharField(127, null=True) active = pw.BooleanField(default=True) rating = pw.IntegerField(default=0) role = pw.ForeignKeyField(Role) class Meta: database = proxy def test_base(db): assert db
"""Wrapper module for a database.""" from __future__ import print_function from datetime import datetime import json import peewee from beerlog import errors from beerlog import constants database_proxy = peewee.Proxy() # pylint: disable=no-init class BeerModel(peewee.Model): """Model for the database.""" class Meta(): """Sets Metadata for the database.""" database = database_proxy def BeerPerCharacter(character, amount): """Helper function to generate the SQL expression for the total amount of beer drunk.""" return peewee.Expression(character.glass, '*', amount) class Character(BeerModel): """class for one Character in the BeerLog database."""
database = database db_table = 'meetups_speaker' def full_name(self): return '{} {}'.format(self.first_name, self.last_name) class Sponsor(peewee.Model): logo = peewee.CharField() class Meta: database = database db_table = 'meetups_sponsor' DeferredMeetupSponsor = peewee.Proxy() class Meetup(peewee.Model): number = peewee.IntegerField() date = peewee.DateTimeField() is_ready = peewee.BooleanField() sponsors = ManyToManyField(Sponsor, through_model=DeferredMeetupSponsor) class Meta: database = database db_table = 'meetups_meetup' def title(self): return 'PyWaw #{}'.format(self.number)