示例#1
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(os.getenv('APP_SETTINGS'))
    app.url_map.strict_slashes = False
    db.init_app(app)
    CORS(app)

    app.register_blueprint(users_blueprint, url_prefix='/api/v1')

    @app.errorhandler(BadRequestException)
    def bad_request_exception(e):
        return bad_request(e)

    @app.errorhandler(404)
    def route_not_found(e):
        return not_found('route')

    @app.errorhandler(405)
    def method_not_allowed(e):
        return not_allowed()

    @app.errorhandler(Exception)
    def internal_server_error(e):
        return internal_error()

    return app
示例#2
0
def main(cfg=Config):
    app = Flask(__name__)
    app.config.from_object(cfg)  # Choose from the different configs...

    db.init_app(app)
    mail.init_app(app)

    app.register_blueprint(main_page)
    app.register_blueprint(login)
    app.register_blueprint(logout)
    app.register_blueprint(delete)
    app.register_blueprint(validate)
    app.register_blueprint(signup)
    app.register_blueprint(reset)

    app.register_blueprint(simulator_api)
    app.register_error_handler(404, page_not_found)

    @app.context_processor
    def utility_processor():
        def is_user_admin(user_id):
            try:
                user = User.query.filter_by(user_id=int(user_id)).first()
                return user.is_admin
            except:
                return False

        return dict(is_user_admin=is_user_admin)

    return app
示例#3
0
def configure_database(app):
    """
    Database configuration should be set here
    """
    # uncomment for sqlalchemy support
    from database.db import db
    db.app = app
    db.init_app(app)
示例#4
0
文件: app.py 项目: dadhia/durak
def create_app():
    app.config['SECRET_KEY'] = os.urandom(32)
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/durak?user=&password='******'SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    login_manager.init_app(app)
    socketio.init_app(app)
    bootstrap.init_app(app)
    with app.app_context():
        db.create_all()
示例#5
0
def init_app(app):
    configure_app(app)
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)
    api.add_namespace(cidadesnamespace)
    api.add_namespace(pesquisasnamespace)
    api.add_namespace(indicadoresnamespace)
    api.add_namespace(historiconamespace)
    app.register_blueprint(blueprint)

    db.init_app(app)
def create_app():

    app = Flask(__name__)
    app.config['SQLALCHEMY_ECHO'] = False
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@943@localhost:5432/postgres"

    app.register_blueprint(api_bp, url_prefix=BASE_PATH)

    db.init_app(app)

    return app
示例#7
0
def create_all():
    from database.db import db
    with app.app_context():
        db.init_app(app)
        db.create_all()
        db.session.commit()
        hashed_passwd = generate_password_hash('test12345', method='sha256')
        new_user = User(username='******',
                        email='*****@*****.**',
                        password=hashed_passwd)
        db.session.add(new_user)
        db.session.commit()
    return True
示例#8
0
def create_new_user(username, password, email):
    from database.db import db
    with app.app_context():
        db.init_app(app)
        hashed_passwd = generate_password_hash(password, method='sha256')
        new_user = User(username=username, email=email, password=hashed_passwd)
        db.session.add(new_user)
        db.session.commit()
    return True


#
# username = '******'
# password= '******'
# email = '*****@*****.**'
# create_new_user(username, password, email)
示例#9
0
def create_app():
    application = Flask(__name__)
    application.config['SQLALCHEMY_DATABASE_URI'] = (
        f'sqlite:////{SQLITE_FILE_PATH}')
    application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    CORS(application)

    db.init_app(application)

    if not db_file_exists():
        setup_database(application)

    api = Api(application)
    api.add_resource(CitiesResource, '/cities')
    api.add_resource(WeatherObservationResource, '/observations')

    return application
示例#10
0
def create_app():
    # Flask 객체 app 생성 및 config 변수 적용
    app = Flask(__name__, static_url_path="/static")
    CORS(app, supports_credentials=True)
    # app object에 config 적용
    app.config.from_object(config)
    # jwt 적용을 위한 JMTManager 적용
    jwt.init_app(app)
    # auth 객체 blueprint 등록
    app.register_blueprint(auth, url_prefix="/auth")
    # api 설정 및 적용
    api = Api(app)
    set_api_resources(api)
    # db 적용 및 migrate
    db.init_app(app)
    db.create_all(app=app)
    migrate.init_app(app, db)

    # JWT 암시적 로그인 연장을 위한 코드
    # app에 대한 모든 HTTP request 요청 실행 후 refresh
    # 여부를 확인하고 refresh 한다.
    @app.after_request
    def add_header(response):
        response.headers["X-Content-Type-Options"] = "nosniff"
        return response

    @app.after_request
    def refresh_expiring_jwts(response):
        try:
            # 현재 accessToken의 expire time이 30분 미만 남았을 때
            # accessToken을 refresh 시켜준다.
            exp_timestamp = get_jwt()["exp"]
            now = datetime.now(timezone.utc)
            target_timestamp = datetime.timestamp(now + timedelta(minutes=30))
            if target_timestamp > exp_timestamp:
                access_token = create_access_token(identity=get_jwt_identity())
                set_access_cookies(response, access_token)
            return response
        except (RuntimeError, KeyError):
            # Case where there is not a valid JWT. Just return the original response
            # 유효한 Access Token이 아닐 때는 기존 response를 그대로 보낸다.
            print("error")
            return response

    return app
示例#11
0
def create_app():
    app = Flask(__name__)

    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s [%(levelname)s] - %(message)s',
                        handlers=[
                            logging.FileHandler("api.log", 'w', 'utf-8'),
                            logging.StreamHandler()
                        ])

    CORS(app)
    app.config.from_object(Config())
    app.register_blueprint(commands.bp)
    app.register_blueprint(api.bp)

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

    return app
示例#12
0
        }, 401)


api.add_resource(User, "/api/v1/user/<int:user_id>")
api.add_resource(UserRegister, "/api/v1/register")
api.add_resource(UserLogin, "/api/v1/login")
api.add_resource(TokenRefresh, "/api/v1/refresh")
api.add_resource(AddChild, "/api/v1/addchild")
api.add_resource(ListChild, "/api/v1/child")
api.add_resource(SearchChild, "/api/v1/searchchild")
api.add_resource(Reset, "/api/v1/reset")
api.add_resource(Image, "/api/v1/image/<name>")

from database.db import db

db.init_app(app)


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


if __name__ == '__main__':

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers',
                             'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods',
示例#13
0
from resources.MasterDetails import MasterDetails
from resources.ChildDetails import ChildDetails
from resources.policy_payment_handler import PolicyPaymentsResource
from resources.policy_payment_handler import PolicyPaymentsHandler
from resources.AWSHandler import AWSPresignedURL
from resources.AWSHandler import AWSPresignedExtended
"""
automatically set the application's os environment
variables from the .env file
to avoid manual and repetitive setting of the same
"""
load_dotenv()

application = Flask(__name__)
application.config.from_object(os.environ['APP_SETTINGS'])
db.init_app(application)
CORS(application,
     resources={r"/*": {
         "origins": application.config['ALLOWED_HOSTS']
     }})
migrate = Migrate(application, db)
jwt = JWTManager(application)
# logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(asctime)s: %(message)s:')


@jwt.expired_token_loader
def expired_token_handler():
    """token sent has expired"""
    response = {
        'status_message': 'failed',
        'message': 'Your token has expired'