Ejemplo n.º 1
0
    def test_database_url(self):
        app = Flask(__name__)
        app.config['DATABASE'] = 'sqlite:///nugget.db'
        database = FlaskDB(app)
        Model = database.Model
        self.assertTrue(isinstance(Model._meta.database, SqliteDatabase))
        self.assertEqual(Model._meta.database.database, 'nugget.db')

        # If a value is specified, it trumps config value.
        database = FlaskDB(app, 'sqlite:///nuglets.db')
        Model = database.Model
        self.assertEqual(Model._meta.database.database, 'nuglets.db')
Ejemplo n.º 2
0
def database_setup(working_dir: str, app: Flask = None):
    storage.init(working_dir)
    db_path = os.path.join(working_dir, "db.sqlite")
    database.init(db_path)

    if app:
        FlaskDB(app, database)

    database.connect()
    models = [
        Job,
        Project,
        ProjectBenchmark,
        ProjectModel,
        ProjectData,
        ProjectLossProfile,
        ProjectPerfProfile,
        ProjectOptimization,
        ProjectOptimizationModifierPruning,
        ProjectOptimizationModifierQuantization,
        ProjectOptimizationModifierLRSchedule,
        ProjectOptimizationModifierTrainable,
    ]
    database.create_tables(
        models=models,
        safe=True,
    )
    for model in models:
        model.raw("PRAGMA foreign_keys=ON").execute()
    database.start()
    database.close()
Ejemplo n.º 3
0
 def test_database_url(self):
     app = Flask(__name__)
     app.config['DATABASE'] = 'sqlite:///nugget.db'
     database = FlaskDB(app)
     Model = database.Model
     self.assertTrue(isinstance(Model._meta.database, SqliteDatabase))
     self.assertEqual(Model._meta.database.database, 'nugget.db')
Ejemplo n.º 4
0
    def test_deferred_database(self):
        app = Flask(__name__)
        app.config.update({
            'DATABASE': {
                'name': ':memory:',
                'engine': 'peewee.SqliteDatabase'
            }
        })

        # Defer initialization of the database.
        database = FlaskDB()

        # Ensure we can access the Model attribute.
        Model = database.Model
        model_db = Model._meta.database

        # Because the database is not initialized, the models will point
        # to an uninitialized Proxy object.
        self.assertTrue(isinstance(model_db, Proxy))
        self.assertRaises(AttributeError, lambda: model_db.database)

        class User(database.Model):
            username = CharField(unique=True)

        # Initialize the database with our Flask app.
        database.init_app(app)

        # Ensure the `Model` property points to the same object as it
        # did before.
        PostInitModel = database.Model
        self.assertTrue(Model is PostInitModel)

        # Ensure that the proxy is initialized.
        self.assertEqual(model_db.database, ':memory:')

        # Ensure we can use our database.
        User.create_table()
        for username in ['charlie', 'huey', 'zaizee']:
            User.create(username=username)

        self.assertEqual(User.select().count(), 3)
        users = User.select().order_by(User.username)
        self.assertEqual([user.username for user in users],
                         ['charlie', 'huey', 'zaizee'])

        self.assertEqual(User._meta.database, database.database)
Ejemplo n.º 5
0
    def test_deferred_database(self):
        app = Flask(__name__)
        app.config.update({
            'DATABASE': {
                'name': ':memory:',
                'engine': 'peewee.SqliteDatabase'}})

        # Defer initialization of the database.
        database = FlaskDB()

        # Ensure we can access the Model attribute.
        Model = database.Model
        model_db = Model._meta.database

        # Because the database is not initialized, the models will point
        # to an uninitialized Proxy object.
        self.assertTrue(isinstance(model_db, Proxy))
        self.assertRaises(AttributeError, lambda: model_db.database)

        class User(database.Model):
            username = CharField(unique=True)

        # Initialize the database with our Flask app.
        database.init_app(app)

        # Ensure the `Model` property points to the same object as it
        # did before.
        PostInitModel = database.Model
        self.assertTrue(Model is PostInitModel)

        # Ensure that the proxy is initialized.
        self.assertEqual(model_db.database, ':memory:')

        # Ensure we can use our database.
        User.create_table()
        for username in ['charlie', 'huey', 'zaizee']:
            User.create(username=username)

        self.assertEqual(User.select().count(), 3)
        users = User.select().order_by(User.username)
        self.assertEqual(
            [user.username for user in users],
            ['charlie', 'huey', 'zaizee'])

        self.assertEqual(User._meta.database, database.database)
Ejemplo n.º 6
0
    def test_database(self):
        app = Flask(__name__)
        app.config.update({
            'DATABASE': {
                'name': ':memory:',
                'engine': 'peewee.SqliteDatabase'}})
        database = FlaskDB(app)

        Model = database.Model
        self.assertTrue(isinstance(Model._meta.database, SqliteDatabase))
        self.assertEqual(Model._meta.database.database, ':memory:')

        # Multiple calls reference the same object.
        self.assertTrue(database.Model is Model)
Ejemplo n.º 7
0
def create_app(config_name):
    _app = Flask(__name__)
    _app.config.from_object(config[config_name])
    _app.json_encoder = JSONEncoder
    config[config_name].init_app(_app)
    CORS(_app, supports_credentials=True)
    FlaskDB(_app, db)
    from .app1 import app1
    _app.register_blueprint(app1, url_prefix='/app1/v1')

    from .app2 import app2
    _app.register_blueprint(app2, url_prefix='/app2/v1')

    if config[config_name].swagger_config.get("template"):
        swagger = Swagger(_app, config=config[config_name].swagger_config,
                          template=config[config_name].swagger_config.get("template"))
    else:
        swagger = Swagger(_app, config=config[config_name].swagger_config)
    return _app
Ejemplo n.º 8
0
def create_app(config_name):
    app = Flask(__name__,
                static_folder="../../dist/static",
                template_folder="../../dist")
    FlaskDB(
        app, db
    )  # 解决peewee不自动关闭连接池连接,参见https://www.cnblogs.com/xueweihan/p/6698456.html
    CORS(app, supports_credentials=True)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .search import search as search_blueprint
    app.register_blueprint(search_blueprint, url_prefix='/search')

    from .login import login as login_blueprint
    app.register_blueprint(login_blueprint, url_prefix='/login')

    from .weather import weather as weather_blueprint
    app.register_blueprint(weather_blueprint, url_prefix='/weather')

    from .bookmarks import bookmarks as bookmarks_blueprint
    app.register_blueprint(bookmarks_blueprint, url_prefix='/bookmarks')

    from .console import console as console_blueprint
    app.register_blueprint(console_blueprint, url_prefix='/console')

    from .script import script as script_blueprint
    app.register_blueprint(script_blueprint, url_prefix='/script')

    from .privilege import privilege as privilege_blueprint
    app.register_blueprint(privilege_blueprint, url_prefix='/privilege')

    from .app_price_monitor import app_price_monitor as app_price_monitor_blueprint
    app.register_blueprint(app_price_monitor_blueprint, url_prefix='/app')

    from .push import push as push_blueprint
    app.register_blueprint(push_blueprint, url_prefix='/push')

    return app
Ejemplo n.º 9
0
def initialize_database(args, admin_user, admin_pw):
    '''
    Initialize ampt_manager database.

    Create initial database tables from model definitions. This is used during
    creation of new app instance/config.

    '''
    ampt_db = SqliteDatabase(app.config['DATABASE'])
    database = FlaskDB(app, ampt_db)

    # Create tables from peewee models
    for model in MODEL_LIST:
        # If told to force initialization, drop existing tables. Fail silently
        # if force option specified but no tables exist.
        if args.force:
            model.drop_table(fail_silently=True)
        model.create_table()

    # Create default admin user
    pw_hash = bcrypt.generate_password_hash(admin_pw)
    initial_user = User()
    initial_user.username=admin_user
    initial_user.display_name='Admin User'
    initial_user.password=pw_hash
    initial_user.email='root@localhost'
    initial_user.save()

    # Create local probe generator
    ProbeGenerator.create(name='Local',
                          address='localhost',
                          port=settings.probe_generator_default_port,
                          auth_key='',
                          active=False,
                          created_by=initial_user,
                          last_modified_by=initial_user)
Ejemplo n.º 10
0
# -*- coding: utf-8 -*-
from flask import Flask
from flask_cors import *
from app import create
from app.models import create_table, db
from config import *
from playhouse.flask_utils import FlaskDB

import sys
app = Flask(__name__)
FlaskDB(app, db)
# from app import novel
CORS(app, supports_credentials=True)
# app.register_blueprint(novel.app, url_prefix="/erolight")
app = create(app)
if __name__ == "__main__":
    if len(sys.argv) is not 1: create_table()

    app.run(port=WEB_PORT, host=WEB_ADDRESS, debug=True)
Ejemplo n.º 11
0
from flask import Flask, url_for
from flask_cors import CORS
from playhouse.flask_utils import FlaskDB

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config['SERVER_NAME'] = "127.0.0.1:5000"
db_wrapper = FlaskDB(app, 'sqlite:///db.sqlite')
from app.views import auth_bp, post_bp, banking_mock_bp, banking_bp
app.register_blueprint(auth_bp, url_prefix="/api/auth")
app.register_blueprint(post_bp, url_prefix="/api/posts")
app.register_blueprint(banking_mock_bp, url_prefix="/api/banking_mock")
app.register_blueprint(banking_bp, url_prefix="/api/banking")
app.secret_key = "beep"
with app.app_context():
    print(url_for('auth.register'))
Ejemplo n.º 12
0
import importlib
import logging.config

import click
from flask import Flask, jsonify
from flask.cli import with_appcontext
from werkzeug.contrib.cache import RedisCache
from playhouse.flask_utils import FlaskDB
from celery import Celery

from app import settings

db = FlaskDB()


def create_app(config_test=None):
    logging.config.dictConfig(settings.LOGGING)
    app = Flask(__name__)
    app.config.from_object(settings)

    if config_test:
        app.config.update(config_test)

    db.init_app(app)

    app.db = db

    app.cache = RedisCache(host=settings.REDIS_HOST,
                           port=settings.REDIS_PORT,
                           db=settings.REDIS_DB)
Ejemplo n.º 13
0
import os
import logging
from flask import Flask
from playhouse.flask_utils import FlaskDB
from flask_admin import Admin
from hse_arch.admin import init_admin
# from hse_arch.api import init_app

db = FlaskDB()  # Создаем обертку над БД
admin = Admin()  # Создаем обертку над админкой
# restful_api = Api()  # не уверен, что это делается здесь
# auth = Auth()  # не уверен, что это делается здесь
# peewee_api = RestAPI()  # не уверен, что это делается здесь

config = {
    "production": "config.ProductionConfig",
    "development": "config.DevelopmentConfig",
    "testing": "config.TestingConfig",
    "default": "config.Config"
}
# TODO: https://damyanon.net/post/flask-series-configuration/ - возможно, стоит использовать env переменную


def create_app(config_class):
    from hse_arch.models.category import Category
    from hse_arch.models.customer import Customer
    from hse_arch.models.order import Order, OrderItem
    from hse_arch.models.product import Product, ProductIngredient, Ingredient
    from hse_arch.models.producers import Producer
    from hse_arch.models.user import User
    app = Flask(__name__)  # Создаем экземпляр класса Flask-приложения
from flask_login import UserMixin
from peewee import *
from flask_admin.contrib.peewee import ModelView
from playhouse.flask_utils import FlaskDB
from playhouse.hybrid import hybrid_property
from playhouse.sqlite_ext import *

from digital_library.app import app, admin

db_wrapper = FlaskDB(app)
database = db_wrapper.database

# TODO: add types validation


class BaseModel(db_wrapper.Model):
    admin_view = None


# `id` field is created by peewee


class TAG(BaseModel):
    Name = TextField(unique=True)


class USER(
        BaseModel, UserMixin
):  # if a method is implemented in BaseModel then this method is used
    Email = TextField(unique=True)
    FirstName = TextField()
Ejemplo n.º 15
0
# List of supported EventMonitor types
MONITOR_TYPES = [
    ('bro', 'Bro sensor'),
    ('snort', 'Snort sensor'),
    ('suricata', 'Suricata sensor'),
]
# List of supported probe IP protocols
PROBE_PROTOCOLS = [
    ('tcp', 'TCP'),
    ('udp', 'UDP'),
]
# Support logs from event monitors that don't include IP protocol
LOG_PROBE_PROTOCOLS = PROBE_PROTOCOLS + [('unspecified', 'Unspecified')]

ampt_db = SqliteDatabase(app.config['DATABASE'])
database = FlaskDB(app, ampt_db)

class BaseModel(database.Model):
    pass

class User(BaseModel, UserMixin):
    username = CharField(max_length=75, unique=True, help_text='User name')
    display_name = CharField(max_length=75, help_text='User name')
    password = CharField(max_length=255, help_text='Password')
    email = CharField(max_length=150, unique=True, help_text='User email address')
    active = BooleanField(default=True)

    def check_password(self, password):
        'Verify supplied user password against stored hash'
        return bcrypt.check_password_hash(self.password, password)
Ejemplo n.º 16
0
def create_app(config_name):
    app = Flask(__name__,
                static_folder="../../dist/static",
                template_folder="../../dist")
    FlaskDB(
        app, db
    )  # 解决peewee不自动关闭连接池连接,参见https://www.cnblogs.com/xueweihan/p/6698456.html
    CORS(app, supports_credentials=True)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .widget import widget as widget_blueprint
    app.register_blueprint(widget_blueprint, url_prefix='/widget')

    from .cloud_drive import cloud_drive as cloud_drive_blueprint
    app.register_blueprint(cloud_drive_blueprint, url_prefix='/cloudDrive')

    from .search import search as search_blueprint
    app.register_blueprint(search_blueprint, url_prefix='/search')

    from .login import login as login_blueprint
    app.register_blueprint(login_blueprint, url_prefix='/login')

    from .weather import weather as weather_blueprint
    app.register_blueprint(weather_blueprint, url_prefix='/weather')

    from .bookmarks import bookmarks as bookmarks_blueprint
    app.register_blueprint(bookmarks_blueprint, url_prefix='/bookmarks')

    from .console import console as console_blueprint
    app.register_blueprint(console_blueprint, url_prefix='/console')

    from .script import script as script_blueprint
    app.register_blueprint(script_blueprint, url_prefix='/script')

    from .privilege import privilege as privilege_blueprint
    app.register_blueprint(privilege_blueprint, url_prefix='/privilege')

    from .app_price_monitor import app_price_monitor as app_price_monitor_blueprint
    app.register_blueprint(app_price_monitor_blueprint, url_prefix='/app')

    from .push import push as push_blueprint
    app.register_blueprint(push_blueprint, url_prefix='/push')

    from .gold_price_monitor import gold_price_monitor as gold_price_monitor_blueprint
    app.register_blueprint(gold_price_monitor_blueprint, url_prefix='/gold')

    from .notes import notes as notes_blueprint
    app.register_blueprint(notes_blueprint, url_prefix='/notes')

    from .short_url import short_url as short_url_blueprint
    app.register_blueprint(short_url_blueprint, url_prefix='/s')

    from .image_hosting import image_hosting as image_hosting_blueprint
    app.register_blueprint(image_hosting_blueprint, url_prefix='/imageHosting')

    from .translator import translator as translator_blueprint
    app.register_blueprint(translator_blueprint, url_prefix='/translator')

    from .wallpapers import wallpapers as wallpapers_blueprint
    app.register_blueprint(wallpapers_blueprint, url_prefix='/wallpapers')

    from .stock import stock as stock_blueprint
    app.register_blueprint(stock_blueprint, url_prefix='/stock')

    from .fund import fund as fund_blueprint
    app.register_blueprint(fund_blueprint, url_prefix='/fund')

    from .news import news as news_blueprint
    app.register_blueprint(news_blueprint, url_prefix='/news')

    return app
Ejemplo n.º 17
0
Archivo: app.py Proyecto: Sinity/pwrank
from flask import Flask
app = Flask(__name__)

from flask_cors import CORS
CORS(app)

from flask_jwt_extended import JWTManager
app.config['JWT_SECRET_KEY'] = 'jwt-secret-string'  # change before running
jwt = JWTManager(app)

from playhouse.flask_utils import FlaskDB
from peewee import SqliteDatabase
db = SqliteDatabase('/home/sinity/dev/pwrank/db')  # change before running
db_wrapper = FlaskDB(app, db)

from flask_restful import Api
from resource import *
api = Api(app)
api.add_resource(AuthResource, '/auth')
api.add_resource(UserResource, '/auth/user/<uuid:uid>')
api.add_resource(UserCollectionResource, '/auth/user')
api.add_resource(RankingResource, '/ranking/<uuid:uid>')
api.add_resource(RankingCollectionResource, '/ranking')
api.add_resource(CompareResource, '/compare/<uuid:ranking_uid>')
Ejemplo n.º 18
0
                      {
                          'x': [1, 2, 3],
                          'y': [2, 4, 5],
                          'type': 'bar',
                          'name': u'Montréal'
                      },
                  ],
                  'layout': {
                      'title': 'Dash Data Visualization'
                  }
              })
])

# FlaskDB is a wrapper for a peewee database that sets up pre/post-request
# hooks for managing database connections.
flask_db = FlaskDB(flask_app)

# The `database` is the actual peewee database, as opposed to flask_db which is
# the wrapper.
database = flask_db.database

# Configure micawber with the default OEmbed providers (YouTube, Flickr, etc).
# We'll use a simple in-memory cache so that multiple requests for the same
# video don't require multiple network requests.
oembed_providers = bootstrap_basic(OEmbedCache())


class Entry(flask_db.Model):
    title = CharField()
    slug = CharField(unique=True)
    content = TextField()
Ejemplo n.º 19
0
from flask_login import LoginManager
from playhouse.flask_utils import FlaskDB
from flask_bcrypt import Bcrypt

login_manager = LoginManager()
database = FlaskDB()
bcrypt = Bcrypt()
Ejemplo n.º 20
0
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   Cellcfg is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty 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 Cellcfg.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################
import importlib
from flask import Flask
from playhouse.flask_utils import FlaskDB
from .proxy import ReverseProxied
from cellconfig import conf, db

app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
app.config.update(dict(conf.items(__package__)))
database = FlaskDB(app, db)

import views
import views_admin
import api
import event

if conf.has_option(__package__, 'PLUGIN'):
    for plugin in conf.get(__package__, 'PLUGIN').split(':'):
        importlib.import_module(plugin, package=__package__)
Ejemplo n.º 21
0
app = Flask(__name__, )
env = os.environ.get("FLASK_ENV")
try:
    app.config.from_pyfile(f"config/{env}.py")
except Exception as e:
    print(f"{e.__class__.__name__}: {e}")

CORS(supports_credentials=True).init_app(app)
if app.config["DATABASE_TYPE"] == "mysql":
    database = pe.MySQLDatabase(app.config["DATABASE"],
                                **app.config["DATABASE_CONF"])
if app.config["DATABASE_TYPE"] == "sqlite":
    database = pe.SqliteDatabase(app.config["SQLITE_DB"],
                                 pragmas=app.config["SQLITE_CONF"])
db = FlaskDB(app, database)
from apps import *
from common.db.init import db_cli

app.cli.add_command(db_cli)
"""
函数模板
"""
from common.libs.UrlManager import UrlManager

app.add_template_global(UrlManager.buildStaticUrl, "buildStaticUrl")
app.add_template_global(UrlManager.buildUrl, "buildUrl")

if __name__ == "__main__":
    app.run()
Ejemplo n.º 22
0
# -*- coding: utf-8 -*-
import json
from playhouse.flask_utils import FlaskDB

dbcourse_wrapper = FlaskDB(database='mysql://*****:*****@databaseip:port/database_instance')

STATUS_VALID = 1
STATUS_INVALID = 0

class CourseBaseModel(dbcourse_wrapper.Model):

    def __str__(self):
        r = {}
        for k in self._data.keys():
            try:
                r[k] = str(getattr(self, k))
            except:
                r[k] = json.dumps(getattr(self, k))
        # return str(r)
        return json.dumps(r, ensure_ascii=False)
Ejemplo n.º 23
0
from playhouse.flask_utils import FlaskDB

flask_db = FlaskDB()
Ejemplo n.º 24
0
# -*- coding: utf-8 -*-
import datetime
import os

from marshmallow_peewee import *
from peewee import *
from playhouse.flask_utils import FlaskDB

from package.base.app import webapp

if os.environ.get('FLASK_ENV') == 'development':
    import logging
    logger = logging.getLogger('peewee')
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.DEBUG)

# 会被存入webapp.config供FlaskDB使用
DATABASE = 'postgresql://*****:*****@localhost:5432/test'

# 将当前文件的以大写字母开头的字符串存入webapp.config
webapp.config.from_object(__name__)

flask_db = FlaskDB(webapp)

database = flask_db.database
Ejemplo n.º 25
0
import datetime, functools

from flask import Flask, session, redirect, url_for, escape, request, jsonify
from peewee import *
from playhouse.flask_utils import FlaskDB

app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

database = SqliteDatabase("test.db")
db_wrap = FlaskDB(app, database=database)

class Role(db_wrap.Model):
    id = AutoField()
    name = CharField(default="ordinary_user", help_text="角色名")

    def __repr__(self):
        return "<Role: {}>".format(self.name)

class User(db_wrap.Model):
    id = AutoField()
    nickname = CharField(default="null")
    username = CharField(index=True, unique=True)
    password = CharField(help_text="密码")
    create_time = DateTimeField(
        default=datetime.datetime.now, help_text="账号创建时间")

    def to_data(self):
        return {
Ejemplo n.º 26
0
from datetime import datetime, timedelta
from threading import Lock

from peewee import DateTimeField, CharField, SmallIntegerField, IntegerField, \
    DoubleField, BooleanField, InsertQuery
from playhouse.flask_utils import FlaskDB
from playhouse.migrate import migrate, MySQLMigrator
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import RetryOperationalError

from pgpool.config import cfg_get
from pgpool.utils import cmp_bool

log = logging.getLogger(__name__)

flaskDb = FlaskDB()

request_lock = Lock()

db_schema_version = 4

webhook_queue = None

class MyRetryDB(RetryOperationalError, PooledMySQLDatabase):
    pass


# Reduction of CharField to fit max length inside 767 bytes for utf8mb4 charset
class Utf8mb4CharField(CharField):
    def __init__(self, max_length=191, *args, **kwargs):
        self.max_length = max_length
Ejemplo n.º 27
0
def peewee_setup(request, app, tmpdir, realdburl):
    from peewee import (
        TextField,
        DateTimeField,
        IntegerField,
        BooleanField,
        ForeignKeyField,
        CharField,
    )
    from playhouse.flask_utils import FlaskDB

    if realdburl:
        engine_mapper = {
            "postgres": "peewee.PostgresqlDatabase",
            "mysql": "peewee.MySQLDatabase",
        }
        db_url, db_info = _setup_realdb(realdburl)
        pieces = urlsplit(db_url)
        db_config = {
            "name": pieces.path[1:],
            "engine": engine_mapper[pieces.scheme.split("+")[0]],
            "user": pieces.username,
            "passwd": pieces.password,
            "host": pieces.hostname,
        }
    else:
        f, path = tempfile.mkstemp(prefix="flask-security-test-db",
                                   suffix=".db",
                                   dir=str(tmpdir))
        db_config = {"name": path, "engine": "peewee.SqliteDatabase"}

    app.config["DATABASE"] = db_config

    db = FlaskDB(app)

    class Role(db.Model, RoleMixin):
        name = CharField(unique=True, max_length=80)
        description = TextField(null=True)

    class User(db.Model, UserMixin):
        email = TextField()
        username = TextField()
        security_number = IntegerField(null=True)
        password = TextField(null=True)
        last_login_at = DateTimeField(null=True)
        current_login_at = DateTimeField(null=True)
        tf_primary_method = TextField(null=True)
        tf_totp_secret = TextField(null=True)
        tf_phone_number = TextField(null=True)
        us_totp_secrets = TextField(null=True)
        us_phone_number = TextField(null=True)
        last_login_ip = TextField(null=True)
        current_login_ip = TextField(null=True)
        login_count = IntegerField(null=True)
        active = BooleanField(default=True)
        confirmed_at = DateTimeField(null=True)

    class UserRoles(db.Model):
        """ Peewee does not have built-in many-to-many support, so we have to
        create this mapping class to link users to roles."""

        user = ForeignKeyField(User, backref="roles")
        role = ForeignKeyField(Role, backref="users")
        name = property(lambda self: self.role.name)
        description = property(lambda self: self.role.description)

    with app.app_context():
        for Model in (Role, User, UserRoles):
            Model.drop_table()
            Model.create_table()

    def tear_down():
        if realdburl:
            db.close_db(None)
            _teardown_realdb(db_info)
        else:
            db.close_db(None)
            os.close(f)
            os.remove(path)

    request.addfinalizer(tear_down)

    return PeeweeUserDatastore(db, User, Role, UserRoles)
Ejemplo n.º 28
0
# third-party imports
from flask import Flask
from peewee import *
from playhouse.flask_utils import FlaskDB

# db variable initialization

app = Flask(__name__)
app.config.from_object('config')
db = FlaskDB(app)
database = db.database

from app import views, models
Ejemplo n.º 29
0
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, logout_user, login_required, login_user
from playhouse.flask_utils import FlaskDB, get_object_or_404
from wtfpeewee.orm import model_form
from my_forms import *
from config import POST_PER_PAGE as ppp

application = Flask(__name__)
application.config.from_object('config')
#bootstrap = Bootstrap(application)

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = '/login'

flask_db = FlaskDB(application)
database = flask_db.database
login_manager.init_app(application)
from models import *


@application.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == 'GET':
        u = User.select().count()
        if u != 0:
            form = LoginForm()
            return render_template('login.html', form=form)
        else:
            content = 'There are no users, please create a user'
# The secret key is used internally by Flask to encrypt session data stored
# in cookies. Make this unique for your app.
SECRET_KEY = 'shhh, secret!'

# This is used by micawber, which will attempt to generate rich media
# embedded objects with maxwidth=800.
SITE_WIDTH = 800

# Create a Flask WSGI app and configure it using values from the module.
app = Flask(__name__)
app.config.from_object(__name__)

# FlaskDB is a wrapper for a peewee database that sets up pre/post-request
# hooks for managing database connections.
flask_db = FlaskDB(app)

# The `database` is the actual peewee database, as opposed to flask_db which is
# the wrapper.
database = flask_db.database

# Configure micawber with the default OEmbed providers (YouTube, Flickr, etc).
# We'll use a simple in-memory cache so that multiple requests for the same
# video don't require multiple network requests.
oembed_providers = bootstrap_basic(OEmbedCache())


class Entry(flask_db.Model):
    title = CharField()
    slug = CharField(unique=True)
    content = TextField()
Ejemplo n.º 31
0
from flask import Flask, abort, render_template, make_response, request, redirect, url_for
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
from playhouse.flask_utils import FlaskDB
from peewee import CharField, DateField
from authomatic import Authomatic
from authomatic.adapters import WerkzeugAdapter
import config

# Configure the Flask application instance.
app = Flask(__name__)
app.config["DATABASE"] = config.database
app.config["SECRET_KEY"] = config.flask_secret

# http://peewee.readthedocs.org/en/latest/peewee/playhouse.html#flask-utils
database = FlaskDB(app)

# http://flask-login.readthedocs.org/en/latest/#flask.ext.login.LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

# http://peterhudec.github.io/authomatic/reference/classes.html#authomatic.Authomatic
authomatic = Authomatic(config.authomatic_config, config.authomatic_secret)


# Super quick user model with peewee
class User(UserMixin, database.Model):
    auth_provider = CharField()
    auth_id = CharField()
    name = CharField(null=True)