예제 #1
0
파일: app.py 프로젝트: prashankMT/Todo-Api
def create_app(env_name):
    """
		Create App
		:param env_name:
		:return:
		"""

    # APP initialization
    app = Flask(__name__)
    print(app_config[env_name])
    app.config.from_object(app_config[env_name])

    db.init_app(app)
    app.register_blueprint(user_blueprint)

    # endpoint for the base
    @app.route("/", methods=['GET'])
    def index():
        """
		endpoint
		:return:
		"""
        return "Vola!!"

    return app
예제 #2
0
파일: app.py 프로젝트: Dyqmin/fixly-clone
def create_app(config_file=None, settings_override=None):
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@db:5432/{POSTGRES_DB}'

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

    init_api(app)

    return app
예제 #3
0
def create_tables():
    """
    This lines of code will make sure that before the first
    call to the database, the `database structure` is being
    created automatically.
    :return:
    """
    from src.db import db
    with app.app_context():
        db.init_app(app)
        db.create_all()
예제 #4
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile('config.py')

    login_manager.init_app(app)
    db.init_app(app)
    rq.init_app(app)

    if app.config['DEBUG']:

        @app.after_request
        def after(resp):
            if resp.status_code >= 400:
                print(resp.get_data().decode())
            return resp

    app.register_blueprint(bp_app, url_prefix='/api')
    app.register_blueprint(bp_tele)
    app.register_blueprint(bp_web)

    return app
예제 #5
0
def create_tables():
    from src.db import db
    db.init_app(app)
    db.create_all()
예제 #6
0
파일: app.py 프로젝트: cvioan/itlaw
from flask_jwt import JWT

from src.security import authenticate, identity
from src.resources.user import UserRegister
from src.resources.dosar import Dosar, DosarList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['PROPAGATE_EXCEPTIONS'] = True
app.secret_key = 'jose'
api = Api(app)


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


jwt = JWT(app, authenticate, identity)  # /auth

api.add_resource(Dosar, '/dosar')
api.add_resource(DosarList, '/dosare')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    from src.db import db

    db.init_app(app)
    app.run(port=5000, debug=True)
예제 #7
0
def create_tables():
    from src.db import db
    with app.app_context():
        db.init_app(app)
        db.create_all()
def create_app(mode: str = 'DEPLOY') -> Flask:
    """
    Creates a Flask app with a specific configuration.
    Default: PRODUCTION.
    It also initialises a data base, API & JWT.
    Defines endpoints and custom http-status-code-error-handler.

    :param mode: 'PRODUCTION', 'DEVELOP', 'TEST'
    :return: Flask app.
    """
    app = Flask(__name__)

    # Check mode
    if mode not in modes:
        mode = 'DEPLOY'

    # Load config
    app.config.from_object("config." + modes[mode])
    app.app_context().push()

    # Initialization of logger
    log = getLogger(app.config['LOGGER_NAME'])
    basicConfig(filename=app.config['LOG_FILE'],
                filemode=app.config['LOG_FILEMODE'],
                level=app.config['LOG_LEVEL'])

    # Initialization of .db, JWT & API
    log.debug("*** INIT START *** {}".format(ctime()))
    db.init_app(app=app)
    jwt = JWTManager(app=app)
    api = Api(app=app)

    @jwt.additional_claims_loader
    def add_claims_to_jwt(identity: int) -> dict:
        """
        Whenever we create a new JWT-token, this function is called to check,
        if we should add any extra data ("claims") to that JWT as well.

        :param identity: Int of the user-id.
        :return: {'is_admin': Bool}
        """
        if identity == app.config['ADMIN']:
            return {'is_admin': True}
        return {'is_admin': False}

    @jwt.token_in_blocklist_loader
    def check_if_token_in_blacklist(jwt_headers, jwt_payload):
        """
        Check it 'jti' is in the BLACKLIST set().
        If true, request will be reverted to the 'revoked_token_callback'.
        """
        return jwt_payload['jti'] in BLACKLIST

    @jwt.expired_token_loader
    def expired_token_callback():
        return jsonify({
            'description': 'The token has expired.',
            'error': 'token_expired'
        }), 401

    @jwt.invalid_token_loader
    def invalid_token_callback(error):
        return jsonify({
            'description': 'Signature verification failed.',
            'error': 'token_invalid'
        }), 401

    @jwt.unauthorized_loader
    def missing_token_callback(error):
        return jsonify({
            'description': 'Request does not contain any access token.',
            'error': 'authorization_required'
        }), 401

    @jwt.needs_fresh_token_loader
    def token_not_fresh_callback(jwt_headers, jwt_payload):
        return jsonify({
            'description': 'Token is NOT fresh.',
            'error': 'fresh_token_required'
        }), 401

    @jwt.revoked_token_loader
    def revoked_token_callback(jwt_headers, jwt_payload):
        return jsonify({
            'description': 'Token has been revoked.',
            'error': 'token_revoked'
        }), 401

    @app.before_first_request
    def create_tables() -> None:
        """
        Creates all the tables (it sees) in a .db file.
        """
        db.create_all()

    @app.errorhandler(404)
    def page_not_found(error) -> tuple:
        log.warning("page_not_found: {}".format(ctime()))
        return render_template('error-404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(error) -> tuple:
        log.error("internal_server_error: {}".format(ctime()))
        return render_template('error-500.html'), 500

    # Endpoints
    api.add_resource(User, '/user/<int:user_id>')
    api.add_resource(UserLogin, '/login')
    api.add_resource(UserLogout, '/logout')
    api.add_resource(UserRegister, '/register')
    api.add_resource(Item, '/item/<string:name>')
    api.add_resource(ItemList, '/items')
    api.add_resource(Store, '/store/<string:name>')
    api.add_resource(StoreList, '/stores')
    api.add_resource(TokenRefresh, '/refresh')

    log.debug("*** INIT COMPLETED *** {}".format(ctime()))
    return app
예제 #9
0
def create_app(config_name):

    app = Flask(__name__)
    api = Api(app)
    cors = CORS(app)
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
    app.config.from_object(app_config[config_name])

    jwt = JWTManager(app)

    @jwt.user_claims_loader
    def add_claims_to_jwt(identity):
        from user.models import User
        #TODO: change condition to check if user is admin
        if identity == 1:
            return {'is_admin': True}
        return {'is_admin': False}

    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(decrypted_token):
        from security.blacklist.models import TokenBlacklist

        return decrypted_token['jti'] in TokenBlacklist.get_all()

    @jwt.expired_token_loader
    def expired_token_callback():
        return jsonify({
            "description": "The token has expired",
            "error": "token_expired"
        }), 401

    @jwt.invalid_token_loader
    def invalid_token_callback(error):
        return jsonify({
            "description": "Signature verification failed",
            "error": "invalid_token"
        }), 401

    @jwt.unauthorized_loader
    def missing_token_callback(error):
        return jsonify({
            "description": "Request does not contain an access token",
            "error": "unauthorized_required"
        }), 401

    @jwt.needs_fresh_token_loader
    def token_not_fresh_call():
        return jsonify({
            "description": "The token has been revoked",
            "error": "token_revoked"
        }), 401

    ### resource area ###

    from user.resources import (UserRegisterAPI, UserLoginAPI, UserAPI,
                                UserLogoutAPI, TokenRefreshAPI)
    api.add_resource(UserRegisterAPI, '/api/v1/register')
    api.add_resource(UserLoginAPI, '/api/v1/login')
    api.add_resource(UserLogoutAPI, '/api/v1/logout')
    api.add_resource(TokenRefreshAPI, '/api/v1/refresh')
    api.add_resource(UserApi, '/api/v1/user')

    db.init_app(app)

    return app