コード例 #1
0
 def initdb(drop):
     if drop:
         click.confirm('确认要删除原来的数据库吗?', abort=True)
         db.drop_all()
         click.echo('Dropped tables.')
     db.create_all()
     click.echo('Initialized database.')
コード例 #2
0
ファイル: app.py プロジェクト: iiclear/clearblog
    def init(username, password):
        click.echo('Initializing the database...')
        db.create_all()

        admin = Admin.query.first()
        if admin is not None:
            click.echo('The administrator already exists, updating...')
            admin.username = username
            admin.set_password(password)
        else:
            click.echo('Creating the temporary administrator account...')
            admin = Admin(username=username,
                          blog_title='Bluelog',
                          blog_sub_title="No, I'm the real thing.",
                          name='Admin',
                          about='Anything about you.')
            admin.set_password(password)
            db.session.add(admin)

        category = Category.query.first()
        if category is None:
            click.echo('Creating the default category...')
            category = Category(name='Default')
            db.session.add(category)

        db.session.commit()
        click.echo('Done.')
コード例 #3
0
ファイル: app.py プロジェクト: huangantai/flask_templates
    def init(username, password):
        print('Initializing the database...')
        db.create_all()

        admin = Admin.query.first()
        if admin is not None:
            print('The administrator already exists, updating...')
            admin.username = username
            admin.set_password(password)
        else:
            print('Creating the temporary administrator account...')
            admin = Admin(username='******',
                          blog_title="Flaskblog",
                          blog_sub_title="No,I am the real thing",
                          name="Miro",
                          about="I am a fun guy....")
            admin.set_password(password)
            db.session.add(admin)

        category = Category.query.first()
        if category is None:
            print('Creating the default category...')
            category = Category(name='Default')
            db.session.add(category)

        db.session.commit()
        print('Done.')
コード例 #4
0
def before_first_request():

    # Create any database tables that don't exist yet.
    db.create_all()

    # Create the Roles "admin" and "end-user" -- unless they already exist
    user_datastore.find_or_create_role(name='admin', description='Administrator')
    user_datastore.find_or_create_role(name='end-user', description='End user')

    # Create two Users for testing purposes -- unless they already exists.
    # In each case, use Flask-Security utility function to encrypt the password.
    encrypted_password = utils.encrypt_password(private.STARTING_ADMIN_PASS)
    if not user_datastore.get_user(private.STARTING_ADMIN1):
        user_datastore.create_user(email=private.STARTING_ADMIN1, password=encrypted_password)
    if not user_datastore.get_user(private.STARTING_ADMIN2):
        user_datastore.create_user(email=private.STARTING_ADMIN2, password=encrypted_password)
        

    # Commit any database changes; the User and Roles must exist before we can add a Role to the User
    db.session.commit()

    # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the
    # Users already have these Roles.) Again, commit any database changes.
    user_datastore.add_role_to_user(private.STARTING_ADMIN1, 'admin')
    confirmed_admin = user_datastore.get_user(private.STARTING_ADMIN1)
    confirmed_admin.confirmed_at = datetime.datetime.utcnow()

    user_datastore.add_role_to_user(private.STARTING_ADMIN2, 'admin')
    confirmed_admin = user_datastore.get_user(private.STARTING_ADMIN2)
    confirmed_admin.confirmed_at = datetime.datetime.utcnow()

    db.session.commit()
コード例 #5
0
ファイル: app.py プロジェクト: Julio92-C/Portfolio_site
def create_app():
    app = Flask(__name__)

    app.config['SECRET_KEY'] = '11eeo9_rCa0a@a#roCr/'

    ENV = 'prod'

    if ENV == 'dev':
        app.debug = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/portfolio'

    else:
        app.debug = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@ec2-3-228-114-251.compute-1.amazonaws.com:5432/d9f0l50lh8a8ai'

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    extensions.bootstrap.init_app(app)

    app.register_blueprint(main)

    db.init_app(app)

    with app.app_context():
        db.create_all()

    return app
コード例 #6
0
def register_extensions(db, app):
    """Register Flask extensions."""
    db.init_app(app)

    with app.app_context():
        db.create_all()
    return None
コード例 #7
0
ファイル: app.py プロジェクト: huangantai/flask_templates
 def initdb(drop):
     if drop:
         db.drop_all()
         print('Drop tables')
     db.create_all()
     Role.init_role()
     print('Initialized database')
コード例 #8
0
def create_app():
    app = Flask(__name__)

    if app.config["ENV"] == "development":
        app.config.from_object("config.DevelopmentConfig")
    else:
        app.config.from_object("config.ProductionConfig")

    app.register_blueprint(json_return)
    app.register_blueprint(main_page)
    app.register_blueprint(account_page)
    app.register_blueprint(register_login_page)
    app.register_blueprint(general_page)
    app.register_blueprint(about_page)
    app.register_blueprint(experience_page)
    app.register_blueprint(education_page)
    app.register_blueprint(skills_page)
    app.register_blueprint(project_page)

    from extensions import db, login_manager, cors, migrate

    db.init_app(app)
    login_manager.init_app(app)
    cors.init_app(app)
    migrate.init_app(app, db)

    @login_manager.user_loader
    def load_user(user_id):
        return General.query.get(int(user_id))

    with app.app_context():
        db.create_all()

    return app
コード例 #9
0
ファイル: app.py プロジェクト: tsheasha/spatial-search
def create_app(settings_overrides=None):
    app = Flask(__name__)

    # Using Cross-origin resource sharing to allow
    # the ajax call from another domain since
    # SimpleHTTPServer runs on port 8000 and this
    # application runs on port 5000
    cors = CORS(app)
    app.config['CORS_HEADERS'] = 'Content-Type'

    configure_settings(app, settings_overrides)

    # Initialise database
    db.init_app(app)

    configure_blueprints(app)

    with app.app_context():
        db.create_all()
        # Initialising the data in the database
        # this should not be needed in a real system
        # since the data would be fed in as a result or
        # real events taking place.
        # However for the sake of this task we need data to work with
        # so will keeo this here.
        if not Shop.query.count():
            load_shops('shops.csv')
        if not Product.query.count():
            load_products('products.csv')
        if not Tag.query.count():
            load_tags('tags.csv')
        if not Tagging.query.count():
            load_taggings('taggings.csv')
    return app
コード例 #10
0
def register_extensions(app_obj):
    app_obj.app_context().push()
    app_obj.register_blueprint(home_controller, url_prefix="/")
    app_obj.register_blueprint(user_controller, url_prefix="/api/users")
    app_obj.register_blueprint(project_controller, url_prefix="/api/projects")
    db.init_app(app_obj)
    db.create_all()
コード例 #11
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    # Create modules
    app.register_blueprint(indexModule)
    app.register_blueprint(themeModule)
    app.register_blueprint(groupModule)
    app.register_blueprint(relationModule)
    app.register_blueprint(constructionModule)
    app.register_blueprint(adminModule)
    app.register_blueprint(mymapModule)

    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    # Create database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    return app
コード例 #12
0
ファイル: app.py プロジェクト: feltnerm/busby
def configure_extensions(app):

    from extensions import cache, db, mail, Login 

    # initialize mail
    mail = mail.init_app(app)

    # initialize cache
    cache = cache.init_app(app)

    # initialize database
    db.init_app(app)
    app.logger.info("Database initialized.")
    db.app = app
    db.metadata.bind = db.get_engine(app)
    db.metadata.reflect()
    app.logger.info("Database tables reflected.")
    from models import User
    db.create_all(bind=['users'])

    # login
    Login.manager.setup_app(app)
    @Login.manager.user_loader
    def load_user(userid):
        return User.query.get(userid)

    @Login.manager.token_loader
    def load_token(token):
        return User.query.filter(User.passkey == token).first()
コード例 #13
0
 def setUp(self) -> None:
     self.app = create_app('test')
     self.app.app_context().push()
     db.drop_all()
     db.create_all()
     self.book1 = {'book_id': 1,
                   "name": 'The Overstory',
                   'author': 'Richard Powers',
                   'year_of_publication': 2018,
                   'edition': '1st',
                   'translator': None
                   }
     self.book2 = {'book_id': 2,
                   'name': 'Test-Driven Development with Python',
                   'author': 'Percival Harry J.W.',
                   'year_of_publication': 2014,
                   'edition': '2nd',
                   'translator': None
                   }
     self.user1 = {'user_id': 1,
                   'name': 'John Smith',
                   'email': '*****@*****.**',
                   }
     self.user2 = {'user_id': 2,
                   'name': 'Jane Doe',
                   'email': '*****@*****.**'
                   }
     db.session.add(Users(**self.user1))
     db.session.add(Users(**self.user2))
     db.session.commit()
コード例 #14
0
ファイル: __init__.py プロジェクト: yonglinZ/gisflask
    def init(username, password):
        """Building project, just for you."""

        click.echo('Initializing the database...')
        db.create_all()

        admin = Admin.query.first()
        if admin is not None:
            click.echo('The administrator already exists, updating...')
            admin.username = username
            admin.set_password(password)
        else:
            click.echo('Creating the temporary administrator account...')
            admin = Admin(username=username, name='Admin')
            admin.set_password(password)
            db.session.add(admin)

        # project = Project.query.first()
        # if project is None:
        #     click.echo('Creating the default project...')
        #     project = Project(name='Default',uid="111",manager_id="1")
        #     db.session.add(project)

        db.session.commit()
        click.echo('Done.')
コード例 #15
0
ファイル: main.py プロジェクト: MyHardWay/Otus_Homework
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    register_extensions(app)
    add_blueprints(app)
    db.create_all()
    return app
コード例 #16
0
ファイル: app.py プロジェクト: LuizGsa21/blogger-backend
def configure_extensions(app):
    """ Configure app extension. """
    # flask SQLAlchemy
    db.init_app(app)
    db.create_all(app=app)

    # CSRF Protection
    csrf.init_app(app)

    @csrf.error_handler
    def csrf_error(reason):
        raise CsrfTokenError()

    # mail.init_app(app)

    # flask OAuthlib
    oauth.init_app(app)

    # Login Manger
    login_manager.init_app(app)

    #  Interface for anonymous users
    class AnonymousUserMixin(_AnonymousUserMixin):
        username = '******'
        firstName = ''
        lastName = ''
        email = ''
        role = Role.GUEST
        is_admin = False

    login_manager.login_view = 'auth.post_login'
    login_manager.session_protection = "strong"
    login_manager.anonymous_user = AnonymousUserMixin
コード例 #17
0
 def initdb(drop):
     if drop:
         click.confirm("This operation will delete the database, continue?",
                       abort=True)
         db.drop_all()
         click.echo('Drop tables.')
     db.create_all()
     click.echo("Initialized database.")
コード例 #18
0
def configure_extensions(app):
    """This function configures all extensions used in app."""

    db.init_app(app)

    with app.app_context():
        db.create_all()
        db.session.commit()
コード例 #19
0
 def __init__(self):
     app = create_app(config_object=ProdConfig)
     app_context = app.app_context()
     app_context.push()
     db.drop_all()  # drop all tables
     db.create_all()  # create a new schema
     with open('default.json') as file:
         self.default_data = json.load(file)
コード例 #20
0
def configure_extensions(app):
    """This function configures all extensions used in app."""

    db.init_app(app)

    with app.app_context():
        db.create_all()
        db.session.commit()
コード例 #21
0
ファイル: __init__.py プロジェクト: hhhyb666/che
 def initdb(drop):
     """Initialize the database."""
     if drop:
         click.confirm('This operation will delete the database, do you want to continue?', abort=True)
         db.drop_all()
         click.echo('Drop tables.')
     db.create_all()
     click.echo('Initialized database.')
コード例 #22
0
def db_corner(app_corner):
    db.app = app_corner
    with app_corner.app_context():
        db.create_all('__all__', app_corner)

    yield db

    db.session.remove()
    db.drop_all()
コード例 #23
0
def configure_extensions(app):
    app.config.setdefault('JWT_SECRET_KEY', SECRET_KEY)
    app.config['SQLALCHEMY_DATABASE_URI'] = db_path
    app.config[
        'SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS
    db.init_app(app)
    jwt.init_app(app)

    db.create_all(app=app)
コード例 #24
0
def init_db():
    print('create tables...')
    db.create_all()
    print('tables created.')
    if not User.query.first():
        user_datastore.create_user(email=app.config['ADMIN_USER'],
                                   password=utils.encrypt_password(
                                       app.config['ADMIN_PASSWORD']))
        db.session.commit()
コード例 #25
0
def init(config='settings.py'):

    app = Flask(__name__)
    app.config.from_pyfile('settings.py')
    db.init_app(app)
    ma.init_app(app)
    with app.app_context():
        db.create_all()
    return app
コード例 #26
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://root:@localhost/knowledge_management?charset=utf8'
    #app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///flask-admin.db'

    # Create modules
    app.register_blueprint(indexModule)
    app.register_blueprint(themeModule)
    app.register_blueprint(groupModule)
    app.register_blueprint(relationModule)
    app.register_blueprint(constructionModule)
    app.register_blueprint(adminModule)
    app.register_blueprint(brustModule)

    app.config['DEBUG'] = True

    app.config['ADMINS'] = frozenset(['*****@*****.**'])
    app.config['SECRET_KEY'] = 'SecretKeyForSessionSigning'
    
    '''
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://%s:@%s/%s?charset=utf8' % (MYSQL_USER, MYSQL_HOST, MYSQL_DB)
    app.config['SQLALCHEMY_ECHO'] = False
    '''
    app.config['DATABASE_CONNECT_OPTIONS'] = {}

    app.config['THREADS_PER_PAGE'] = 8

    app.config['CSRF_ENABLED'] = True
    app.config['CSRF_SESSION_KEY'] = 'somethingimpossibletoguess'
    
    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    # Create database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # init security
    security.init_app(app, datastore=user_datastore)

    # init admin
    admin.init_app(app)
    admin.add_view(UserAdmin(User, db.session))
    # admin.add_view(sqla.ModelView(User, db.session))
    admin.add_view(sqla.ModelView(Role, db.session))
    
    return app
コード例 #27
0
ファイル: conftest.py プロジェクト: corner-cn/corner-backend
def db_corner(app_corner):
    db.app = app_corner
    with app_corner.app_context():
        db.create_all('__all__', app_corner)


    yield db

    db.session.remove()
    db.drop_all()
コード例 #28
0
ファイル: main.py プロジェクト: qitianchan/busad
def create_app():

    app = Flask(__name__)
    app.config.from_object('server.app.config')
    init_app(app)
    config_extensions(app)
    with app.app_context():
        db.create_all()

    return app
コード例 #29
0
def create_app():

    app = Flask(__name__)
    app.config.from_object('server.app.config')
    init_app(app)
    config_extensions(app)
    with app.app_context():
        db.create_all()

    return app
コード例 #30
0
 def setUp(self):
     """
     1. create db if not exists, drop db and create if exists
     2. db.create_all()
     """
     create_db()
     self.app = create_app(TestingConfig)
     self.app_context = self.app.app_context()
     self.app_context.push()
     self.test_client = self.app.test_client()
     db.create_all()
コード例 #31
0
ファイル: app.py プロジェクト: jwelker110/store_backend
def configure_extensions(app):
    # setup SQLAlchemy
    db.init_app(app)
    # db.drop_all(app=app)
    db.create_all(app=app)
    from dummy_data import create_test_data
    # create_test_data(app)

    mail.init_app(app)

    bcrypt.init_app(app)
コード例 #32
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    register_extensions(app)
    register_resources(app)

    db.init_app(app)
    with app.app_context():
        db.create_all()

    return app
コード例 #33
0
ファイル: server.py プロジェクト: eggachecat/openml.org
def register_extensions(app):
    argon2.init_app(app)
    loginmgr.init_app(app)
    loginmgr.login_view = 'login'
    create_dash_app(app)

    # Database initialisation
    db.init_app(app)
    migrate = Migrate(app, db)
    with app.app_context():
        db.create_all()
    return db
コード例 #34
0
ファイル: manage.py プロジェクト: vug/personalwebapp
def create_db():
    """Create database and its schema. Add post states 'draft' and 'published'"""
    db.create_all()

    from models import PostState
    PostState.query.delete()
    db.session.add(PostState('draft'))
    db.session.add(PostState('published'))
    db.session.commit()

    print('Database schema and, "draft" and "published" blog post states have been created. '
          'You can use populate_db command to populate it with the first post and an example draft post. '
          'Also the create_user command to create admin users who can write blog posts.')
コード例 #35
0
    def setUp(self):
        import config
        from main import app_factory
        from extensions import db

        self.app: Empty = app_factory(config.Test, config.project_name)
        self.client = self.app.test_client()

        # https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure/page/2
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()
コード例 #36
0
ファイル: main.py プロジェクト: AleksMD/books_sharing
def create_app(env='dev'):
    app = Flask(__name__)
    app.config.from_object(get_config(env))
    db.init_app(app)
    mail.init_app(app)

    app.register_blueprint(user_blueprint)
    app.register_blueprint(book_blueprint)
    app.register_blueprint(library_blueprint)
    app.register_blueprint(home_page)
    db.create_all(app=app)
    migrate.init_app(app, db)
    return app
コード例 #37
0
 def run(self, **kwargs):
     db.create_all()
     # check if admin exists
     a = Role.query.filter_by(name='admin').first()
     if a is None:
         db.session.add(Role(name='admin'))
         db.session.commit()
         u = prompt('Admin Email?', default='*****@*****.**')
         p = prompt('Admin Password (min 6 characters)?', default='enferno')
         CreateUserCommand().run(email=u, password=p, active=1)
         AddRoleCommand().run(user_identifier=u, role_name='admin')
     else:
         print 'Seems like an Admin is already installed'
コード例 #38
0
ファイル: script.py プロジェクト: loctv/flask-server-starter
 def run(self, **kwargs):
     db.create_all()
     # check if admin exists
     a = Role.query.filter_by(name='admin').first()
     if a is None:
         db.session.add(Role(name='admin'))
         db.session.commit()
         u = prompt('Admin Email?', default='*****@*****.**')
         p = prompt('Admin Password (min 6 characters)?', default='enferno')
         CreateUserCommand().run(email=u, password=p, active=1)
         AddRoleCommand().run(user_identifier=u, role_name='admin')
     else:
         print 'Seems like an Admin is already installed'
コード例 #39
0
def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'the quick brown dog jumps over the lazy fox'
    # mysql+pymysql://<username>:<password>@<host>/<dbname>'
    # (using sqlite for dev purposes)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['UPLOAD_FOLDER'] = '/storage/dbfile'

    # alembic.init_app(app)
    db.init_app(app)

    import models  # noqa: F401

    with app.app_context():
        db.create_all()
        db.session.commit()
        # alembic.revision('making changes')
        # alembic.upgrade()

    from routes.route_utilities import verify_token  # noqa: F401
    from routes.user import user_blueprint
    from routes.dbfile import dbfile_blueprint
    from routes.auth import auth_blueprint
    from routes.employee import employee_blueprint
    # from routes.cost import cost_blueprint
    from routes.reservation import reservation_blueprint
    from routes.roomtype import roomtype_blueprint
    from routes.room import room_blueprint
    from routes.sale import sale_blueprint
    from routes.reservat import reservat_blueprint
    from routes.statgen import statgen_blueprint

    app.register_blueprint(auth_blueprint)
    app.register_blueprint(user_blueprint)
    app.register_blueprint(dbfile_blueprint)
    app.register_blueprint(employee_blueprint)
    # app.register_blueprint(cost_blueprint)
    app.register_blueprint(reservation_blueprint)
    app.register_blueprint(roomtype_blueprint)
    app.register_blueprint(room_blueprint)
    app.register_blueprint(sale_blueprint)
    app.register_blueprint(reservat_blueprint)
    app.register_blueprint(statgen_blueprint)


    currencyThread = threading.Thread(target=putCurrenciesInDB, args=(app,))
    # currencyThread.start()  # enable for testing and production only

    return app
コード例 #40
0
ファイル: __init__.py プロジェクト: AthelasPeru/foodclan
def create_app(config_mode):
	app = Flask(__name__)
	app.config.from_object(config[config_mode])

	toolbar.init_app(app)
	foundation.init_app(app)


	from views import main

	app.register_blueprint(main)

	db.init_app(app)

	db.create_all(app=app)	

	return app
コード例 #41
0
ファイル: __init__.py プロジェクト: yangwangsmile/test2
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    # Create database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    """
    # Create admin
    admin.init_app(app)
    for m in model.__all__:
        m = getattr(model, m)
        n = m._name()
        admin.add_view(SQLModelView(m, db.session, name=n))
    """

    return app
コード例 #42
0
ファイル: base.py プロジェクト: vug/personalwebapp
    def setUp(self):
        sqlite_in_memory_uri = 'sqlite://'
        config = {'SQLALCHEMY_DATABASE_URI': sqlite_in_memory_uri,
                  'TESTING': True,
                  'WTF_CSRF_ENABLED': False}
        app = create_app(config)

        self.test_user_email = 'tester@test_users.com'
        self.test_user_password = '******'

        with app.app_context():
            db.create_all()
            self.test_user = User(self.test_user_email, self.test_user_password, 'Mr. Tester', timezone=-5)
            db.session.add(self.test_user)
            db.session.add(PostState(name='draft'))
            db.session.add(PostState(name='published'))
            db.session.commit()

        self.app = app.test_client()
        self.get_context = app.app_context
コード例 #43
0
ファイル: __init__.py プロジェクト: huxiaoqian/project
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    # Create modules
    app.register_blueprint(rootModule)
    app.register_blueprint(identifyModule)
    app.register_blueprint(moodlensModule)
    app.register_blueprint(profileModule)
    app.register_blueprint(propagateModule)
    app.register_blueprint(adminModule)
    app.register_blueprint(graphModule)
    
    
    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    # Create database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # # Create admin
    # admin.init_app(app)
    # for m in model.__all__:
    #     m = getattr(model, m)
    #     n = m._name()
    #     admin.add_view(SQLModelView(m, db.session, name=n))

    return app
コード例 #44
0
def configure_extensions(app):
    """ Configure app extension. """
    # flask SQLAlchemy
    db.init_app(app)
    db.create_all(app=app)

    # CSRF Protection
    csrf.init_app(app)

    @csrf.error_handler
    @xhr_or_template('errors/forbidden-page.html')
    def csrf_error(message):
        flash(message, 'danger')
        return {'status': 403}


    # mail.init_app(app)

    # Login Manger
    login_manager.init_app(app)
    login_manager.login_view = 'frontend.login'

    # Setup login manager anonymous class.
    class DefaultAnonymousUserMixin(AnonymousUserMixin):
        id = None
        firstName = None
        lastName = None
        username = '******'
        email = None
        dateJoined = None
        avatar = 'avatar.jpg' # TODO: find a better avatar img for guest users

        @staticmethod
        def is_admin():
            return False

    login_manager.anonymous_user = DefaultAnonymousUserMixin
コード例 #45
0
ファイル: factory.py プロジェクト: tsheasha/tictail
def create_app(priority_settings=None):
    
    # Initialising a Flask App
    app = Flask(__name__, static_url_path='')
    heroku = Heroku()
    compress = Compress() 

    # Load configuraiton from settings file
    app.config.from_object(settings)
    app.config.from_object(priority_settings)

    # Initialise database
    db.init_app(app)

    # Using Heroku as deployment server
    heroku.init_app(app)
    
    # Gziping responses from app
    compress.init_app(app)
    
    # Using Flask-Login
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'accounts.login'
    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    # Registering Blueprints in an effor to make app modular
    app.register_blueprint(index_blueprint)
    app.register_blueprint(todo_blueprint)
    app.register_blueprint(user_blueprint)
    app.register_blueprint(api_todo_blueprint)

    with app.app_context():
        db.create_all()
    return app
コード例 #46
0
ファイル: app.py プロジェクト: rtx3/Salt-MWDS
def initdb():
    db.drop_all()
    db.create_all()
コード例 #47
0
ファイル: __init__.py プロジェクト: huxiaoqian/case
def create_app():
    app = Flask(__name__)

    # Create modules
    app.register_blueprint(rootModule)
    app.register_blueprint(moodlensModule)
    app.register_blueprint(opinionModule)
    app.register_blueprint(propagateModule)
    app.register_blueprint(indexModule)
    app.register_blueprint(evolutionModule)
    app.register_blueprint(identifyModule)
    app.register_blueprint(quota_systemModule)
    app.register_blueprint(dataoutModule)

    # the debug toolbar is only enabled in debug mode
    app.config['DEBUG'] = True

    app.config['ADMINS'] = frozenset(['*****@*****.**'])
    app.config['SECRET_KEY'] = 'SecretKeyForSessionSigning'

    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://%s:@%s/%s?charset=utf8' % (MYSQL_USER, MYSQL_HOST, MYSQL_DB)
    app.config['SQLALCHEMY_ECHO'] = False
    app.config['DATABASE_CONNECT_OPTIONS'] = {}

    app.config['THREADS_PER_PAGE'] = 8

    app.config['CSRF_ENABLED'] = True
    app.config['CSRF_SESSION_KEY'] = 'somethingimpossibletoguess'

    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    app.config['MONGO_HOST'] = MONGODB_HOST
    app.config['MONGO_PORT'] = MONGODB_PORT

    app.config['MONGODB_SETTINGS'] = {
        'db': MASTER_TIMELINE_54API_WEIBO_DB,
        'host': MONGODB_HOST,
        'port': MONGODB_PORT
    }

    # Create mysql database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # Create mongo_engine
    mongo_engine.init_app(app)

    admin.init_app(app)
    """
    # Create mysql database admin, visit via url: http://HOST:PORT/admin/
    for m in model.__all__:
        m = getattr(model, m)
        n = m._name()
        admin.add_view(SQLModelView(m, db.session, name=n))

    for m in mongodb_model.__all__:
        admin.add_view(MongoDBView(m))
    """

    # init mongo
    mongo.init_app(app)

    return app
コード例 #48
0
ファイル: manage.py プロジェクト: coco369/qxh_ecp
def init_db():
    '''init database'''
    db.create_all()
    print 'Init database success.'
コード例 #49
0
def init_db():
    db.create_all(app=app)
コード例 #50
0
ファイル: commands.py プロジェクト: fengluo/flask-shield
 def run(self):
     db.create_all()
コード例 #51
0
ファイル: main.py プロジェクト: greatghoul/Local
def initdb():
    app = make_application()
    db.app = app
    db.drop_all()
    db.create_all()
    logger.info("Database reseted")
コード例 #52
0
ファイル: escalante.py プロジェクト: johnharris85/escalante
def create_db(app):
    from models import User, Client
    db.create_all()
    return None
コード例 #53
0
ファイル: manage.py プロジェクト: WillardDone/ncland
def createall():
    "Creates database tables"

    db.create_all()
コード例 #54
0
'''
Created on Apr 25, 2016

@author: gonzalo
'''
from factory import create_app
from model import User
from extensions import db

if __name__ == '__main__':
    app = create_app("local")
    db.create_all(app=app)
コード例 #55
0
import flask
import flask.views

from views import *
from extensions import db


app = flask.Flask(__name__)
app.secret_key = "lepetitbonhomeenmousse"
users = {'test': 'test'}

## DATABASES
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db.init_app(app)
db.app = app
db.create_all()


## VIEWS
class MainView(flask.views.MethodView):
    def get(self):
        return flask.render_template('index.html')
    
    def post(self):
        if 'logout' in flask.request.form:
            flask.session.pop('username', None)
            return flask.redirect(flask.url_for('index'))
        required = ['username', 'password']
        for r in required:
            if r not in flask.request.form:
                flask.flash("Error: {0} is required.".format(r))
コード例 #56
0
ファイル: app.py プロジェクト: ocomsoft/enferno
 def before_first_request():
     db.create_all()
コード例 #57
0
ファイル: models.py プロジェクト: edwinavalos/flask-rsvp
def create_all(app=None):
    db.create_all(app=app)
コード例 #58
0
ファイル: manage.py プロジェクト: nocoffe/pyweb
def createall():
    db.create_all()
コード例 #59
0
 def init_table():
     db.create_all()
コード例 #60
0
ファイル: __init__.py プロジェクト: B1aZer/ImInIt
def create_db():
    with app.test_request_context():
        db.create_all()