Example #1
0
def register_extensions(app):
    login.init_app(app)
    login.login_view = 'main.login'  #type: ignore
    bootstrap.init_app(app)
    db.init_app(app)
    with app.app_context():
        if db.engine.url.drivername == 'sqlite':
            migrate.init_app(app, db, render_as_batch=True)
        else:
            migrate.init_app(app, db)
    csrf.init_app(app)
    sitemap.init_app(app)
    cache.init_app(app, config=app.config)

    def fetch_token(name):
        item = oauth.models.OAuth1Token.query.filter_by(
            name=name,
            user_id=(getattr(current_user, 'id', False)
                     or g.current_id)).first()
        if item:
            return item.to_token()

    oauth_client.init_app(app, fetch_token=fetch_token, cache=cache)
    oauth_client.register(
        name='schoology',
        api_base_url='https://api.schoology.com/v1/',
        request_token_url='https://api.schoology.com/v1/oauth/request_token',
        access_token_url='https://api.schoology.com/v1/oauth/access_token',
        authorize_url='https://www.schoology.com/oauth/authorize',
        client_id=app.config['SCHOOLOGY_CLIENT_ID'],
        client_key=app.config['SCHOOLOGY_CLIENT_SECRET'])
Example #2
0
def create_app(environemnt):
    """
    App factory for the server.

    Instantiates a Flask object.
    Configures the app according to the environment.
    Initializes the extensions.
    Adds the middleware to check headers.
    Returns the app instance.

    :param: environment
        Environemnt to configure the server to
    :returns:
    """
    app = Flask(__name__)
    app.config.from_object(cfg_map[environemnt])
    app.redis = Redis.from_url(app.config.get("REDIS_URL"))
    app.task_queue = Queue(app.config.get("REDIS_QUEUE_NAME"),
                           connection=app.redis)
    mongo_client = MongoClient(
        app.config.get("MONGO_URI"),
        authSource=app.config.get("MONGO_AUTH_SOURCE"),
    )
    app.mongo = mongo_client[app.config.get("MONGO_DATABASE")]

    from app import bcrypt
    from app import cors
    from app import db
    from app import migrate

    db.init_app(app)
    cors.init_app(app, resources={r"/*": {"origins": "*"}})
    bcrypt.init_app(app)
    migrate.init_app(app, db)

    from app.api import api

    api.init_app(app)

    from app.api.auth.models import Token  # noqa: F401
    from app.api.sentiment.models import Sentiment  # noqa: F401
    from app.api.users.models import User  # noqa: F401

    @app.before_request
    def check_headers():
        if ("swagger" not in request.path and "admin" not in request.path
                and request.method != "OPTIONS"):
            accepts = request.headers.get("Accept")
            if not accepts or accepts != "application/json":
                abort(415, "Only content type supported is application/json")
            if request.method in ["POST", "PUT"]:
                content_type = request.headers.get("Content-Type")
                if not content_type or content_type != "application/json":
                    abort(
                        415,
                        "POST/PUT requests should define Content-Type header",
                    )

    return app
Example #3
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    app.register_blueprint(routes_bp)
    app.db = db
    return app
Example #4
0
def create_app():
    app = Flask(__name__)

    import os
    if not os.environ.get('APP_SETTING'):
        os.environ['APP_SETTING'] = 'config/dev.cfg'

    app.config.from_envvar('APP_SETTING', silent=True)

    from app import model as db
    db.init_app(app)

    from app import migrate as mi
    mi.init_app(app)

    from app import schema as ma
    ma.init_app(app)

    from app.controller.user_controller import login_manager
    login_manager.init_app(app)

    from app.controller.user_controller import bp as user_bp
    app.register_blueprint(user_bp)

    from app.controller.board_controller import bp as board_bp
    app.register_blueprint(board_bp)

    from app.controller.post_controller import bp as post_bp
    app.register_blueprint(post_bp)

    from app.controller.comment_controller import bp as comment_bp
    app.register_blueprint(comment_bp)

    @app.errorhandler(422)
    def schema_validation_handler(err):
        exc = getattr(err, 'exc')
        messages = exc.messages if exc else ['Invalid request']
        result = dict(messages=messages)
        return default_messages_error_schema.jsonify(result), 422

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin',
                             'http://localhost:4200')
        response.headers.add('Access-Control-Allow-Credentials', 'true')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET,PUT,POST,DELETE,OPTIONS,PATCH')
        return response

    return app
Example #5
0
def client():    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(os.path.dirname(__file__), 'test.db')
    app.config['TESTING'] = True
    db.init_app(app)
    with app.app_context():
        db.create_all()     
        migrate.init_app(app, db)
    
    with app.test_client() as client:       
        yield client
        print("Teardown context")
        db.session.remove()
        db.drop_all()
        os.remove(os.path.join(os.path.dirname(__file__), 'test.db'))    
Example #6
0
def create_app():
    app = Flask(__name__, template_folder="templates", static_folder="assets")
    app.config.from_object(config_map[os.environ.get("FLASK_ENV", "production")])

    breadcrumbs.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    login_manager.login_message = None
    login_manager.login_view = ".start_page"

    app.register_blueprint(main_blueprint)

    app.logger.setLevel(app.config.get("LOG_LEVEL", LOGLEVEL_WARNING))
    print(app.logger)

    return app
Example #7
0
def create_app(env=None):
    """An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/.
        :param env: The configuration object to use.
        """
    app = Flask(__name__,
                static_folder=None,
                instance_path=os.path.join(ROOT_PROJECT_DIR, 'instance'))

    setup_config(app, env)

    if app.config.get('LOG_LEVEL') is not None:
        print('Setting Log Level to %s' % (app.config.get('LOG_LEVEL')))
        logging.basicConfig(
            level=logging.getLevelName(app.config.get('LOG_LEVEL')))

    # scan_models()
    from .model import import_models
    import_models()

    db.app = app
    db.init_app(app)

    migrate.init_app(app=app, db=db)

    # populated regions table required for adverts form. Must be imported
    # before blueprints
    # from data.generator import Generator
    # generator = Generator()
    # generator.create_regions()
    #
    # bcrypt.init_app(app)
    # login_manager.init_app(app)
    #
    # if not app.debug:
    #     ErrorHandler(app)

    register_commands(app)

    load_blueprints(app)

    CORS(app)

    return app
def init_extensions(app):
    """
    初始化第三方插件
    :return:
    """
    # flask-MongoEngine
    db.init_app(app)
    db.connection(**app.config.get('ORDER_DB_CONFIG'))
    db.connection(**app.config.get('INVENTORY_DB_CONFIG'))
    db.connection(**app.config.get('CART_DB_CONFIG'))
    db.connection(**app.config.get('CONTENT_DB_CONFIG'))
    db.connection(**app.config.get('LOG_DB_CONFIG'))
    mongo_inventory.init_app(app, config_prefix='MONGO_INVENTORY')
    redis.connection_pool = ConnectionPool(**app.config.get('REDIS_CONFIG'))
    session_redis.connection_pool = ConnectionPool(
        **app.config.get('SESSION_REDIS'))
    # server side session
    app.session_interface = RedisSessionInterface(session_redis)
    # flask-script
    migrate.init_app(app, db)
    # flask-mail
    mail.init_app(app)
    # flask-cache
    cache.init_app(app)
    # flask-admin
    admin.init_app(app)
    # flask-bcrypt
    bcrypt.init_app(app)
    # flask-babel
    babel.init_app(app)
    # flask-toolbar
    toolbar.init_app(app)
    # flask-assets
    assets.init_app(app)

    login_manager.login_view = 'frontend.login'

    # login_manager.refresh_view = 'frontend.reauth'
    @login_manager.user_loader
    def load_user(id):
        """

        :param id:
        :return:
        """
        return User.objects(id=id, is_deleted=False).first()

    login_manager.init_app(app)
    login_manager.login_message = gettext('Please login to access this page.')
    login_manager.needs_refresh_message = gettext(
        'Please reauthenticate to access this page.')

    # flask-principal
    principal.init_app(app)
    from flask_principal import identity_loaded

    @identity_loaded.conect_via(app)
    def on_identity_loaded(sender, identity):
        """

        :param sender:
        :param identity:
        :return:
        """
        principal_on_identity_loaded(sender, identity)
Example #9
0
from app import create_app, db, migrate, cli
from app.models import User, Post, Message, Notification, Task

app = create_app()
cli.register(app)


@app.shell_context_processor
def make_shell_context():
    return {
        'db': db,
        'User': User,
        'Post': Post,
        'Message': Message,
        'Notification': Notification,
        'Task': Task
    }


with app.app_context():
    if db.engine.url.drivername == 'sqlite':
        migrate.init_app(app, db, render_as_batch=True)
    else:
        migrate.init_app(app, db)
Example #10
0
from datetime import date

from flask import Flask, jsonify, request

from app import db, migrate
from controller import (BaseController, BudgetController, MutationController,
                        TransactionController, WalletController)
from model import Budget, Transaction
from serializer import BudgetSerializer, TransactionSerializer
from service import BudgetService, RecordNotFoundError, TransactionService

app = Flask(__name__,
            static_url_path='',
            static_folder='static',
            template_folder='templates')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
db.init_app(app)
migrate.init_app(app, db)

app.register_blueprint(BaseController)
app.register_blueprint(BudgetController, url_prefix='/budgets')
app.register_blueprint(MutationController, url_prefix='/mutations')
app.register_blueprint(TransactionController, url_prefix='/transactions')
app.register_blueprint(WalletController, url_prefix='/wallets')