コード例 #1
0
def create_app(config_filename):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config_filename)
    db.init_app(app)
    app.register_blueprint(product_blueprint)
    migrate = Migrate(app, db)
    return app
コード例 #2
0
def create_app():
    """
    Create and configure an instance of the Flask application.
    """
    app = Flask(__name__)

    # Config
    from application.config import Config
    app.config.from_object(Config)

    # SQLAlchemy
    from application.models import db
    db.init_app(app)

    # Migrate
    migrate.init_app(app, db)

    # JWT
    jwt.init_app(app)

    # Marshmallow serializer
    from application.serializer import ma
    ma.init_app(app)

    # Blueprint
    from application.auth import bp as bp_auth
    from application.store import bp as bp_store
    app.register_blueprint(bp_auth)
    app.register_blueprint(bp_store)

    return app
コード例 #3
0
def register_extensions(app):
    from application.assets import env
    env.init_app(app)

    from application.models import db
    db.init_app(app)

    # flask security setup
    from application.extensions import user_datastore
    Security(app, user_datastore)

    # flask markdown
    from flaskext.markdown import Markdown
    Markdown(app)

    # flask mail
    from application.extensions import mail
    mail.init_app(app)

    import os
    if 'SENTRY_DSN' in os.environ:
        from raven.contrib.flask import Sentry
        Sentry(app, dsn=os.environ['SENTRY_DSN'])

    from application.sso.oidc import OIDC
    app.oidc_client = OIDC(app)
コード例 #4
0
def create_app(config=None):
    """Our application factory. It optionally takes a config
    object that can be used to update our applications
    configuration"""

    app = Flask(__name__, template_folder='views')

    if config:
        app.config.from_object(config)

    # Install plugins after the comment
    heroku = Heroku(app)
    bootstrap = Bootstrap(app)
    db.init_app(app)

    # Install blueprints after the comment
    app.register_blueprint(home.app, url_prefix="/")
    app.register_blueprint(registration.app, url_prefix="/registration")
    app.register_blueprint(authentication.app, url_prefix="/auth")

    # Some jinja helpers

    app.jinja_env.globals.update(has_session=has_session)

    return app
コード例 #5
0
def create_app(config_class=Config):
    app.config.from_object(config_class)
    from application import routes, forms
    from application.models import db
    db.init_app(app)
    migrate = Migrate()
    migrate.init_app(app, db)
    return app
コード例 #6
0
def create_db():
    app = Flask(__name__)
    app.config.from_object(os.environ['APP_SETTINGS'])
    db.init_app(app)

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

    return None
コード例 #7
0
def register_extensions(app):
    from application.assets import env
    env.init_app(app)

    from application.models import db
    db.init_app(app)

    # flask security setup
    from application.extensions import user_datastore
    Security(app, user_datastore)
コード例 #8
0
def create_app(config_filename, debug):
    # Instantiate the Flask application with configurations
    app = Flask(__name__, instance_relative_config=True)
    app.debug = debug
    # Instantiate Configs
    app.config.from_object(config_filename)

    path = op.join(op.dirname(__file__), 'static')
    # Instantiate the debug toolbar. Only for debug true
    toolbar = DebugToolbarExtension(app)

    # Initialize babel
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        if request.args.get('lang'):
            session['lang'] = request.args.get('lang')
        return session.get('lang', 'en')

    db.init_app(app)
    # Init Migrations
    migrate = Migrate(app, db)

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    register_blueprints(app)

    # Create admin
    admin = Admin(
        app,
        'My Dashboard',
        base_template='my_master.html',
        template_mode='bootstrap3',
    )

    # Add model views
    admin.add_view(UserModelView(User, db.session, name='Users'))
    admin.add_view(RoleModelView(Role, db.session, name="Roles"))
    admin.add_view(CustomView(name="Custom view", endpoint='custom'))

    # define a context processor for merging flask-admin's template context into the
    # flask-security views.
    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    h=admin_helpers,
                    get_url=url_for)

    return app
コード例 #9
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../sqlite3.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    db.init_app(app)

    app.register_blueprint(page_bp)

    app.register_blueprint(api_v1_bp,
                           url_prefix='/{prefix}/{version}'.format(
                               prefix='api', version=API_VERSION_V1))
    app.register_blueprint(api_v2_bp,
                           url_prefix='/{prefix}/{version}'.format(
                               prefix='api', version=API_VERSION_V2))

    return app
コード例 #10
0
def create_app():
    """Create Flask app."""
    config = load_config()
    print(f"Conguration loaded : {config}")
    app = Flask(__name__)
    app.config.from_object(config)
    if not hasattr(app, 'production'):
        app.production = not app.debug and not app.testing
    # CSRF protect
    # CSRFProtect(app)
    app.register_blueprint(api)
    app.register_blueprint(site)
    print("Blueprint registered")
    db.init_app(app)
    print('Database initialised')
    return app
コード例 #11
0
def create_app(config_name):

    app = Flask(__name__)
    config_module = f"application.config.{config_name.capitalize()}Config"
    app.config.from_object(config_module)

    from application.models import db, migrate

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

    @app.route("/")
    def hello_world():
        return "Hello, World!!!!"

    return app
コード例 #12
0
def register_extensions(app, user_datastore):

    db.init_app(app)
    app.db = db

    serializer(app.secret_key)

    # user_manager(app, app.db, User)
    # print(f"user manager: {dir(user_manager)}")

    admin.init_app(app)

    debug_toolbar(app)

    # security(app, user_datastore)
    security.init_app(app, user_datastore)

    # define a context processor for merging flask-admin's template context into the
    # flask-security views.
    @security.context_processor
    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
            get_url=url_for
        )

    # Access front bluprint and add context variables for Flask-admin layout 
    @front_blueprint.context_processor
    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
            get_url=url_for
        )

    # from app.admin_core import configure_admin
    # configure_admin(admin)
    
    return None
コード例 #13
0
ファイル: api_service.py プロジェクト: Tri-Try/REST
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../sqlite3.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    db.init_app(app)

    app.register_blueprint(page_bp)

    app.register_blueprint(
        api_v1_bp,
        url_prefix='/{prefix}/{version}'.
        format(prefix='api', version=API_VERSION_V1)
    )
    app.register_blueprint(
        api_v2_bp,
        url_prefix='/{prefix}/{version}'.
        format(prefix='api', version=API_VERSION_V2)
    )

    return app
コード例 #14
0
ファイル: app.py プロジェクト: ilayt/flask_testproj
def create_app(config_name):

    app = Flask(__name__)
    config_module = f"application.config.{config_name.capitalize()}Config"
    app.config.from_object(config_module)

    db.init_app(app)

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

    @app.route("/")
    def hello_world():
        print('request came')
        return "Hello, World!"

    @app.route("/users")
    def users():
        num_users = User.query.count()
        return f"Number of users: {num_users}"

    return app
コード例 #15
0
ファイル: __init__.py プロジェクト: 0xDEADCAT/colors-api
def create_app(config_obj):
    # Create the Connexion application instance
    connex_app = connexion.App(__name__, specification_dir=config_obj.SPECIFICATION_DIR)

    # Read the specification file to configure the endpoints
    connex_app.add_api(config_obj.SPECIFICATION_FILE)

    # Get the underlying Flask app instance
    app = connex_app.app
    app.config.from_object(config_obj)

    # Initialize database plugin
    from application.models import db
    db.init_app(app)

    with app.app_context():
        # Include routes
        from . import routes

        # Register blueprints
        app.register_blueprint(routes.main_bp)

        return connex_app
コード例 #16
0
from datetime import datetime
from flask import Flask, jsonify, request

app = Flask(__name__)
config = app.config.from_envvar('APP_SETTINGS')

from application.models import db, Task

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


def get_task(task_id):
    return db.session.query(Task).filter_by(id=task_id).first_or_404()


@app.route("/tasks")
def tasks_list():
    tasks = db.session.query(Task).all()
    return jsonify(tasks=[i.serialize for i in tasks])


@app.route("/tasks/<int:task_id>")
def task_by_id(task_id):
    task = get_task(task_id)
    return jsonify(task=task.serialize)


@app.route("/tasks/post", methods=['POST'])
def task_post():
コード例 #17
0
ファイル: app.py プロジェクト: Vishalghyv/libindex
def create_app(config_name):

    app = Flask(__name__)

    config_module = f"application.config.{config_name.capitalize()}Config"

    app.config.from_object(config_module)

    from application.models import db, migrate

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

    @app.route('/loading')
    def loading():

        if config_name == "development":
            # project_gutenberg.main()
            from application.pipeline import loader
            loader.load_to_dtm_table(db, DTM)
        else:
            return render_template('index.html')

        return config_name

    # Home page
    @app.route("/")
    def index():
        return render_template('index.html')

    @app.route("/submit", methods=['GET', 'POST', 'RESET'])
    def submit():
        if request.method == 'POST':
            try:
                text_entered = request.form['text']
            except:
                return render_template('index.html',
                                       message='Please give a valid input')

            if (text_entered == ''):
                return render_template(
                    'index.html',
                    message='Please enter some text input to be searched')

            try:
                _results = []
                search_terms = text_entered.split()

                for search_term in search_terms:
                    _results.append(DTM.title.contains(search_term))

                _rec = []
                for record in _results:
                    _rec.append(record.title)

            #
            #     return _res.dtm_id
            #
            #         # for res in _res:
            #         #     _results.append(res.dtm_id)
            #     return len(_results)
            #
            #     # results = []
            #     # for dtm_id in _results:
            #     #     entity = DTM.query.filter_by(dtm_id=dtm_id).__dict__
            #     #     results.append(entity)
            #     # ans = results
            except:
                # return render_template('index.html', message='No such item found')
                pass
            return str(_results[2].title)
            # print(ans)
            # return render_template('found.html', output=ans)

    # Docs page and proposal page
    @app.route("/docs")
    def about():
        return render_template('docs.html')

    # Team page
    @app.route("/team")
    def OurTeam():
        return render_template('team.html')

    return app
コード例 #18
0
def create_app():
    app = Flask(__name__)  # type: Flask
    app.config.from_object(config)
    db.init_app(app)
    CSRFProtect(app)
    return app
コード例 #19
0
def create_app():
    app = Flask(__name__)

    config_module = f"application.config.Config"

    app.config.from_object(config_module)

    from application.models import db, migrate

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

    @app.route('/workflows', methods=['POST'])
    def create_workflow():
        if request.is_json:
            data = request.get_json()

            not_allowed_fields, missing_fields = validate_body_structure(data)
            if not_allowed_fields:
                return {
                    "error":
                    f"The fields {not_allowed_fields} are not allowed for the workflow object"
                }, 400

            if missing_fields:
                return {
                    "error":
                    f"The fields {missing_fields} are required for the workflow object"
                }, 400

            invalid_format_fields = validate_fields_format(data)
            if invalid_format_fields:
                return {
                    "error": f"The fields {invalid_format_fields} are invalid"
                }, 400

            new_workflow = WorkflowModel(status=data['status'],
                                         data=data['data'],
                                         steps=data['steps'])

            db.session.add(new_workflow)
            db.session.commit()

            connection = pika.BlockingConnection(
                pika.ConnectionParameters(host='development_rabbitmq_1'))
            channel = connection.channel()
            channel.queue_declare(queue='workflow_queue', durable=True)
            channel.basic_publish(
                exchange='',
                routing_key='workflow_queue',
                body=str(new_workflow.UUID),
                properties=pika.BasicProperties(delivery_mode=2))
            connection.close()

            return {
                "message": f"The workflow has been created successfully.",
                "workflow": {
                    "uuid": new_workflow.UUID,
                    "data": new_workflow.data,
                    "steps": new_workflow.steps,
                    "status": new_workflow.status
                }
            }

        else:
            return {"error": "The request payload is not in JSON format"}, 400

    @app.route('/workflows', methods=['GET'])
    def retrieve_workflows():
        workflows = WorkflowModel.query.all()
        results = [{
            "uuid": workflow.UUID,
            "data": workflow.data,
            "steps": workflow.steps,
            "status": workflow.status
        } for workflow in workflows]

        return {"count": len(results), "workflows": results}

    @app.route('/workflows/<workflow_id>', methods=['PATCH'])
    def update_workflow(workflow_id):
        workflow = WorkflowModel.query.get_or_404(workflow_id)

        data = request.get_json()

        not_allowed_fields, _ = validate_body_structure(data)
        if not_allowed_fields:
            return {
                "error":
                f"The fields {not_allowed_fields} are not allowed for the workflow object"
            }, 400

        invalid_format_fields = validate_fields_format(data)
        if invalid_format_fields:
            return {
                "error": f"The fields {invalid_format_fields} are invalid"
            }, 400

        if 'data' in data.keys() or 'steps' in data.keys():
            return {"error": f"You can update only the workflow status"}, 400

        workflow.status = data['status']

        db.session.add(workflow)
        db.session.commit()

        return {
            "message": f"The workflow {workflow.UUID} was successfully updated"
        }

    @app.route('/workflows/consume', methods=['GET'])
    def update_workflows():

        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='development_rabbitmq_1'))
        channel = connection.channel()
        channel.queue_declare(queue='workflow_queue', durable=True)

        channel.basic_qos(prefetch_count=1)

        method, properties, body = channel.basic_get(queue='workflow_queue',
                                                     auto_ack=True)

        if method is None:
            return {"message": "There is no workflow to consume"}
        else:
            uuid_recovered = body.decode()

        return {
            "message":
            f"The workflow {uuid_recovered} was successfully consumed. "
            f"Download the csv file from http://localhost:5000/workflows/download/{uuid_recovered}"
        }

    @app.route('/workflows/download/<workflow_id>', methods=['GET'])
    def download_workflow_csv(workflow_id):

        workflow = WorkflowModel.query.get_or_404(workflow_id)

        excel.init_excel(app)
        extension_type = "csv"
        filename = workflow_id + "." + extension_type

        return excel.make_response_from_dict(workflow.data,
                                             file_type=extension_type,
                                             file_name=filename)

    return app
コード例 #20
0
def create_app(config):
    app = Flask(__name__, template_folder='templates', static_folder='static')
    app.config.from_object(config)
    from application.models import db
    db.init_app(app)
    return app
コード例 #21
0
ファイル: __init__.py プロジェクト: lvzhidong/ec
def _init_database(app):
    db.init_app(app)
コード例 #22
0
from application.controllers import users_controller
from application.controllers import notes_controller
from application.controllers import courses_controller
from application.controllers import home_controller
from application.controllers import messages_controller
from application.controllers import comments_controller

import json

app = Flask(__name__)
app.debug = True

# need to find a way to dynamically find the config file's path
app.config.from_pyfile("/opt/apps/notes-n-things-env/notes-n-things/config/config.py")

db.init_app(app)

# Extensions like Flask-SQLAlchemy now know what the "current" app
# is while within this block. Therefore, you can now run........
with app.app_context():        
        db.create_all()

# Create the Flask-Restless API manager.
restless_manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)

messages_controller.create_message_api(restless_manager)
home_controller.create_home_api(restless_manager)
users_controller.create_user_api(restless_manager)
notes_controller.create_note_api(restless_manager)
courses_controller.create_course_api(restless_manager)
comments_controller.create_comment_api(restless_manager)