Ejemplo n.º 1
0
def create_app(env_name):
    """

    Create app

    """

    # app initiliazation
    app = Flask(__name__)
    app.config.from_object(app_config[env_name])
    db.init_app(app)
    app.register_blueprint(job_blueprint, url_prefix='/modulelog')
    app.register_blueprint(jobid_blueprint, url_prefix='/modulelogid')

    @app.route('/', methods=['GET'])
    def index():
        """

        example endpoint

        """

        return 'Congratulations! Your first endpoint is working'

    return app
Ejemplo n.º 2
0
def setup_app(app):
    # cria as tabelas se elas nao existirem ainda
    @app.before_first_request
    def create_tables():
        db.create_all()

    #inicia base de dados
    db.init_app(app)

    #congirura blueprint para as rotas com namespace
    blueprint = Blueprint('api', __name__, url_prefix='/api')

    #adiciona blueprint no app
    api.init_app(blueprint)
    #chama a funcao que vai congigurar as API
    init_config(app)
    #adiciona namespaces to blueprint
    api.add_namespace(author_namespace)
    api.add_namespace(post_namespace)

    #registra blueprint
    app.register_blueprint(blueprint, url_prefix='')

    if __name__ == "__main__":
        app.run(debug=True, host='0.0.0.0')
Ejemplo n.º 3
0
def create_app(config_file='config.py'):
    app = Flask(__name__)

    app.config.from_pyfile(config_file)

    db.init_app(app)

    # Blueprints
    app.register_blueprint(auth.bp)
    app.register_blueprint(dashboard.bp)

    # Index page
    @app.route('/')
    def index():
        return redirect(url_for('auth.sign_in'))

    # DB Creation
    from src.models import users

    @app.route('/create-db')
    def create_db():
        db.create_all()
        return "DB Created!"

    return app
Ejemplo n.º 4
0
def create_app():
    flask_app = Flask(__name__)
    flask_app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_CONNECTION_URI
    flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    flask_app.app_context().push()
    db.init_app(flask_app)
    db.create_all()
    return flask_app
Ejemplo n.º 5
0
def create_simple_app():
    app = Flask(__name__)
    logging.basicConfig(format="%(asctime)s %(levelname)s [%(module)s %(lineno)d] %(message)s",
                        level=app.config['LOG_LEVEL'])
    app.config.from_envvar("CONFIG")    

    db.init_app(app)

    return app
Ejemplo n.º 6
0
def create_app():
    app = Flask(__name__)

    config_app(app)
    db.init_app(app)

    api = Api(app)
    create_api(api)

    return app
Ejemplo n.º 7
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['DEBUG'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///{}".format(
            os.path.join(project_dir, TEST_DB))
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        app.config['PAGE_SIZE'] = 10
        db.init_app(app)
        self.app = app.test_client()

        self.assertEqual(app.debug, False)
Ejemplo n.º 8
0
def create_app():
    """This is an application factory"""
    app = Flask(__name__)
    app.config.from_object("src.config.BaseConfig")
    CORS(app)

    db.init_app(app)
    jwt.init_app(app)

    app.register_blueprint(api, url_prefix="/api")

    return app
Ejemplo n.º 9
0
def create_app(env_name):
    # Initialize app
    app = Flask(__name__)
    CORS(app)

    app.config.from_object(app_config[env_name])

    db.init_app(app)

    app.register_blueprint(api_bp, url_prefix='/api')

    return app
Ejemplo n.º 10
0
def create_app(env):
    app = Flask(__name__)

    from config import app_config
    app.config.from_object(app_config[env])

    from src import api_bp
    app.register_blueprint(api_bp)

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

    return app
Ejemplo n.º 11
0
    def setUpClass(cls):
        from src.app import application
        from src.models import db
        from src import settings
        application.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://{0:s}:{1:s}@{2:s}:{3:d}/{4:s}'.format(
            settings.DB_USER, settings.DB_PASS, settings.DB_HOST, settings.DB_PORT, settings.DB_NAME)
        application.config['TESTING'] = True

        db.init_app(application)
        db.create_all(app=application)

        cls.test_app = application.test_client()
        cls.db = db
        cls.application = application
Ejemplo n.º 12
0
 def setUp(self):
     #create app
     self.app = create_test_app()
     #init with app test1
     db.init_app(self.app)
     #bind context
     self.app.app_context().push()
     #create instance for tests
     self.instance = Inventory(**{
         "value"         : "+55 86 90000-0000",
         "monthyPrice"   : 15,
         "currency"      : "R$",
         "setupPrice"    : 25,
     })
     self.instance.save()
Ejemplo n.º 13
0
def create_app(config_object):
    """Application factory function"""
    app = Flask(__name__, static_folder=None, template_folder=None)
    app.config.from_object(config_object)

    app.register_blueprint(views)
    app.register_blueprint(recycles)
    app.register_blueprint(users)

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

    return app
Ejemplo n.º 14
0
def create_app():
    """
    Create a instance of Flask App
    """
    app = Flask(__name__)
    #set config
    app.config.from_object('config')
    #start db
    db.init_app(app)

    #set blueprints
    app.register_blueprint(inventory_blueprint, url_prefix='/api/v1/inventory')

    #handlers
    app.register_error_handler(500, handle_internal_server_error)
    return app
Ejemplo n.º 15
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)

    # DO NOT deploy this application to a production environment without first adjusting
    # the CORS settings
    CORS(app)

    # Initialize extensions
    db.init_app(app)
    migrate.init_app(app, db)

    # Initialize blueprints
    app.register_blueprint(root_blueprint)
    app.register_blueprint(campaign_blueprint)

    return app
Ejemplo n.º 16
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    with app.app_context():
        db.init_app(app)
        migrate.init_app(app, db)
        app.register_blueprint(errors.bp)
        app.register_blueprint(actors.bp)
        app.register_blueprint(movies.bp)

        @app.route('/')
        @app.route('/api')
        def index():
            return jsonify({'message': 'Welcome to the casting agency API'})

    return app
Ejemplo n.º 17
0
    def setUpClass(self):
        """Excuted in the beginning of the test, the target of this test is that all tests run in order at once """
        """Define test variables and initialize src."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "casting_agency_test"
        self.database_path = "postgresql://*****:*****@{}/{}".format('localhost:5432', self.database_name)

        # binds the src to the current context
        self.new_actor = {"name": "Markos24", "age": 23, "gender": "Male"}
        self.new_movie = {"title": "the real stuff", "release_date": "08/20/2020"}
        setup_db(self.app, self.database_path)

        with self.app.app_context():
            db.init_app(self.app)
            # create all tables
            db.drop_all()
            db.create_all()
Ejemplo n.º 18
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False

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

            example_user = User(id=1,
                                email="*****@*****.**",
                                username="******")
            example_user.set_password("111")
            db.session.merge(example_user)

            db.session.commit()

        self.app = app.test_client()
Ejemplo n.º 19
0
def create_app(env_name):

    app = Flask(__name__)

    app.config.from_object(app_config[env_name])

    db.init_app(app)

    app.register_blueprint(question_blueprnt, url_prefix='/api/v1/questions')
    app.register_blueprint(response_blueprint, url_prefix='/api/v1/responses')

    @app.route('/', methods=['GET'])
    def index():
        # question = QuestionModel.get_all_question()
        # #  testing endpoint
        # req_data = request.get_json()
        return 'endpoint is working'

    return app
Ejemplo n.º 20
0
def create_app(env_name):

    app = Flask(__name__)
    app.config.from_object(app_config[env_name])

    bcrypt.init_app(app)
    db.init_app(app)

    app.register_blueprint(user_blueprint, url_prefix='/garden/v1/users')
    app.register_blueprint(device_blueprint, url_prefix='/garden/v1/devices')

    docs = FlaskApiSpec(app)
    docs.register(devices.create, blueprint=device_blueprint)

    @app.route('/', methods=['GET'])
    def index():
        return 'blah blah blah'

    return app
Ejemplo n.º 21
0
def create_app():
    # create flask app
    app = Flask(__name__)

    app.config.from_envvar("CONFIG")
            
    # allow any origin for testing and development environments
    if app.config["TESTING"] or app.config["DEVELOPMENT"]:
        CORS(app) 

    # configure logger
    logging.basicConfig(format="%(asctime)s %(levelname)s [%(module)s %(lineno)d] %(message)s", level=app.config['LOG_LEVEL'])

    # init sqlalchemy db connection
    db.init_app(app)
    # db.create_all()

    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(jokes, url_prefix='/jokes')

    return app
Ejemplo n.º 22
0
def build_api():
    api_build = Flask(__name__)
    CORS(api_build, supports_credentials=True)
    api_build.url_map.strict_slashes = False  # critical to come before build_blueprints

    if api_build.config['ENV'] == 'development':
        print(bcolours.OKGREEN + "\n %% DEV %% \n" + bcolours.ENDC)
        api_build.config.from_object('config.DevelopmentConfig')
    elif api_build.config['ENV'] == 'testing':
        print(bcolours.WARNING + "\n %% TEST %% \n" + bcolours.ENDC)
        api_build.config.from_object('config.TestingConfig')
    elif api_build.config['ENV'] == 'production':
        print(bcolours.OKBLUE + "\n %% PROD %% \n" + bcolours.ENDC)
        api_build.config.from_object('config.ProductionConfig')
    else:
        raise RuntimeError('CONFIGURATION STARTUP ERROR')

    db.init_app(api_build)
    build_blueprints(api_build)
    build_jwt_helpers(JWTManager(api_build))
    Migrate(api_build, db)
    return api_build
Ejemplo n.º 23
0
def create_app(env_name):
    """
  Create the app
  """
    # initialize the app
    app = Flask(__name__)

    app.config.from_object(app_config[env_name])

    app.register_blueprint(api_v1)
    app.register_blueprint(user_api)

    # initialize bcrypt
    bcrypt.init_app(app)

    # initialize the database
    db.init_app(app)

    # # initialize migration scripts
    # Migrate(app, db)

    return app
Ejemplo n.º 24
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='sridhar')

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    @app.route('/hello')
    def hello():
        return "Hello World"

    from src.models import db
    from src.controllers import auth
    db.init_app(app)
    app.register_blueprint(auth.auth_blueprint)

    from src.controllers import posts
    app.register_blueprint(posts.bp)
    app.add_url_rule('/', endpoint="index")
    CORS(app)
    return app
Ejemplo n.º 25
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(app_config[config_name])
    app.register_blueprint(product_api, url_prefix="/api")
    app.register_blueprint(variants_api, url_prefix="/api")
    app.register_blueprint(variants_property_api, url_prefix="/api")
    app.register_blueprint(branch_api, url_prefix="/api")
    app.register_blueprint(user_api, url_prefix="/api")
    db.init_app(app)
    bcrypt.init_app(app)

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

    migrate = Migrate(app, db)
    from src.models.branch_model import Branch
    from src.models.product_model import Product
    from src.models.variants_model import Variants
    from src.models.variants_property_model import VariantsProperty

    return app
Ejemplo n.º 26
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile(SETTINGS_FILE)

    @app.before_first_request
    def create_db():
        db.create_all()

    if not os.getenv('SECRET'):
        raise EnvironmentError(
            'The secret key is required. Pls add to the environment in the variable "SECRET".'
        )

    if not os.getenv('SQLALCHEMY_DATABASE_URI'):
        raise EnvironmentError(
            'The environment variable SQLALCHEMY_DATABASE_URI is required.')

    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv(
        'SQLALCHEMY_DATABASE_URI')
    app.secret_key = os.getenv('SECRET')
    db.init_app(app)
    api.init_app(app)
    JWTManager(app)
    return app
Ejemplo n.º 27
0
from flask import Flask
from flask_migrate import Migrate
from src.models import db, Usuario, Producto, Tienda, Suscripcion
import json
import os

# iniciar la aplicación
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# iniciar la sesión de sqlalchemy - mysql
MIGRATE = Migrate(app, db)
db.init_app(app)
with app.app_context():
    # cargar data de un archivo .json con la información de los objetos a crear
    with open("./baseline_data.json") as data_file:
        data = json.load(data_file)
        # crear esos objetos y guardar en bdd
        for tienda in data["tienda"]:
            nuevo_tienda = Tienda.nuevo(
                tienda["nombre_tienda"], tienda["correo_tienda"],
                tienda["telefono_tienda"], tienda["foto_tienda"],
                tienda["facebook_tienda"], tienda["instagram_tienda"],
                tienda["twitter_tienda"], tienda["zona_general"],
                tienda["zona_uno"], tienda["zona_dos"], tienda["zona_tres"])
            db.session.add(nuevo_tienda)
            db.session.commit()

        for producto in data["producto"]:
            nuevo_producto = Producto.nuevo(
                producto["titulo"], producto["foto"], producto["descripcion"],
Ejemplo n.º 28
0
def create_app(env_name):
    app = Flask(__name__, static_url_path='')
    CORS(app, support_credentials=True)
    #app.config.from_object(app_config[env_name])
    app.config[
        "SQLALCHEMY_DATABASE_URI"] = "postgresql://*****:*****@database-1.cvbo289m1v6g.us-west-2.rds.amazonaws.com:5432/postgres"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["DEBUG"] = True
    db.init_app(app)

    @app.route('/api/', methods=['GET'])
    def index():
        return 'This index endpoint is working!'

    @app.route('/api/ingredients')
    @cross_origin(supports_credentials=True)
    def get_all_ingredients():
        ingredients_schema = IngredientSchema(many=True)
        return jsonify(
            ingredients_schema.dump(Ingredient.query.limit(10).all()))

    @app.route('/api/ingredient/<sought_ingredient>/<y>')
    @cross_origin(supports_credentials=True)
    def get_ingredient_by_name(sought_ingredient, y):
        ingredient_schema = IngredientSchema(many=True)
        found_ingredient = Ingredient.query.filter_by(name=sought_ingredient)
        if found_ingredient is None:
            response = {'message': 'Sorry. Ingredient does not exist.'}
            return jsonify(response), 404
        result = ingredient_schema.dump(found_ingredient)
        result_call = result[0]["name"]
        sql = text(
            f"select i.id as source_id, i.name as source_name, t.id as target_id, t.name as target, s.strength from ingredients i, similarities s, ingredients t  where t.id=s.target and i.id=s.source and i.name='{result_call}' and s.strength>{y} and i.id!=t.id order by s.strength desc"
        )
        sims = db.engine.execute(sql)
        print(sims)
        sim_results = jsonify({'ing_data': [dict(row) for row in sims]})
        print('this is the ing json', sim_results)
        return sim_results

    @app.route('/api/recipes/')
    @cross_origin(supports_credentials=True)
    def get_matching_recipes():
        schema = RawDataSchema(many=True)
        array = request.args.getlist("ing")
        num = len(array)
        string = ', '.join(str(e) for e in array)
        sql = text(
            f"select r.* from (select max(recipe_id), count(recipe_id) from ingredients i, recipe_ingredients ri  where i.id=ri.ingredient_id and i.id in ({string} ) group by recipe_id having count(recipe_id)={num}) as foo, raw_data r where foo.max=r.id;"
        )
        recipes = db.engine.execute(sql)
        if recipes is None:
            return []
        print(recipes)
        recipes_to_send = jsonify({'rec_data': [dict(row) for row in recipes]})
        print('this is the rec json', recipes_to_send)
        return recipes_to_send
        # return jsonify(schema.dump())

    @app.route('/api/recipe/<id>')
    @cross_origin(supports_credentials=True)
    def get_recipe_by_id(id):
        schema = RawDataSchema(many=False)
        # recipe = RawDataModel.query.get(id)
        # print(recipe.allData)
        return jsonify(schema.dump(RawDataModel.query.get(id)))

    @app.route('/api/json/<path:path>')
    @cross_origin(supports_credentials=True)
    def get_json(path):
        return send_from_directory('data', path)

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

    return app
Ejemplo n.º 29
0
#!/usr/local/bin/python3
"""
RESTful API
"""
import logging

import connexion

from src import SWAGGER_PATH
from src import settings
from src.config import log
from src.models import db

log.init()
logger = logging.getLogger('app')

logger.info('Path of swagger file: {path}'.format(path=SWAGGER_PATH))
app = connexion.App(__name__, specification_dir=SWAGGER_PATH)
app.add_api('employee.yaml')
application = app.app
application.config[
    'SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://{0:s}:{1:s}@{2:s}:{3:d}/{4:s}'.format(
        settings.DB_USER, settings.DB_PASS, settings.DB_HOST, settings.DB_PORT,
        settings.DB_NAME)
application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(application)
db.create_all(app=application)

if __name__ == '__main__':
    application.run(port=settings.APP_PORT)
Ejemplo n.º 30
0
 def setUpClass(cls):
     app = create_app('test')
     app.app_context().push()
     db.init_app(app)
     cls.request = app.test_client()
Ejemplo n.º 31
0
from flask import Flask

from src.models import db
from src.assets_loader import assets
from src.api import api

app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.BaseConfiguration')
app.config.from_pyfile('config.py', silent=True)

api.init_app(app)
assets.init_app(app)
db.init_app(app)

import src.controllers