Exemplo n.º 1
0
def create_app(config=AppConfig):
    """Return app object given config object."""
    kwargs = dict(
        template_folder='dist',
        static_folder='dist/static',
    )

    app = Flask(__name__, **kwargs)

    CORS(app, resources={r"/api/*": {"origins": "*"}})
    app.config.from_object(config)

    app.url_map.strict_slashes = False

    # initialize error handlers
    initialize_errorhandlers(app)

    # bind app to db
    db.init_app(app)

    s3.init_app(app)

    import api.views

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

    return app
Exemplo n.º 2
0
def create_app(config=AppConfig):
    """Return app object given config object."""
    #https://zappa-ok587zsna.s3.us-east-2.amazonaws.com
    kwargs = dict(
        template_folder='dist',
        static_folder='dist/static',
        # host_matching=True,
        # static_host='https://zappa-ok587zsna.s3.us-east-2.amazonaws.com',
    )

    app = Flask(__name__, **kwargs)

    CORS(app, resources={r"/api/*": {"origins": "*"}})
    app.config.from_object(config)

    app.url_map.strict_slashes = False

    # initialize error handlers
    initialize_errorhandlers(app)

    # bind app to db
    db.init_app(app)

    bcrypt.init_app(app)

    s3.init_app(app)

    import api.views

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

    return app
Exemplo n.º 3
0
def create_app():
    # create the application object and configure
    app = Flask(__name__)
    app.config.from_pyfile('configure.py')
    with app.app_context():
        db.init_app(app)
        app.register_blueprint(api, url_prefix='/api')
        app.register_blueprint(dashboard, url_prefix='')
    return app
Exemplo n.º 4
0
def create_app():
    app = Flask(__name__,
                static_folder='../dist/static',
                template_folder='../dist')
    app.config.from_object('config.Config')
    db.init_app(app)

    app.register_blueprint(task_router, url_prefix='/api')
    CORS(app)
    return app
Exemplo n.º 5
0
def _register_database(app):
    """Register extensions.
    
    :param app: the Flask instance.
    :type app: flask.Flask.
    :returns: the configured Flask instance.
    :rtype: flask.Flask.
    """
    db.init_app(app)
    return app
Exemplo n.º 6
0
def create_app(config_object=ProdConfig):
    """ Factory function for creating application object """
    print('Initializing Flask. Config:', config_object)
    app = Flask(__name__)
    app.config.from_object(config_object)
    CORS(app, support_credentials=True)
    db.init_app(app)
    register_blueprints(app)
    register_errorhandlers(app)
    return app
Exemplo n.º 7
0
def db(request, app):
    from api.database import db

    db.init_app(app)

    def teardown():
        try:
            os.unlink(app.config["DATABASE_URI"])
        except OSError:
            pass

    request.addfinalizer(teardown)
    return db
Exemplo n.º 8
0
def create_app(env=env):
    app = Flask(__name__)
    app.url_map.strict_slashes = False  # Make url without trailing slash work.
    app.config.from_object(env_configs.get(env))
    db.init_app(app)
    ma.init_app(app)

    app.register_error_handler(404, not_found)
    app.register_blueprint(api_v1_bp, url_prefix='/api/v1')

    migrate = Migrate(app, db)

    return app
Exemplo n.º 9
0
def create_app():

    app = Flask(__name__)

    # CORS対応
    CORS(app)

    # DB設定を読み込む
    app.config.from_object('config.Config')
    db.init_app(app)

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

    return app
Exemplo n.º 10
0
def create_app():
	app = Flask(__name__)
	app.config.from_object('api.config.DatabaseConf')

	from api.database import db
	db.app = app
	db.init_app(app)

	from user.methods import user_blueprint
	app.register_blueprint(user_blueprint, url_prefix = '/user')
	from pedido.methods import pedido_blueprint
	app.register_blueprint(pedido_blueprint, url_prefix = '/pedido')	
	from laundry.methods import laundry_blueprint
	app.register_blueprint(laundry_blueprint, url_prefix = '/laundry')

	return app
Exemplo n.º 11
0
def app_factory(alt_config=None):
    """Factory app creation method 

    Args:
        alt_config: Optional Flask config
            if not provided, the production config will be used by default
    
    Returns:
        Flask application
    """

    # import the app logging module here?
    # use a central logger

    app = Flask(__name__, instance_relative_config=True)

    if alt_config is None:
        # use the default production config if separate config is not specified
        app.config.from_pyfile('flask_prod.cfg', silent=True)
    else:
        # if config specified, load that config
        app.config.from_pyfile(alt_config)

    username = app.config['USERNAME']
    password = app.config['PASSWORD']
    hostname = app.config['HOSTNAME']

    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://{0}:{1}@{2}:5432/postgres'.format(username, password, hostname)

    db.init_app(app)

    with app.app_context():
        from api.healthz import healthz
        from api.newsarticle import newsarticle
        from api.topicdoc import topicdoc
        from api.topic import topic
        from api.articleloc import articleloc

        app.register_blueprint(healthz)
        app.register_blueprint(newsarticle)
        app.register_blueprint(topicdoc)
        app.register_blueprint(topic)
        app.register_blueprint(articleloc)
        
    return app
Exemplo n.º 12
0
def create_app():

    app = Flask(__name__)

    # CORS対応
    CORS(app)

    # DBなどの`設定`を読み込む。config.pyで定義
    app.config.from_object('config.Config')
    db.init_app(app)

    # 起動時にtoken, ログイン情報の初期化
    JWT(app, authenticate, identity)

    app.register_blueprint(codeworks_router, url_prefix='/api')
    app.register_blueprint(session_router, url_prefix='/session')
    # app.register_blueprint(discordbot, url_prefix='/discordbot')

    return app
Exemplo n.º 13
0
def create_app(config='config.py', db=db):
    app = Flask(__name__, instance_relative_config=True)
    CORS(app)

    if config:
        app.config.from_pyfile(config)
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        app.secret_key = os.environ.get('SECRET_KEY')

    from api import models
    db.init_app(app)
    db.app = app
    db.create_all()

    from api.conversation_controller import conversation_api
    app.register_blueprint(conversation_api)

    return app
Exemplo n.º 14
0
def create_app(pconfig=None, debug=False):
    app = Flask(__name__)
    app.debug = debug
    configobj = pconfig or \
        os.environ.get('PYSTRO_SETTINGS') or \
        defaultconfig
    app.config.from_object(configobj)
    app.app_context().push()
    with app.app_context():
        db.init_app(app)
        db.drop_all()
        try:
            db.create_all()
            if not app.testing:
                init_api_data(app)
        except (OperationalError, ObjectDeletedError):
            db.session.rollback()
            db.session.remove()
    setup_admin_api_routes(app)
    setup_public_api_routes(app)
    JWT(app, authenticate, identity)
    register_restaurants_blueprints(app)
    return app
Exemplo n.º 15
0
def register_extensions(app):
    restapi.init_app(app)
    db.init_app(app)
Exemplo n.º 16
0
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
from flask_cors import CORS, cross_origin
#from endpoints.fastTextVectors import load

from api.endpoints import api
from api.database import db
from api.database.db_admin import db_admin

app = Flask(__name__)
app.config.from_object('config')
CORS(app)

api.init_app(app)
db.init_app(app)
db_admin(app, db)
app.run(host='0.0.0.0', debug=True)
Exemplo n.º 17
0
def get_app():
    app = Flask(__name__, static_url_path="", static_folder="frontend")

    # trailing slashes accepted
    app.url_map.strict_slashes = False

    # Api wrapper over the Flask app with prefix "/api"
    api = Api(app, "/api")

    # Cross origin resource sharing - disable in production env.
    # CORS(app)

    # Setup the Flask-JWT-Simple extension
    app.config['JWT_SECRET_KEY'] = "super_secret_scipion_cloudify_web_jwt_key"
    app.config['JWT_EXPIRES'] = timedelta(days=1)
    jwt = JWTManager(app)

    # SQLite & SQLAlchemy DB setup
    app.config['SQLALCHEMY_DATABASE_URI'] = const.DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # change JWT default error messages
    @jwt.expired_token_loader
    def my_expired_token_callback():
        return jsonify({"message": "Access token expired, please login"}), 401

    @jwt.invalid_token_loader
    def my_invalid_token_callback(reason):
        return jsonify({"message": "Access token invalid: " + reason}), 401

    @jwt.unauthorized_loader
    def my_unauthorized_token_callback(reason):
        return jsonify({"message": "Unauthorized: " + reason}), 401

    # Serve React App
    @app.route("/", defaults={'e': None})
    # handle all routes (except API) by react
    @app.errorhandler(404)
    def react_index(e):
        return app.send_static_file('index.html')

    # API routes bellow
    @app.route("/api/authenticate")
    def authenticate():
        try:
            name = bytearray(request.environ['MELLON_name'],
                             'iso-8859-1').decode('utf-8')
            email = request.environ['MELLON_mail']
            id = request.environ['MELLON_eduPersonUniqueId']
        except:
            return "No Shibboleth data. This page should not be accessed directly!"
        return render_template("store_jwt.html",
                               token=create_jwt(identity={
                                   "id": id,
                                   "name": name,
                                   "email": email
                               }))

    #@app.route("/api/development/authenticate")
    #def authenticate_dev():
    #    name = "Tom Bombadil"
    #    email = "*****@*****.**"
    #    id = "some_shibboleth_id_of_the_user"

    #    return jsonify({
    #        "token": create_jwt(identity={ "id": id, "name": name, "email": email })
    #    })

    # current user identity
    api.add_resource(IdentityResource, "/users/me")

    # deployments
    api.add_resource(Deployments, "/deployments")
    api.add_resource(Deployment, "/deployments/<int:deployment_id>")
    api.add_resource(DeploymentLog, "/deployments/<int:deployment_id>/log")
    api.add_resource(DeploymentUndeploy,
                     "/deployments/<int:deployment_id>/undeploy")

    # templates
    api.add_resource(Templates, "/templates")
    api.add_resource(Template, "/templates/<int:template_id>")

    db.init_app(app)
    return app
Exemplo n.º 18
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from api.database import db

app = Flask(__name__)
app.config.from_object('api.config')

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

manager = Manager(app)
manager.add_command('db', MigrateCommand)

from api.users.model import User

if __name__ == '__main__':
    manager.run()
Exemplo n.º 19
0
def create_app():
    app = Flask(__name__)
    ################flask_login
    """
  login_manager = LoginManager()
  login_manager.init_app(app)
  app.config['SECRET_KEY'] = "secret"
  app.config['EXPLAIN_TEMPLATE_LOADING'] = True


  class User(UserMixin):
    def __init__(self, id, name, password):
        self.id = id
        self.name = name
        self.password = password

  # ログイン用ユーザー作成
  users = {
    1: User(1, "user01", "password"),
    2: User(2, "user02", "password")
  }

  # ユーザーチェックに使用する辞書作成
  nested_dict = lambda: defaultdict(nested_dict)
  user_check = nested_dict()
  for i in users.values():
    user_check[i.name]["password"] = i.password
    user_check[i.name]["id"] = i.id

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

  @app.route('/')
  def home():
      return Response("home: <a href='/login/'>Login</a> <a href='/protected/'>Protected</a> <a href='/logout/'>Logout</a>")

  # ログインしないと表示されないパス
  @app.route('/protected/')
  @login_required
  def protected():
      return Response('''
      protected<br />
      <a href="/logout/">logout</a>
      ''')

  # ログインパス
  @app.route('/login/', methods=["GET", "POST"])
  def login():
    if(request.method == "POST"):
      # ユーザーチェック
      if(request.form["username"] in user_check and request.form["password"] == user_check[request.form["username"]]["password"]):
        # ユーザーが存在した場合はログイン
        login_user(users.get(user_check[request.form["username"]]["id"]))
        return Response('''
          login success!<br />
          <a href="/protected/">protected</a><br />
          <a href="/logout/">logout</a>
          ''')
      else:
        return abort(401)
    else:
        return render_template("login.html")

    # ログアウトパス
    @app.route('/logout/')
    @login_required
    def logout():
        logout_user()
        return Response('''
        logout success!<br />
        <a href="/login/">login</a>
        ''')
    """
    ################

    # CORS対応
    CORS(app)

    # DB設定を読み込む
    app.config.from_object('config.Config')
    db.init_app(app)

    app.register_blueprint(user_router, url_prefix='/api')
    app.register_blueprint(karuta_router, url_prefix='/api')
    app.register_blueprint(user_score_router, url_prefix='/api')
    return app
Exemplo n.º 20
0
def add_extensions(app: Flask) -> None:
    from api.database import db

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