def create_app(config=None):
    if config is None:
        config = DevelopmentConfig()

    app = Flask(__name__)

    app.config.from_object(config)
    app.config.from_envvar('{{cookiecutter.app_name|upper}}_CONFIG', silent=True)

    assets.init_app(app)
    assets.from_yaml(app.config['ASSETS'])

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    babel.init_app(app)
    mail.init_app(app)

    @app.route('/')
    def home():
        return render_template('home.html')

    for name, url_prefix in app.config.get('MODULES', []):
        blueprint = getattr(getattr(modules, name), name)
        app.register_blueprint(blueprint, url_prefix=url_prefix)

    return app
예제 #2
0
def register_extensions(app):
    assets.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #3
0
def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    assets.init_app(app)
    toolbar = DebugToolbarExtension(app)
    cache.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #4
0
def register_extensions(app):
    db.init_app(app)
    dbm.init_app(app)
    login_manager.init_app(app)
    assets.init_app(app)
    if app.config['DEBUG_TB_ENABLED']:
        DebugToolbarExtension(app)
    cache.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #5
0
def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    assets.init_app(app)
    assets.app = app
    assets.url = app.static_url_path
    toolbar = DebugToolbarExtension(app)
    cache.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #6
0
def register_extensions(app):
    """Register Flask extensions."""
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #7
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    webpack.init_app(app)
    return None
예제 #8
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    webpack.init_app(app)
    return None
예제 #9
0
def register_extensions(app):
    """Register Flask extensions."""
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #10
0
def register_extensions(app):
    """Register Flask extensions.

    :param app: 

    """
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    return None
예제 #11
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. {{cookiecutter.app_name}}.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)

    if cache:
        # initialize the cache
        cache.init_app(app)

    if debug_toolbar:
        # initialize the debug tool bar
        debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    if assets_env:
        assets_env.init_app(app)
        assets_loader = PythonAssetsLoader(assets)
        for name, bundle in assets_loader.load_bundles().items():
            assets_env.register(name, bundle)

    # register our blueprints
    main_controller.before_request(before_app_request)
    app.register_blueprint(main_controller)

    admin_controller.before_request(before_app_request)
    app.register_blueprint(admin_controller)

    file_controller.before_request(before_app_request)
    app.register_blueprint(file_controller)

    return app
예제 #12
0
def register_extensions(app):
    """ Register Flask extensions. """

    bcrypt.init_app(app)
    cache.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    # webpack.init_app(app)
    jwt.init_app(app)
    # If db is SQLAlchemy instance,
    # Flask-SQLAlchemy must be initialized before Flask-Marshmallow
    db.init_app(app)
    ma.init_app(app)
    mail.init_app(app)
    rest_api.init_app(app)
    celery.init_app(app)
def test_app():
    # when flask isnt running, selenium test runs as readonly. but when session is running it asks to authenticate?
    ##added this to pick up LOGIN_DISABLED flag from flask_config to turn off authenticatin for testing
    os.environ['LOGIN_DISABLED'] = 'True'
    os.environ['ANON_USER'] = '******'## added as part of module 10
    # construct the new application
    application = app.create_app()
    # added login manager to use anonymouse user as part of module 10
    login_manager = create_login_manager()
    login_manager.init_app(application)
    login_manager.anonymous_user = User
    application.config.from_object('flask_config.Config')  
    # start the app in its own thread.
    thread = Thread(target=lambda: application.run(use_reloader=False))
    thread.daemon = True
    thread.start()
    yield app
    # Tear Down
    thread.join(1)
예제 #14
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. {{cookiecutter.repo_name}}.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # initialize the cache
    # cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    return app
예제 #15
0
def register_extensions(app):
    bcrypt.init_app(app)
    cache.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    return None
예제 #16
0
def register_extensions(app):
    assets.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, Base)
    return None
예제 #17
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(
        'flask_config.Config')  #added secret key back for module 10
    # added as part of module 10
    #login_disabled = os.getenv('LOGIN_DISABLED') == 'True'
    #app.config['LOGIN_DISABLED'] = login_disabled

    load_dotenv()
    MONGO_LOGIN = os.getenv("MONGO_LOGIN")  # take .env from dotenv
    MONGO_PASS = os.getenv("MONGO_PASS")  # take .env from dotenv
    GIT_CLIENT_ID = os.getenv("GIT_CLIENT_ID")  # take .env from dotenv
    GIT_CLIENT_SECRET = os.getenv("GIT_CLIENT_SECRET")  # take .env from dotenv

    #module 11 pointing to cosmos db
    #myclient = pymongo.MongoClient('mongodb+srv://%s:%[email protected]/ToDo?retryWrites=true&w=majority' % (MONGO_LOGIN, MONGO_PASS))
    myclient = pymongo.MongoClient(
        'mongodb://%s:%[email protected]:10255/DefaultDatabase?ssl=true&retrywrites=false&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@module11-cosmos-serverless@'
        % (MONGO_LOGIN, MONGO_PASS))
    print(myclient)
    mydb = myclient["ToDo"]
    mycollection = mydb["All Items"]

    login_manager = create_login_manager()
    login_manager.init_app(app)

    @app.route('/')
    @login_required
    def root():
        return redirect(url_for('getAll'))

    @app.route('/root/github/authorized')
    def login():
        # provder (github) sends the authorization code back
        code = request.args.get('code')
        client = WebApplicationClient(
            client_id=os.getenv("GIT_CLIENT_ID"),
            client_secret=os.getenv("GIT_CLIENT_SECRET"),
            code=code)
        # client then sends he authorization code back to the providers token URL to exchange for token
        url, headers, body = client.prepare_token_request(
            'https://github.com/login/oauth/access_token',
            client_secret=os.getenv("GIT_CLIENT_SECRET"),
            code=code)
        # parse the JSON response body post token validation, receives an access token or key
        token_response = requests.post(url,
                                       headers=headers,
                                       data=body,
                                       auth=(os.getenv("GIT_CLIENT_ID"),
                                             os.getenv("GIT_CLIENT_SECRET")))
        # parse the token from the response
        token = client.parse_request_body_response(token_response.text)
        # save the token
        session['oauth_token'] = token
        # get user id details by passing above git token
        github = OAuth2Session(os.getenv("GIT_CLIENT_ID"),
                               token=session['oauth_token'])
        # can see my details in response 200
        userinfo_response = jsonify(
            github.get('https://api.github.com/user').json())
        # prints out logged in user, TheLegendaryPan in this case!
        user_id = userinfo_response.json['login']

        user = User(user_id)
        login_user(user)

        return redirect(url_for('getAll'))

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return Response('<p>Logged out</p>')

    @app.route('/items/get_all_cards', methods=["GET"])
    @login_required
    def getAll():

        #myclient = pymongo.MongoClient('mongodb+srv://%s:%[email protected]/ToDo?retryWrites=true&w=majority' % (MONGO_LOGIN, MONGO_PASS))
        #mydb = myclient["ToDo"]
        #mycollection = mydb["All Items"]
        myclient = pymongo.MongoClient(
            'mongodb://%s:%[email protected]:10255/DefaultDatabase?ssl=true&retrywrites=false&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@module11-cosmos-serverless@'
            % (MONGO_LOGIN, MONGO_PASS))
        mydb = myclient["ToDo"]
        mycollection = mydb["All Items"]

        todo_resp = mycollection.find(
        )  # find method returns a cursor instance for iteration

        todo_list = [TodoItem.from_mongo_card(card)
                     for card in todo_resp]  ## returns list of dict

        # user authorization
        user_authorizaion = User(current_user.get_id())
        reader = user_authorizaion.get_role() == Role.Reader

        return render_template('all_items.html',
                               todos=ViewModel(todo_list, reader))

    @app.route('/Items_Done', methods=['POST', 'GET'])
    @login_required
    @accesscheck
    def Items_Done():
        if request.method == 'POST':
            if request.form['action'] == 'Mark as Done':
                card_name = request.form['card_name']
                card_id = request.form['card_id']
                myquery = {"_id": ObjectId(card_id)}
                newvalue = {"$set": {"status": "Done"}}
                mycollection.update_one(myquery, newvalue)
            elif request.form['action'] == 'Delete':
                card_id = request.form['card_id']
                myquery = {"_id": ObjectId(card_id)}
                mycollection.delete_one(myquery)

        return redirect("/")

    @app.route('/Items_To_Do', methods=['POST', 'GET'])
    @login_required
    @accesscheck
    def Items_To_Do():
        if request.method == 'POST':
            if request.form['action'] == 'Mark as To Do':
                card_name = request.form['card_name']
                card_id = request.form['card_id']
                myquery = {"_id": ObjectId(card_id)}
                newvalue = {"$set": {"status": "To Do"}}
                mycollection.update_one(myquery, newvalue)
            elif request.form['action'] == 'Delete':
                card_id = request.form['card_id']
                myquery = {"_id": ObjectId(card_id)}
                mycollection.delete_one(myquery)
        return redirect("/")

    @app.route('/items/create_item_page', methods=['POST', 'GET'])
    @login_required
    @accesscheck
    def create_item_page():
        return render_template('CreateCard.html')

    @app.route('/items/Items_To_Add', methods=['POST', 'GET'])
    @login_required
    @accesscheck
    def Items_To_Add():
        if request.method == 'POST':
            card_name = request.form['card_name']
            mycollection.insert_one({
                "title": card_name,
                "status": "To Do",
                "update_time": datetime.now()
            })
        return redirect("/")

    if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=5000)

    return app