Example #1
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    '''Added Rest Configurations'''
    api = Api(app, default_mediatype='application/json')
    api.add_resource(WeatherAnalisys, '/analise')
    api.add_resource(WeatherCity, '/cidade')

    '''Added CORS'''
    CORS(app)

    '''Added DB'''
    db.init_app(app)
    Migrate(app, db)

    '''Added Documentation Swagger'''
    SWAGGER_URL = ''
    API_URL = '/static/swagger.json'

    swaggerui_blueprint = get_swaggerui_blueprint(
        SWAGGER_URL,
        API_URL,
        config={
            'app_name': "WEBSERVICE FLASK WEATHER"
        }
    )
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

    return app
Example #2
0
def create_app(config=None):
    """

    Args:
        config: configuration object, specifying application variables
        such as database uri.

    Returns: instanciated Flask app

    """

    app = Flask(__name__,
                template_folder='site_web/templates',
                static_folder='site_web/static')

    # Load configuration from external file, or use production config
    if config is None:
        app.config.from_object(CONFIG_FILE_PROD)
    else:
        app.config.from_object(config)

    db.init_app(app)

    if config is None:
        with app.app_context():
            populate_db(app)

    app.register_blueprint(api_blueprint, url_prefix='/api')
    jwt.init_app(app)
    app.register_blueprint(site_blueprint)
    Bootstrap(app)

    return app
Example #3
0
def create_app():
    app = Flask(__name__)
    env = os.environ.get("FLASK_ENV", "dev")
    app.config.from_object(config[env])

    # Register db to the app
    from api.models import db
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'login.login_route'
    login_manager.init_app(app)

    from api.models import Person

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



    # Register blueprints for main sections of the app

    from .blueprints.login import login as login_blueprint
    app.register_blueprint(login_blueprint)

    from .blueprints.generic import generic as generic_blueprint
    app.register_blueprint(generic_blueprint)

    return app
def create_app(testing=False):
    """Flask Application Factory

    config_override isn't current used 
    """
    # Instantiate flask app
    app = Flask(__name__, instance_relative_config=True)

    # Set configurations
    env = os.environ.get("FLASK_ENV", "development")
    app.config.from_object(_config[env])
    if testing:
        app.config["TESTING"] = True

    # TODO: Add logger

    # Register database
    db.init_app(app)

    with app.app_context():
        db.create_all(bind=["users"])

        if env == "development":
            from api.models import User

            user = User(username="******")
            user.hash_password("debug")
            db.session.add(user)
            user = User(username="******")
            user.hash_password("SelfService2020")
            db.session.add(user)
            db.session.commit()

    # Add CORS headers
    CORS(app)

    # proxy support for Nginx
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # Profile
    # app.wsgi_app = ProfilerMiddleware(app.wsgi_app)

    # Register blueprints for API endpoints
    app.register_blueprint(_main._main)
    app.register_blueprint(_filter._filter)
    app.register_blueprint(_patient_history._patient_history)
    app.register_blueprint(_patient_images._patient_images)
    app.register_blueprint(_users._users)
    app.register_blueprint(_elasticsearch._elasticsearch)

    # Register error handler
    app.register_error_handler(Exception, exception_handler)

    # Shell context
    @app.shell_context_processor
    def make_shell_context():
        return dict(db=db, models=models)

    return app
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)  # add CORS

    # check environment variables to see which config to load
    env = os.environ.get("FLASK_ENV", "dev")
    if test_config:
        # ignore environment variable config if config was given
        app.config.from_mapping(**test_config)
    else:
        app.config.from_object(config[env])
        Auth.set_key()
    celery.conf.update(app.config)
    # logging
    formatter = RequestFormatter(
        "%(asctime)s %(remote_addr)s: requested %(url)s: %(levelname)s in [%(module)s: %(lineno)d]: %(message)s"
    )
    if app.config.get("LOG_FILE"):
        fh = logging.FileHandler(app.config.get("LOG_FILE"))
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
        app.logger.addHandler(fh)

    strm = logging.StreamHandler()
    strm.setLevel(logging.DEBUG)
    strm.setFormatter(formatter)

    app.logger.addHandler(strm)
    app.logger.setLevel(logging.DEBUG)

    # decide whether to create database
    if env != "prod":
        db_url = app.config["SQLALCHEMY_DATABASE_URI"]
        if not database_exists(db_url):
            create_database(db_url)

    # register sqlalchemy to this app
    from api.models import db

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

    # import and register blueprints
    from api.views import main, games, search_page, updates

    app.register_blueprint(main.main)
    app.register_blueprint(games.games_page)
    app.register_blueprint(search_page.search_page)
    app.register_blueprint(updates.updates_page)

    # register error Handler
    app.register_error_handler(Exception, all_exception_handler)

    return app
Example #6
0
def create_app(run_filename):
    app = Flask(run_filename)
    from api.models import db
    CORS(app, support_credentials=True)
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = '''mysql://*****:*****@localhost/favourite_things'''
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    from api.routes import init_routes
    init_routes(app)
    return app
def create_celery_flask(environment=os.getenv('APP_SETTINGS', 'Production')):
    """Factory Method that creates an instance of the app with the given env.

    Args:
        environment (str): Specify the configuration to initialize app with.

    Return:
        app (Flask): it returns an instance of Flask.
    """
    app = Flask(__name__)
    app.config.from_object(configuration[environment])
    db.init_app(app)

    return app
Example #8
0
def get_test_app():
    if not LOCAL:
        return get_production_db_test_app()

    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:?cache=shared'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['TESTING'] = True
    db.init_app(app)
    app.register_blueprint(api)
    with app.app_context():
        db.drop_all()
        db.create_all()
    return app
Example #9
0
def create_app():
    app = Flask(__name__, static_folder='./web/build', static_url_path='/')
    app.config.from_object(Config)
    with app.app_context():
        db.init_app(app)

        migrate = Migrate(app, db, directory='api/migrations')

        create_app_v1(app)
        create_app_v2(app)

        @app.route('/')
        def index():
            return app.send_static_file('index.html')

        return app
Example #10
0
def init():
    app = Flask(__name__)
    user = os.environ.get("MONGO_USER")
    password = os.environ.get("MONGO_PASSWORD")
    db = os.environ.get("MONGO_DB")
    app.config["MONGODB_SETTINGS"] = {
        "db":
        db,
        "host":
        "mongodb+srv://%s:%[email protected]/test?retryWrites=true&w=majority"
        % (user, password),
    }
    from api.models import db

    db.init_app(app)  # initialize Flask MongoEngine with this flask app
    Migrate(app, db)
Example #11
0
def create_app(config_class):
    app = Flask(__name__, template_folder='../templates')
    app.config.from_object(config_class)

    db.init_app(app)
    bcrypt.init_app(app)
    compress.init_app(app)
    cors.init_app(app, origins=app.config.get('ALLOWED_HOSTS', '*'))
    environment.init_app(app, '/environment')
    health.init_app(app, '/healthcheck')
    mail.init_app(app)

    api_views = [GamesView, TurnsView, UsersView]
    for view in api_views:
        view.register(app, route_prefix='/api/')

    return app
Example #12
0
def create_app(config_name):
    '''
        App init function
    '''
    app = Flask(__name__, instance_relative_config=True)
    # Register blueprint
    prefix = '/api/v1/'
    # Register blueprints
    app.register_blueprint(USER, url_prefix=prefix)
    app.register_blueprint(BUSINESS, url_prefix=prefix+'businesses')
    app.register_blueprint(REVIEW, url_prefix=prefix)
    CORS(app, resources={r"/api/v1*": {"origins": "*"}})
    app.config.from_object(api_config[config_name])
    mail.init_app(app)
    db.init_app(app)
    Swagger(app, config=SWAGGER_CONFIG, template=TEMPLATE)
    return app
Example #13
0
import os

from api.decorators import api_wrapper

app.config.from_object(config.options)
app.secret_key = config.SECRET_KEY
app.api = api

if not os.path.exists(app.config["UPLOAD_FOLDER"]):
	os.makedirs(app.config["UPLOAD_FOLDER"])
if not os.path.exists(app.config["PFP_FOLDER"]):
	os.makedirs(app.config["PFP_FOLDER"])

with app.app_context():
	from api.models import db, Config, Users, UserActivity, Teams, Problems, Files, Solves, LoginTokens, TeamInvitations, Tickets, TicketReplies, ProgrammingSubmissions
	db.init_app(app)
	try:
		db.create_all()
	except:
		import traceback
		print traceback.format_exc()
	app.db = db

@app.route("/api")
@api_wrapper
def hello_world():
	return { "success": 1, "message": "The API is apparently functional." }

@app.route("/files/<path:path>")
def get_file(path):
	request_path = os.path.join(app.config["UPLOAD_FOLDER"], path)