示例#1
0
def init_db():
    """
    Create the database tables.
    """

    create_model_tables([Document, Document_Format, Document_Text],
                        fail_silently=True)
示例#2
0
def setup_database():
    try:
        create_model_tables(models, fail_silently=True)
    except Exception as ex:
        raise
    else:
        return db
示例#3
0
    def setUp(self):
        """ initialise temporary new database. """

        self.ctx = streetsign_server.app.test_request_context

        # streetsign_server.app.config['MODE'] = 'testing'
        models.bcrypt = MockBcrypt()
        streetsign_server.app.config["DATABASE_FILE"] = ":memory:"

        streetsign_server.app.config["TESTING"] = True

        models.DB = SqliteDatabase(None, threadlocals=True, autocommit=False)
        models.DB.init(streetsign_server.app.config["DATABASE_FILE"])

        model_list = []

        for modelname in models.__all__:
            model = getattr(models, modelname)
            try:
                model._meta.database = models.DB  # pylint: disable=protected-access
                model_list.append(model)
            except AttributeError:
                pass

        create_model_tables(model_list)
        models.DB.set_autocommit(False)

        self.client = streetsign_server.app.test_client()
示例#4
0
def set_and_drop(dbfile="tests2.db", tables=None):
    if tables is None:
        tables = [
            Indexer, IndexerNzbDownload, Search, IndexerSearch,
            IndexerApiAccess, IndexerStatus, TvIdCache, MovieIdCache,
            SearchResult
        ]
    deleteDbFile(dbfile)
    database.db = SqliteQueueDatabase(dbfile,
                                      autostart=True,
                                      results_timeout=2.0)

    models = [
        obj for name, obj in inspect.getmembers(
            tables,
            lambda obj: type(obj) == type and issubclass(obj, peewee.Model))
    ]
    peewee.create_model_tables(models)
    database.db.start()
    x = database.Indexer.select().count()
    if os.path.exists("testsettings.cfg"):
        os.remove("testsettings.cfg")
    shutil.copy("testsettings.cfg.orig", "testsettings.cfg")
    config.load("testsettings.cfg")
    # sleep(1)
    pass
示例#5
0
    def setUp(self):
        ''' initialise temporary new database. '''

        self.ctx = streetsign_server.app.test_request_context

        # streetsign_server.app.config['MODE'] = 'testing'
        models.bcrypt = MockBcrypt()
        streetsign_server.app.config['DATABASE_FILE'] = ':memory:'

        streetsign_server.app.config['TESTING'] = True

        models.DB = SqliteDatabase(None, threadlocals=True, autocommit=False)
        models.DB.init(streetsign_server.app.config['DATABASE_FILE'])

        model_list = []

        for modelname in models.__all__:
            model = getattr(models, modelname)
            try:
                model._meta.database = models.DB  # pylint: disable=protected-access
                model_list.append(model)
            except AttributeError:
                pass

        create_model_tables(model_list)
        models.DB.set_autocommit(False)

        self.client = streetsign_server.app.test_client()
示例#6
0
 def __enter__(self):
     self.orig = []
     for m in self.models:
         self.orig.append(m._meta.database)
         m._meta.database = self.db
     if self.create_tables:
         create_model_tables(self.models, fail_silently=self.fail_silently)
示例#7
0
 def __enter__(self):
     self.orig = []
     for m in self.models:
         self.orig.append(m._meta.database)
         m._meta.database = self.db
     if self.create_tables:
         create_model_tables(self.models, fail_silently=self.fail_silently)
示例#8
0
文件: main.py 项目: ak64th/IntQuiz
def init_db():
    to_create = User, QuizBook, Question, Activity, UserInfo, Run, FinalScore, Archive
    create_model_tables(models=to_create, fail_silently=True)
    # 创建测试用户
    user, created = User.get_or_create(username='******', admin=True)
    if created:
        user.set_password('123456')
        user.save()
示例#9
0
def setup_database():
    try:
        db = settings.options.database.connection
        db.connect()
        create_model_tables(models, fail_silently=True)
    except Exception as ex:
        logger.error(ex.message)
        raise
    return db
示例#10
0
文件: inst.py 项目: overview/osp
def init_db():

    """
    Create the database tables.
    """

    create_model_tables([
        Institution,
    ], fail_silently=True)
示例#11
0
def init_db():
    """
    Create the database tables.
    """

    create_model_tables([
        Text,
        Citation,
    ], fail_silently=True)
def init_db():

    """
    Create the database tables.
    """

    create_model_tables([
        Text,
        Citation,
    ], fail_silently=True)
示例#13
0
def init_db():
    """
    Create the database tables.
    """

    create_model_tables([
        Institution,
        Institution_Document,
    ],
                        fail_silently=True)
def init_db():
    """
    Create the database tables.
    """

    create_model_tables([
        Field,
        Subfield,
        Subfield_Document,
    ],
                        fail_silently=True)
示例#15
0
文件: corpus.py 项目: overview/osp
def init_db():

    """
    Create the database tables.
    """

    create_model_tables([
        Document,
        Document_Format,
        Document_Text
    ], fail_silently=True)
示例#16
0
    def setUp(self):
        for model_class in MODELS:
            model_class._meta.database = self.database

        drop_model_tables(MODELS, fail_silently=True)
        create_model_tables(MODELS)
        self.migrator = self.migrator_class(self.database)

        if 'newpages' in User._meta.reverse_rel:
            del User._meta.reverse_rel['newpages']
            delattr(User, 'newpages')
示例#17
0
文件: dates.py 项目: overview/osp
def init_db():

    """
    Create the database tables.
    """

    create_model_tables([
        Document_Date_Archive_Url,
        Document_Date_Semester,
        Document_Date_File_Metadata
    ], fail_silently=True)
def init_db():

    """
    Create the database tables.
    """

    create_model_tables([
        Field,
        Subfield,
        Subfield_Document,
    ], fail_silently=True)
示例#19
0
    def setUp(self):
        for model_class in MODELS:
            model_class._meta.database = self.database

        drop_model_tables(MODELS, fail_silently=True)
        create_model_tables(MODELS)
        self.migrator = self.migrator_class(self.database)

        if 'newpages' in User._meta.reverse_rel:
            del User._meta.reverse_rel['newpages']
            delattr(User, 'newpages')
示例#20
0
文件: hlom.py 项目: overview/osp
def init_db():

    """
    Create the database tables.
    """

    create_model_tables([
        HLOM_Record,
        HLOM_Record_Cited,
        HLOM_Citation,
        HLOM_Node,
        HLOM_Edge,
    ], fail_silently=True)
def create_tables():
    tables = []
    module = sys.modules[__name__]
    for sym in dir(module):
        attr = getattr(module, sym)
        if inspect.isclass(attr) and issubclass(attr, db.Model) and not attr.__abstract__:
            tables.append(attr)

    peewee.drop_model_tables(tables, fail_silently=True)
    peewee.create_model_tables(tables, fail_silently=True)

    try:
        from ... import migration
        version, _ = migration.migrations[-1]
    except IndexError:
        version = "000"

    Schema.create(version=version, description="Initial state.")
示例#22
0
def configure_peewee(db_name='sqlite:///:memory:',
                     db_options=None,
                     drop_before=False):

    from peewee import create_model_tables, drop_model_tables

    db_options = db_options or {}

    database = connect(db_name, **db_options)
    database_proxy.initialize(database)

    tables = [
        User, Domain, Mailbox, Mynetwork, Policy, GreylistEntry,
        GreylistMetric, WhiteList, BlackList
    ]
    if drop_before:
        drop_model_tables(tables, fail_silently=True)

    create_model_tables(tables, fail_silently=True)
示例#23
0
def configure_peewee(db_name='sqlite:///:memory:', db_options=None, drop_before=False):
    
    from peewee import create_model_tables, drop_model_tables
    
    db_options = db_options or {}

    database = connect(db_name, **db_options)
    database_proxy.initialize(database)

    tables = [User,
              Domain,
              Mailbox,
              Mynetwork,
              Policy, 
              GreylistEntry, 
              GreylistMetric, 
              WhiteList, 
              BlackList]
    if drop_before:
        drop_model_tables(tables, fail_silently=True)

    create_model_tables(tables, fail_silently=True)
示例#24
0
def main():
    create_model_tables([
        Type, Color, Size, Article, Customer, City, District, Seller, Offer,
        Order, OfferOrder
    ])

    Type(name="Pants").save()
    Type(name="Shirt").save()
    Type(name="Dress").save()
    Type(name="Jacket").save()
    Type(name="Suit").save()

    Color(name="Red").save()
    Color(name="Green").save()
    Color(name="Yellow").save()
    Color(name="Blue").save()

    Size(name="XXS").save()
    Size(name="S").save()
    Size(name="M").save()
    Size(name="L").save()
    Size(name="XL").save()
    Size(name="XXL").save()
示例#25
0
def rebuilddb(options):
    '''
    Rebuild DB
    '''
    from peewee import drop_model_tables, create_model_tables, find_subclasses
    from models import BaseModel, populate_tables
    print "Reconsruyendo la base de datos..."
    models = find_subclasses(BaseModel)
    print "Drop tables..."
    drop_model_tables(models)
    print "Cereate tables..."
    create_model_tables(models)
    CONFIG = {
            'default':[
                    dict(address='192.168.1.97', description="Placa de prueba 1 "),
                    dict(address='192.168.1.98', description="Placa de prueba 2"),
            ],
            'test':[
                dict(address='127.0.0.1', description=u"Conexión con localhost"),
            ]
        }
    print "Populating..."
    for name, list_of_comaster_cfg in CONFIG.iteritems():
        populate_tables(name, list_of_comaster_cfg)
示例#26
0
    def create_tables(self, db):
        for model in MODELS:
            model._meta.database = db

        drop_model_tables(MODELS, fail_silently=True)
        create_model_tables(MODELS)
示例#27
0
文件: app.py 项目: rahul3103/gpback
    'address': '2101 California St',
    'phone': '1111111111',
    'rating': 3,
    'listed': True,
    'status': True
}]

app.config['SECRET_KEY'] = 'top secret!'
app.config['OAUTH_CREDENTIALS'] = {
    'facebook': {
        'id': '2117634981801814',
        'secret': '1f38cd50e4671b2c82d0c827912d2cad'
    }
}

create_model_tables([User, Listing], fail_silently=True)

login_manager = LoginManager(app)
login_manager.login_view = 'index'
login_manager.login_message = 'You need to login'


@login_manager.user_loader
def load_user(id):
    return User.select().where(User.id == id).first()


@app.route('/')
def index():
    return redirect(WEB_URL)
示例#28
0
# Run this file in order to create the necessary tables
from pp.models import *
from peewee import create_model_tables
create_model_tables([User, Bill, QRCode])
示例#29
0
#!/usr/bin/env python3

from scan import scan_code, parse_code
from receipt_orm import Entry, Receipt
from settings import get_config_file
import peewee
import default
import receipt_orm

db = peewee.SqliteDatabase(get_config_file()["Basic"]["Database"])
receipt_orm.proxy.initialize(db)
db.connect()
peewee.create_model_tables([Receipt, Entry])
for i in range(2):
    q = parse_code(scan_code("/dev/video0", (640, 480)))
    if q.verify():
        print("OK")
    r = q.get(default.login, default.password)
    print(r._meta.database.database)
    r.save()
print(db.get_tables())

for i in range(2):
    print()
示例#30
0
 def setUp(self):
     drop_model_tables(MODELS, fail_silently=True)
     create_model_tables(MODELS)
     self.t1 = None
     self.t2 = None
示例#31
0
from peewee import create_model_tables

create_model_tables([ModelA, ModelB, ModelC])
示例#32
0
    id = PrimaryKeyField()
    speaker = ForeignKeyField(Speaker)
    name = CharField()
    description = CharField()
    event = ForeignKeyField(Event)
    duration = CharField()
    publish_date = CharField()

#URL,ID,URL,Speaker,Name,Short Summary,Event,Duration,Publish date



database.connect()

#    drop_model_tables([Speaker, Category, TagTalk, Tag, Talk])
create_model_tables([Speaker, Talk, Event])

seen_speakers = {}
seen_events = {}
seen_ids = set()

with database.transaction():
    with open('talks.json', 'r') as f:
        data = json.load(f)
        for elem in data:
            speaker = elem['Speaker']
            event = elem['Event']
            speaker_obj = None
            event_obj = None
            if speaker in seen_speakers:
                speaker_obj = seen_speakers[speaker]
示例#33
0
class User(BaseModel):
    id = peewee.IntegerField(primary_key=True)
    email = peewee.TextField(unique=True)
    password_hash = peewee.TextField()

    @classmethod
    def get_by_email(cls, email):
        return cls.select().where(cls.email == email).first()

    def set_password(self, password):
        self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt())

    def check_password(self, password):
        if bcrypt.checkpw(password, self.password_hash):
            return True
        return False


class Scenario(BaseModel):
    id = peewee.IntegerField(primary_key=True)
    user = peewee.ForeignKeyField(User, related_name='scenarios')
    name = peewee.CharField(max_length=30)
    status = peewee.CharField(default='new')
    created = peewee.DateTimeField()
    public = peewee.BooleanField(default=True)
    input = JSONField(default={})
    output = JSONField(default={})


peewee.create_model_tables([User, Scenario], fail_silently=True)
示例#34
0
from peewee import create_model_tables
create_model_tables([ModelA, ModelB, ModelC])
示例#35
0
# Run this file in order to create the necessary tables
from web.database import *
from peewee import create_model_tables
create_model_tables([User, Text])
示例#36
0
文件: db.py 项目: csytan/textmug
class Page(BaseModel):
    id = peewee.PrimaryKeyField()
    title = peewee.TextField()
    user = peewee.ForeignKeyField(User, null=True, related_name='pages')
    created = peewee.DateTimeField()
    text = peewee.TextField(default='')
    public = peewee.BooleanField(default=True)
    encrypted = peewee.BooleanField(default=False)

    @classmethod
    def get_by_id(cls, id):
        return cls.select().where(cls.id == id).first()

    @classmethod
    def get_recent(cls):
        return cls.select().where(cls.public == True).order_by(cls.created.desc())

    def editable(self, user):
        if not self.id or \
            (user and user.is_admin()) or \
            (user and self._data['user'] == user.id):
            return True
        return False


peewee.create_model_tables([Settings, User, Page], fail_silently=True)




示例#37
0
from app.models import Restaurant, Votes
from peewee import create_model_tables

create_model_tables([Restaurant, Votes])
示例#38
0
    def create_tables(self, db):
        for model in MODELS:
            model._meta.database = db

        drop_model_tables(MODELS, fail_silently=True)
        create_model_tables(MODELS)
示例#39
0
 def setUp(self):
     drop_model_tables(MODELS, fail_silently=True)
     create_model_tables(MODELS)
示例#40
0
def create_tables():
    peewee.create_model_tables(ALL_MODELS)
示例#41
0
def setup_db():
    create_model_tables([Users], fail_silently=True)
示例#42
0
@app.route('/a.js')
def script():
    account_id = request.args.get('id')
    if account_id:
        return Response(
            app.config['JAVASCRIPT'] % (app.config['DOMAIN'], account_id),
            mimetype='text/javascript')
    return Response('', mimetype='text/javascript')

@app.errorhandler(404)
def not_found(e):
    return Response('<h3>Not found.</h3>')

# Request handlers -- these two hooks are provided by flask and we will use them
# to create and tear down a database connection on each request.
@app.before_request
def before_request():
    g.db = database
    g.db.connect()

@app.after_request
def after_request(response):
    g.db.close()
    return response


if __name__ == '__main__':
    create_model_tables([Account, PageView], fail_silently=True)
    app.run(debug=True)
示例#43
0
__author__ = 'artemstafeev'
from app import *
from peewee import create_model_tables
create_model_tables([User])
示例#44
0
import os

import peewee

from app import create_app
from app.models import *

DB = 'twitter_lite.db'
app = create_app()

if __name__ == '__main__':
    if os.path.exists(DB):
        os.remove(DB)

    peewee.create_model_tables([User, Post, Relationship])

    with app.app_context():
        User.gen_fake()
        Post.gen_fake()
        Relationship.gen_fake()
示例#45
0
def main():
    create_model_tables([
        OrderTime, OfferTime, Article, Customer, Seller, Price, OfferFact,
        OrderFact
    ])
示例#46
0
文件: app.py 项目: ArmandoToda/peewee
    # Ensure the account id matches the domain of the URL we wish to record.
    if not account.verify_url(request.args['url']):
        abort(403)

    # Store the page-view data in the database.
    PageView.create_from_request(account, request)

    # Return a 1px gif.
    response = Response(app.config['BEACON'], mimetype='image/gif')
    response.headers['Cache-Control'] = 'private, no-cache'
    return response

@app.route('/a.js')
def script():
    account_id = request.args.get('id')
    if account_id:
        return Response(
            app.config['JAVASCRIPT'] % (app.config['DOMAIN'], account_id),
            mimetype='text/javascript')
    return Response('', mimetype='text/javascript')

@app.errorhandler(404)
def not_found(e):
    return Response('<h3>Not found.</h3>')


if __name__ == '__main__':
    create_model_tables([Account, PageView], fail_silently=True)
    app.run(debug=True)
示例#47
0
import peewee

from app.sql import Item, Item2Source, Source

peewee.drop_model_tables([Item, Source, Item2Source], fail_silently=True)
peewee.create_model_tables([Item, Source, Item2Source])
示例#48
0
    class Meta:
        db_table = 'gsfr_gist_reference'


class UserGistFavorite(BaseModel):
    user = ForeignKeyField(User)
    gist = ForeignKeyField(GistReference)

    class Meta:
        db_table = 'gsfr_user_gist_favorite'


class Rating(BaseModel):
    name = CharField(unique=True)

    class Meta:
        db_table = 'gsfr_rating'


class UserGistRating(BaseModel):
    user = ForeignKeyField(User)
    gist = ForeignKeyField(GistReference)
    rating = ForeignKeyField(Rating)

    class Meta:
        db_table = 'gsfr_user_gist_rating'


models = [User, UserRelationship, UserGithub, UserGistFavorite, UserGistRating, GistReference, Rating]
create_model_tables(models, fail_silently=True)
示例#49
0
class BaseModel(Model):
    class Meta:
        database = db

class User(BaseModel):
    username = CharField(unique=True)

class Tweet(BaseModel):
    user = ForeignKeyField(User, related_name='tweets')
    message = TextField()
    created_date = DateTimeField(default=datetime.datetime.now)
    is_published = BooleanField(default=True)

db.connect()
create_model_tables([User, Tweet])

charlie = User.create(username='******')
huey = User(username='******')
huey.save()

# No need to set `is_published` or `created_date` since they
# will just use the default values we specified.
Tweet.create(user=charlie, message='My first tweet')

# # A simple query selecting a user.
# cc = User.get(User.username == 'charles')
# print "User.get(User.username == 'charles') : " + cc

# Get tweets created by one of several users. The "<<" operator
# corresponds to the SQL "IN" operator.
示例#50
0
def create_tables(fail_silently=False):
    models = database.Model.__subclasses__()
    create_model_tables(models, fail_silently=fail_silently)
示例#51
0
        port=url.port
    )

else:
    db = PostgresqlDatabase('lastchances')

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

class CrushUser(BaseModel):
    username = CharField(primary_key=True)
    created = DateTimeField(default=datetime.datetime.now)
    updated = DateTimeField()

    def save(self, *args, **kwargs):
        self.updated = datetime.datetime.now()
        return super(CrushUser, self).save(*args, **kwargs)

class Crush(BaseModel):
    user = ForeignKeyField(CrushUser)
    crush = CharField()
    created = DateTimeField(default=datetime.datetime.now)

class Match(BaseModel):
    user_1 = ForeignKeyField(CrushUser, related_name='user_1')
    user_2 = ForeignKeyField(CrushUser, related_name='user_2')

if __name__ == '__main__':
    create_model_tables([CrushUser, Crush, Match], fail_silently=True)
示例#52
0
def init_all_tables():
    peewee.create_model_tables([Image, TagRelationship])
示例#53
0
import json
from flask import Flask, jsonify, request
from playhouse.shortcuts import model_to_dict
from flask_cors import CORS
from model import Users, Event
from peewee import create_model_tables

app = Flask(__name__)
CORS(app)

create_model_tables([Users, Event], fail_silently=True)


@app.route('/registration', methods=['POST'])
def registration():
    if request.method == 'POST':
        reg_data = json.loads(request.data)
        try:
            user = Users(**reg_data)
            user.save()
            return json.dumps({'success': True, 'user': user.id}), 200
        except:
            return json.dumps({'success': False}), 400


@app.route('/event/<int:id>', methods=['POST'])
@app.route('/event', methods=['POST'])
def event(id=0):
    if request.method == 'POST':
        eve_data = json.loads(request.data)
        if (id == 0):
示例#54
0
from flask import Flask,render_template,request
import urllib.request
from bs4 import BeautifulSoup
from model import SynsAnts
from peewee import create_model_tables

app = Flask(__name__)

create_model_tables([SynsAnts], fail_silently=True)

url = 'http://www.synonym.com/synonym/'

def get_synonym(word):
	full_url = url + word
	response = urllib.request.urlopen(full_url)
	html = response.read()
	soup = BeautifulSoup(html,'html.parser')
	synonyms_ul = soup.find('ul',{'class':'synonyms'})
	synonyms = synonyms_ul.find_all('a')
	antonyms_ul = soup.find('ul' , {'class':'antonyms'})
	antonyms = antonyms_ul.find_all('a')
	synsants = {}
	synsants['word'] = word
	synsants['synonyms'] = [str(synonym.string) for synonym in synonyms]
	synsants['antonyms'] = [str(antonym.string) for antonym in antonyms]
	return synsants 


def exists(word):
	return SynsAnts.select().where(SynsAnts.word == word).exists()	
 def create_tables(self):
     create_model_tables(*self.models)
示例#56
0
import inspect
import math
import peewee
import models
from models import IPTask

l_models = [
    obj for name, obj in inspect.getmembers(
        models, lambda obj: inspect.isclass(obj) and issubclass(obj, peewee.Model)
    )
]

peewee.create_model_tables(l_models, fail_silently=True)
with open("delegated-apnic-latest.txt", 'r') as f:
    for line in f:
        if line.startswith("#"):
            continue
        row = line.strip().split("|")
        if len(row) == 7:
            _, country, ip_type, start_ip, n, date, state = row
            if country == "CN" and ip_type == "ipv4":
                t_range = int(32-math.log(int(n),2))
                if IPTask.select().where(IPTask.start_ip==start_ip).exists():
                    IPTask.update(t_range=t_range).where(IPTask.start_ip==start_ip)
                else:
                    IPTask.create(start_ip=start_ip,
                                  t_range=t_range
                                  )
示例#57
0
 def setUpClass(cls):
     peewee.drop_model_tables([Item, Source, Item2Source],
                              fail_silently=True)
     peewee.create_model_tables([Item, Source, Item2Source])
示例#58
0
def create_tables(fail_silently=False):
    models = database.Model.__subclasses__()
    create_model_tables(models, fail_silently=fail_silently)
示例#59
0
# -*- coding: utf-8 -*-
#
# Copyright © 2015 Chaoyi Zha <*****@*****.**>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version.  This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.  You
# should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
'''
Run this file in order to create the necessary database tables
'''

from canvass.database import *
from peewee import create_model_tables
create_model_tables([Record])