def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY = os.urandom(24), # flask-SQLAlchemy用の定義 # SQLALCHEMY_DATABASE_URI = 'sqlite:////app/server/instance/api.sqlite', SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'postgresql://*****:*****@db/postgres', SQLALCHEMY_TRACK_MODIFICATIONS = False, # flask_jwt_extended用の定義 JWT_SECRET_KEY = os.urandom(24), JWT_ERROR_MESSAGE_KEY = 'message', ) # enable CORS CORS(app, resources={r'/*': {'origins': '*'}}) # flask_jwt_extendedを初期化 jwt = JWTManager(app) @jwt.user_loader_callback_loader def user_loader_callback(identity): current_user = User.query.filter(User.username == identity).first() return current_user if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # sanity check route @app.route('/ping', methods=['GET']) def hello(): return jsonify('Hello, World!!') from . import db db.init_app(app) from . import auth app.register_blueprint(auth.bp) from . import note app.register_blueprint(note.bp) return app
def create_app(): app = Flask(__name__, instance_relative_config=True, static_folder='static') cred = credentials.Certificate( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config', 'ServiceAccountkey.json')) app.config['BASE_DIR'] = os.path.dirname(os.path.abspath(__file__)) if not config.DEBUG: app.config['SQLALCHEMY_DATABASE_URI'] = os.environ[ 'SQLALCHEMY_DATABASE_URI'] elif config.ENV == 'LOCAL': app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % config.POSTGRES else: app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True init_dimen() with app.app_context(): db.init_app(app) db.create_all() settings = Settings.init_setup() firebase_admin.initialize_app( cred, { 'storageBucket': settings.firebaseStorageBucket, 'databaseURL': settings.firebaseDatabaseURL }) app.config['SECRET_KEY'] = settings.secretKey if Settings.environment[settings.appEnvironment] == 'Development': app.config['DEBUG'] = True else: app.config['DEBUG'] = False app.config["POSTS_PER_PAGE"] = config.POSTS_PER_PAGE CORS(app, resources={r"*": {"origins": "*"}}) return app
def create_app(test_config=None): """ The flask application factory. To run the app somewhere else you can: ``` from api import create_app app = create_app() if __main__ == "__name__": app.run() """ app = Flask(__name__) CORS(app) # add CORS JWTManager(app) # check environment variables to see which config to load env = os.environ.get("FLASK_ENV", "dev") # for configuration options, look at api/config.py if test_config: # purposely done so we can inject test configurations # this may be used as well if you'd like to pass # in a separate configuration although I would recommend # adding/changing it in api/config.py instead # ignore environment variable config if config was given app.config.from_mapping(**test_config) else: app.config.from_object( config[env]) # config dict is from api/config.py # 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) root = logging.getLogger("core") root.addHandler(strm) # 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.db import db db.init_app(app) # initialize Flask SQLALchemy with this flask app Migrate(app, db) init_jtw_security(app) # register error Handler app.register_error_handler(Exception, all_exception_handler) # import and register blueprints # from .blueprints import register_blueprints # why blueprints http://flask.pocoo.org/docs/1.0/blueprints/ # register_blueprints(app) return app
from flask import Flask from flask_restful import Api from api.routes import initialize_routes from api.config.api_config import config from api.db import db app = Flask(__name__) app.config.update(config) api = Api(app, prefix="/api/v1") db.init_app(app) initialize_routes(api) # We only need this in development @app.before_first_request def create_tables(): db.create_all()
# Import flask and template operators from flask import Flask from flask_restful import Api from api.db import db from api.modules.todo import Todo, todo_bp app = Flask(__name__) api = Api(app) #configuring resources to use api.add_resource(Todo, '/todo') app.config.from_object('config') app.register_blueprint(todo_bp) db.init_app(app)
def setUpClass(cls): app.config['SQLALCHEMY_DATABASE_URI'] = BaseTest.SQLALCHEMY_DATABASE_URI app.config['DEBUG'] = False with app.app_context(): db.init_app(app)
with open('config.yaml', 'r') as yamlFile: config = yaml.safe_load(yamlFile) for section in config: sectionDict = config[section] for key, value in sectionDict.items(): os.environ[key] = value try: loadConfig() except FileNotFoundError: pass application = Flask(__name__) application.register_blueprint(base.bp) application.register_blueprint(search.search) application.register_blueprint(uuid.uuid) application.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://{}:{}@{}:{}/{}'.format( os.environ['DB_USER'], os.environ['DB_PSWD'], os.environ['DB_HOST'], os.environ['DB_PORT'], os.environ['DB_NAME']) application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False application.config['ELASTICSEARCH_INDEX_URI'] = '{}:{}'.format( os.environ['ES_HOST'], os.environ['ES_PORT']) application.config['SWAGGER'] = {'title': 'CCE Search'} db.init_app(application) elastic.init_app(application) docs = SwaggerDoc() swagger = Swagger(application, template=docs.getDocs())
def create_app(): app = Flask(__name__) app.config.from_object(os.getenv('APP_SETTINGS')) app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL') app.config['SECRET_KEY'] = os.getenv( 'SECRET_KEY') # secrets.token_urlsafe(24) app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['CSRF_ENABLED'] = True app.config['BCRYPT_LOG_ROUNDS'] = 15 app.config['JWT_TOKEN_LOCATION'] = ['cookies'] app.config['JWT_COOKIE_SECURE'] = False app.config['JWT_ACCESS_COOKIE_PATH'] = '/api' app.config['JWT_REFRESH_COOKIE_PATH'] = '/auth/refresh/' app.config['JWT_COOKIE_CSRF_PROTECT'] = True app.config['JWT_CSRF_CHECK_FORM'] = True app.config["JWT_BLACKLIST_ENABLED"] = True # enable blacklist feature app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = [ "access", "refresh", ] app.config["SESSION_COOKIE_HTTPONLY"] = True app.config["REMEMBER_COOKIE_HTTPONLY"] = True db.init_app(app) ma.init_app(app) migrate.init_app(app, db) bcrypt.init_app(app) jwt.init_app(app) cors.init_app(app, origins=CORS_ORIGIN_WHITELIST, supports_credentials=True) # Blueprints from api.auth import auth_bp CORS(auth_bp, origins=CORS_ORIGIN_WHITELIST, supports_credentials=True) app.register_blueprint(auth_bp) # Custom Views @app.route('/hello/') @app.route('/hello/<string:name>') def hello(name=None): if name: return jsonify({'message': 'Hi {}!'.format(name)}) return jsonify({'message': 'Hello World!'}) with app.app_context(): # Register Models from api.models import CategoryModel from api.models import ArticleModel from api.auth.models import UserModel from api.auth.models import CompanyModel from api.auth.models import RoleModel from api.auth.models import TokenModel # Register Views from api.resources import ArticleListView from api.resources import CategoryListView from api.auth.resources import RoleDetailView from api.auth.resources import RoleListView from api.auth.resources import UserView from api.auth.resources import UserRegisterView from api.auth.resources import UserLoginView from api.auth.resources import TestView from api.auth.resources import UserLogoutView from api.auth.resources import TokenRefresh from api.auth.resources import CompanyView from api.auth.resources import CompanyListView from api.auth.resources import TokenRefreshLogin from api.auth.resources import NeverTokenView from api.auth.resources import TokenView from api.auth.resources import ChangePasswordView api_article_list = ArticleListView.as_view('api_article_list') app.add_url_rule('/api/article/', view_func=api_article_list, methods=[ 'GET', 'POST', ]) api_category_list = CategoryListView.as_view('api_category_list') app.add_url_rule('/category/', view_func=api_category_list, methods=[ 'GET', 'POST', ]) user_auth = UserView.as_view('user_auth') app.add_url_rule('/auth/user/<int:user_id>', view_func=user_auth, methods=[ 'GET', 'DELETE', ]) role_list_auth = RoleListView.as_view('role_list_auth') app.add_url_rule('/auth/role/', view_func=role_list_auth, methods=[ 'GET', 'POST', ]) role_auth = RoleDetailView.as_view('role_auth') app.add_url_rule('/auth/role/<int:role_id>', view_func=role_auth, methods=[ 'GET', 'POST', ]) register_auth = UserRegisterView.as_view('register_auth') app.add_url_rule('/auth/register', view_func=register_auth, methods=[ 'POST', ]) login_auth = UserLoginView.as_view('login_auth') app.add_url_rule('/auth/login', view_func=login_auth, methods=[ 'POST', ]) test_auth = TestView.as_view('test_auth') app.add_url_rule('/auth/test', view_func=test_auth, methods=[ 'GET', ]) logout_auth = UserLogoutView.as_view('logout_auth') app.add_url_rule('/auth/logout', view_func=logout_auth, methods=[ 'POST', ]) refresh_auth = TokenRefresh.as_view('refresh_auth') app.add_url_rule('/auth/refresh', view_func=refresh_auth, methods=[ 'POST', ]) refresh_login_auth = TokenRefreshLogin.as_view('refresh_login_auth') app.add_url_rule('/auth/refresh/login', view_func=refresh_login_auth, methods=[ 'POST', ]) company_list_api = CompanyListView.as_view('company_list_api') app.add_url_rule('/auth/company/', view_func=company_list_api, methods=[ 'GET', 'POST', ]) company_api = CompanyView.as_view('company_api') app.add_url_rule('/auth/company/<int:_id>', view_func=company_api, methods=[ 'GET', 'PUT', 'DELETE', ]) test_token = TokenView.as_view('test_token') app.add_url_rule('/auth/token', view_func=test_token, methods=[ 'POST', ]) never_token = NeverTokenView.as_view('never_token') app.add_url_rule('/auth/token/never', view_func=never_token, methods=[ 'POST', ]) change_password = ChangePasswordView.as_view('change_password') app.add_url_rule('/auth/change-password', view_func=change_password, methods=[ 'POST', ]) # Authentication @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): data = TokenModel.find_by_jti(decrypted_token["jti"]) if data: return data.blacklisted else: return None @jwt.user_claims_loader def add_claims_to_access_token(identity): return { 'user': identity, 'company_id': UserModel.find_by_id(_id=identity).company_id, 'roles': [ role.name for role in UserModel.find_by_id(_id=identity).roles ] } # Handle CORS # def add_cors_headers(response): # response.headers['Access-Control-Allow-Origin'] = '*' # if request.headers['Origin'] in CORS_ORIGIN_WHITELIST: # response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] # if request.method == 'OPTIONS': # response.headers['Access-Control-Allow-Methods'] = 'DELETE, GET, POST, PUT' # headers = request.headers.get('Access-Control-Request-Headers') # if headers: # response.headers['Access-Control-Allow-Headers'] = headers # response.headers.add('Access-Control-Allow-Headers', 'X-Requested-With') # print(response.headers) # return response # # app.after_request(add_cors_headers) # Error Handlers @app.errorhandler(403) def permission_denied(e): return { "errors": "You don't have permission to view this resource" }, 403 app.register_error_handler(403, permission_denied) # Commands from api.initialize import initialize_cli app.cli.add_command(initialize_cli) return app