Exemplo n.º 1
0
def send_report():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    with app.app_context():
        mail = Mail(app)
        q = db.session.query(User)
        # Check all users if they requested report
        for user in q:
            if user.email_frequency is None:
                continue
            # check report freq against the current time - in case worker dies the report would be send with proper freq
            # Opposed to when some counter would be used(the state of counyter would die with it)
            if int(time.time()) % user.email_frequency == 0:
                msg = Message('BeepBeep Email report',
                              sender=os.environ['EMAIL_ID'],
                              recipients=[user.email])
                msg.body = "Report from strava"
                mail.send(msg)
Exemplo n.º 2
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['GITLAB_URI'] = 'https://umcs.schneiderp.ovh'
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/gitlab_monolith'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///gitlab-monolith'

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            suser = User()
            suser.email = '*****@*****.**'
            suser.is_admin = True
            suser.set_password('ok')
            db.session.add(suser)
            db.session.commit()
    return app
Exemplo n.º 3
0
def send_all_mail():  # pragma: no cover
    print('sending')
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP
    mail = Mail(app)
    mail.init_app(app=app)
    with app.app_context():
        users = db.session.query(User).filter()
        for user in users:
            report = db.session.query(Report).filter(
                Report.runner_id == user.id).first()
            if report is not None and time(
            ) - report.timestamp >= report.choice_time:
                body = prepare_body(user, app)

                if body:
                    msg = Message('Your BeepBeep Report',
                                  sender=app.config['MAIL_USERNAME'],
                                  recipients=[user.email])
                    msg.body = body
                    mail.send(msg)
                    report.set_timestamp()
                    db.session.merge(report)
                    db.session.commit()
Exemplo n.º 4
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['STRAVA_CLIENT_ID'] = '31670'
    app.config[
        'STRAVA_CLIENT_SECRET'] = '47874ae3e3f326817f0c8391d181c67cef645482'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/runnerly'

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            tarek = User()
            tarek.email = '*****@*****.**'
            tarek.is_admin = True
            tarek.set_password('ok')
            db.session.add(tarek)
            db.session.commit()
    return app
Exemplo n.º 5
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['STRAVA_CLIENT_ID'] = os.environ['STRAVA_CLIENT_ID']
    app.config['STRAVA_CLIENT_SECRET'] = os.environ['STRAVA_CLIENT_SECRET']
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///beepbeep.db'

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.email = '*****@*****.**'
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()
    return app
Exemplo n.º 6
0
def create_app():
    app = Flask(__name__)
    app.config[
        'WTF_CSRF_SECRET_KEY'] = 'ec35ae128aa97f834ab848ecf823340875ddf483e9a535440cf68e05b3b38865'
    app.config[
        'SECRET_KEY'] = '58c8f1ffb80e7d48d936cb8a485504498fc6c5dcfce18e3de6dcd3b851ff0540'
    app.config['STRAVA_CLIENT_ID'] = os.environ['STRAVA_CLIENT_ID']
    app.config['STRAVA_CLIENT_SECRET'] = os.environ['STRAVA_CLIENT_SECRET']
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///beepbeep.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.email = '*****@*****.**'
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()
    return app
Exemplo n.º 7
0
def client():
    """ This function initialize a new DB for every test and creates the app. This function returns a tuple,
    the first element is a test client and the second is the app itself. Test client must be used for sending
    request and the app should be used for getting a context when, for example, we need to query the DB.
    I haven't found a more elegant way to do this."""
    app = create_app()
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db_fd, app.config['DATABASE'] = tempfile.mkstemp()
    print(app.config['DATABASE'])
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE']
    app.config['TESTING'] = True
    app.config[
        'WTF_CSRF_ENABLED'] = False  # disable CSRF validation -> DO THIS ONLY DURING TESTS!
    client = app.test_client()

    db.create_all(app=app)
    db.init_app(app=app)
    #with app.app_context():
    #db.engine.execute(_data_sql)
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.email = '*****@*****.**'
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

    yield client, app

    os.close(db_fd)
    os.unlink(app.config['DATABASE'])
Exemplo n.º 8
0
def create_celery_app():
    """
    This application create the flask app for the worker
    Thanks https://github.com/nebularazer/flask-celery-example
    """
    ## redis inside the http is the name of network that is called like the containser
    ## a good reference is https://stackoverflow.com/a/55410571/7290562
    BACKEND = "redis://{}:6379".format("rd01")
    BROKER = "redis://{}:6379/0".format("rd01")
    if _CELERY is False:
        return Celery(__name__, backend=BACKEND, broker=BROKER)
    app = Flask(__name__)
    app.config["WTF_CSRF_SECRET_KEY"] = "A SECRET KEY"
    app.config["SECRET_KEY"] = "ANOTHER ONE"
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db/gooutsafe.db"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

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

    celery_app = Celery(app.import_name, backend=BACKEND, broker=BROKER)

    # celery.conf.update(app.config)

    class ContextTask(celery_app.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery_app.Task = ContextTask

    return celery_app
Exemplo n.º 9
0
def do_task():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    return []
Exemplo n.º 10
0
def fetch_all_runs():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    return runs_fetched
Exemplo n.º 11
0
def create_context():
    global _APP
    # lazy init
    print(_APP)  #for testing shows what kind of app we use
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
        _APP = app
    else:
        app = _APP
    return app
Exemplo n.º 12
0
def create_app(debug=False):
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # DEBUGGING AND TESTING
    app.config['SQLALCHEMY_ECHO'] = False
    app.config['TESTING'] = debug
    app.config['LOGIN_DISABLED'] = True
    app.config['WTF_CSRF_ENABLED'] = False

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

        q = db.session.query(Story).filter(Story.id == 1)
        story = q.first()
        if story is None:
            example = Story()
            example.text = 'Trial story of example admin user :)'
            example.likes = 42
            example.author_id = 1
            example.dicenumber = 6
            example.roll = {
                'dice': ['bike', 'tulip', 'happy', 'cat', 'ladder', 'rain']
            }
            example.date = datetime.datetime(2019, 11, 5)
            db.session.add(example)
            db.session.commit()

    return app
Exemplo n.º 13
0
def fetch_all_runs():
    from monolith.app import app
    db.init_app(app)
    run_fetched = {}

    with app.app_context():
        q = db.session.query(User)
        for user in q:
            if user.strava_token is None:
                continue
            print('Fetching Strava for %s' % user.email)
            run_fetched[user.id] = fetch_runs(user)

    return run_fetched
Exemplo n.º 14
0
def test_app():
    app = create_app()

    app.config[
        'WTF_CSRF_ENABLED'] = False  #this has been disabled to allows testing of forms
    temp_db, app.config['DATABASE'] = tempfile.mkstemp()
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE']

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

    yield app, app.test_client()

    os.close(temp_db)
Exemplo n.º 15
0
def create_testing_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['STRAVA_CLIENT_ID'] = os.environ['STRAVA_CLIENT_ID']
    app.config['STRAVA_CLIENT_SECRET'] = os.environ['STRAVA_CLIENT_SECRET']
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///beepbeeptest.db'
    app.config['TESTING'] = True

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    return app
Exemplo n.º 16
0
def create_app():
    app = Flask(__name__)
    # App
    app.config[
        'SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # suppress pytest warning
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['STRAVA_CLIENT_ID'] = os.environ['STRAVA_CLIENT_ID']
    app.config['STRAVA_CLIENT_SECRET'] = os.environ['STRAVA_CLIENT_SECRET']
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///beepbeep.db'

    # Mail
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USERNAME'] = os.environ['MAIL_USERNAME']
    app.config['MAIL_PASSWORD'] = os.environ['MAIL_PASSWORD']
    app.config['MAIL_USE_TLS'] = False
    app.config['MAIL_USE_SSL'] = True

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

    from monolith.database import db, User, Report
    db.init_app(app)
    login_manager.init_app(app)
    db.create_all(app=app)

    # create a first admin user
    with app.app_context():
        app.register_error_handler(401, render_error_page)
        app.register_error_handler(403, render_error_page)
        app.register_error_handler(404, render_error_page)
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.email = '*****@*****.**'
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()
    return app
Exemplo n.º 17
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///gooutsafe.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

        q = db.session.query(Restaurant).filter(Restaurant.id == 1)
        restaurant = q.first()
        if restaurant is None:
            example = Restaurant()
            example.name = 'Trial Restaurant'
            example.likes = 42
            example.phone = 555123456
            example.lat = 43.720586
            example.lon = 10.408347
            db.session.add(example)
            db.session.commit()

    return app
Exemplo n.º 18
0
def fetch_all_runs():
    global _APP
    # lazy init
    if _APP is None:
        from .app import app
        db.init_app(app)
        _APP = app
    else:
        app = _APP

    runs_fetched = {}

    with app.app_context():
        q = db.session.query(User)
        for user in q:
            if user.strava_token is None:
                continue
            runs_fetched[user.id] = fetch_runs(user)

    return runs_fetched
Exemplo n.º 19
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db'

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

        q = db.session.query(Story).filter(Story.id == 1)
        story = q.first()
        if story is None:
            example = Story()
            example.text = 'Trial story of example admin user :)'
            example.likes = 42
            example.author_id = 1
            print(example)
            db.session.add(example)
            db.session.commit()

    return app
Exemplo n.º 20
0
def fetch_all_runs():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    runs_fetched = {}

    with app.app_context():
        q = db.session.query(User)
        for user in q:
            if user.strava_token is None:
                continue
            print('Fetching Strava for %s' % user.email)
            runs_fetched[user.id] = fetch_runs(user)

    return runs_fetched
Exemplo n.º 21
0
def fetch_all_groups():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    groups_fetched = {}

    with app.app_context():
        q = db.session.query(User)
        for user in q:
            if user.gitlab_token is None:
                continue
            print('Fetching Gitlab Groups for %s' % user.email)
            groups_fetched[user.id] = fetch_groups(user)

    return groups_fetched
Exemplo n.º 22
0
def create_app(debug=False):
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # DEBUGGING AND TESTING
    app.config['SQLALCHEMY_ECHO'] = False
    app.config['TESTING'] = debug
    app.config['LOGIN_DISABLED'] = True
    app.config['WTF_CSRF_ENABLED'] = False

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    return app
Exemplo n.º 23
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    # app.config['STRAVA_CLIENT_ID'] = 29641
    # app.config['STRAVA_CLIENT_SECRET'] = "097321492b94a769fe8be68a50ab2a780f30b6dc"

    app.config['STRAVA_CLIENT_ID'] = os.environ['STRAVA_CLIENT_ID']
    app.config['STRAVA_CLIENT_SECRET'] = os.environ['STRAVA_CLIENT_SECRET']
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///beepbeep.db'
    app.config['MAIL_SERVER']='smtp.gmail.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USERNAME'] = os.environ['EMAIL_ID']
    app.config['MAIL_PASSWORD'] = os.environ['EMAIL_PASS']
    app.config['MAIL_USE_TLS'] = False
    app.config['MAIL_USE_SSL'] = True




    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.email = '*****@*****.**'
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()
    return app
Exemplo n.º 24
0
def create_app(test=False,
               database=DATABASE_NAME,
               login_disabled=False,
               test_telegram=False):
    '''
    Prepares initializes the application and its utilities.
    '''
    app = Flask(__name__)
    Bootstrap(app)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['CELERY_BROKER_URL'] = 'redis://*****:*****@localhost'
    # The address of the SMTP server
    app.config['SMTP_SERVER_ADDRESS'] = 'localhost'
    # The port of the SMTP server
    app.config['SMTP_SERVER_PORT'] = 8025
    app.config['CELERY_TIMEZONE'] = 'Europe/Rome'
    app.config['PERMANENT_SESSION_LIFETIME'] = dt.timedelta(minutes=120)
    app.config['SQLALCHEMY_DATABASE_URI'] = database
    app.config['LOGIN_DISABLED'] = login_disabled
    app.config['CELERYBEAT_SCHEDULE'] = {
        'monthly-digest': {
            'task': 'monolith.task.send_digest',
            # Scheduled for the first day of each month
            'schedule': crontab(day_of_month='1'),
            # Scheduled every 10 seconds
            # 'schedule': 10.0,
        }
    }

    if test:
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['CELERY_ALWAYS_EAGER'] = True
        app.config['SMTP_SERVER_ADDRESS'] = 'localhost'
        app.config['SMTP_SERVER_PORT'] = 8025
        # Disables periodic task
        app.config['CELERYBEAT_SCHEDULE'] = {}
    if test_telegram:
        app.config['TELEGRAM_TESTING'] = True

    # Celery initialization
    celery = celeryapp.create_celery_app(app)
    celeryapp.celery = celery

    # Initialization of the DB and login manager
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = '/login'
    db.create_all(app=app)

    if not test or (test and test_telegram):
        # initialize Telegram
        create_bot(mock=test_telegram)
        updater = Updater(token, use_context=True)
        dp = updater.dispatcher

        # Add functions to the dispatcher.
        # When a function such as start is launched on telegram it will run the
        # corresponding function
        dp.add_handler(CommandHandler('start', on_start))
        dp.add_handler(CommandHandler('login', on_login))
        updater.start_polling()
        app.config['TELEGRAM_UPDATER'] = updater

    # Required to avoid circular dependencies
    from monolith.views import blueprints
    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

    # Registration of the error handlers
    from monolith.views import errors
    app.register_error_handler(400, errors.bad_request)
    app.register_error_handler(401, errors.unauthorized)
    app.register_error_handler(403, errors.forbidden)
    app.register_error_handler(404, errors.page_not_found)
    app.register_error_handler(410, errors.gone)

    # Creation of an admin user
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.username = '******'
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = dt.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

    return app
Exemplo n.º 25
0
def db_instance(app):
    db.init_app(app)
    db.create_all(app=app)
    with app.app_context():
        yield db
Exemplo n.º 26
0
def create_app(tests=False):
    app = Flask(__name__)
    app.config["WTF_CSRF_SECRET_KEY"] = "A SECRET KEY"
    app.config["SECRET_KEY"] = "ANOTHER ONE"
    if tests is False:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///gooutsafe.db"
    else:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///tests/gooutsafe.db"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    # create a first admin user
    with app.app_context():

        # create the user roles
        q = db.session.query(Role).filter(Role.id == 1)
        role = q.first()
        if role is None:
            role = Role()
            role.value = "ADMIN"
            role.label = "Admin role"
            db.session.add(role)
            role = Role()
            role.value = "OPERATOR"
            role.label = "Operator role"
            db.session.add(role)
            role = Role()
            role.value = "CUSTOMER"
            role.label = "Customer role"
            db.session.add(role)
            role = Role()
            role.value = "HEALTH"
            role.label = "Health role"
            db.session.add(role)
            db.session.commit()

        # an Admin user
        q = db.session.query(User).filter(User.email == "*****@*****.**")
        user = q.first()
        if user is None:
            admin_user = User()
            admin_user.firstname = "Admin"
            admin_user.lastname = "Admin"
            admin_user.email = "*****@*****.**"
            admin_user.phone = "3334455678"
            admin_user.dateofbirth = datetime.datetime(2020, 10, 5)
            admin_user.is_admin = True
            admin_user.set_password("admin")
            admin_user.role_id = 1
            db.session.add(admin_user)
            db.session.commit()

        # an operator
        q = db.session.query(User).filter(User.email == "*****@*****.**")
        user = q.first()
        if user is None:
            first_operator = User()
            first_operator.firstname = "Ham"
            first_operator.lastname = "Burger"
            first_operator.email = "*****@*****.**"
            first_operator.phone = "222333567"
            first_operator.is_admin = False
            first_operator.set_password("operator")
            first_operator.role_id = 2
            db.session.add(first_operator)
            db.session.commit()

        # a customer
        q = db.session.query(User).filter(User.email == "*****@*****.**")
        user = q.first()
        if user is None:
            first_customer = User()
            first_customer.firstname = "John"
            first_customer.lastname = "Doe"
            first_customer.email = "*****@*****.**"
            first_customer.phone = "111234765"
            first_customer.is_admin = False
            first_customer.set_password("customer")
            first_customer.role_id = 3
            db.session.add(first_customer)
            db.session.commit()

        # health autority
        q = db.session.query(User).filter(
            User.email == "*****@*****.**")
        user = q.first()
        if user is None:
            health_authority = User()
            health_authority.firstname = "Health"
            health_authority.lastname = "Authority"
            health_authority.email = "*****@*****.**"
            health_authority.phone = "321456783"
            health_authority.is_admin = False
            health_authority.set_password("nocovid")
            health_authority.role_id = 4
            db.session.add(health_authority)
            db.session.commit()

        # a restaurant
        q = db.session.query(Restaurant).filter(Restaurant.id == 1)
        restaurant = q.first()
        if restaurant is None:
            # load the first operator
            q = db.session.query(User).filter(
                User.email == "*****@*****.**")
            user = q.first()
            first_restaurant = Restaurant()
            first_restaurant.name = "Trial Restaurant"
            first_restaurant.likes = 42
            first_restaurant.phone = 555123456
            first_restaurant.covid_measures = "Distance between tables 2mt; Menù touch; Alcohol Gel; Only Electronic Payment"
            first_restaurant.lat = 43.720586
            first_restaurant.lon = 10.408347
            first_restaurant.owner_id = user.id
            db.session.add(first_restaurant)
            db.session.commit()

        # a table
        q = db.session.query(RestaurantTable).filter(RestaurantTable.id == 1)
        table = q.first()
        if table is None:
            # insert the first table
            q = db.session.query(Restaurant).filter(
                Restaurant.name == "Trial Restaurant")
            restaurant = q.first()
            first_table = RestaurantTable()
            first_table.restaurant_id = restaurant.id
            first_table.name = "Table 1"
            first_table.max_seats = 6
            first_table.available = True
            db.session.add(first_table)
            db.session.commit()

        # another table
        q = db.session.query(RestaurantTable).filter(RestaurantTable.id == 2)
        table = q.first()
        if table is None:
            # insert the first table
            q = db.session.query(Restaurant).filter(
                Restaurant.name == "Trial Restaurant")
            restaurant = q.first()
            second_table = RestaurantTable()
            second_table.restaurant_id = restaurant.id
            second_table.name = "Table 2"
            second_table.max_seats = 4
            second_table.available = True
            db.session.add(second_table)
            db.session.commit()

        # insert some opening hours
        q = (db.session.query(OpeningHours).filter(
            OpeningHours.restaurant_id == 1).filter(
                OpeningHours.week_day == 0))
        openinghour = q.first()
        if openinghour is None:
            q = db.session.query(Restaurant).filter(
                Restaurant.name == "Trial Restaurant")
            restaurant = q.first()
            first_opening_hours = OpeningHours()
            first_opening_hours.restaurant_id = restaurant.id
            first_opening_hours.week_day = 0
            first_opening_hours.open_lunch = datetime.time(hour=12)
            first_opening_hours.close_lunch = datetime.time(hour=15)
            first_opening_hours.open_dinner = datetime.time(hour=20)
            first_opening_hours.close_dinner = datetime.time(hour=22)
            db.session.add(first_opening_hours)
            db.session.commit()

        # insert some opening hours
        q = (db.session.query(OpeningHours).filter(
            OpeningHours.restaurant_id == 1).filter(
                OpeningHours.week_day == 2))
        openinghour = q.first()
        if openinghour is None:
            q = db.session.query(Restaurant).filter(
                Restaurant.name == "Trial Restaurant")
            restaurant = q.first()
            second_opening_hours = OpeningHours()
            second_opening_hours.restaurant_id = restaurant.id
            second_opening_hours.week_day = 2
            second_opening_hours.open_lunch = datetime.time(hour=12)
            second_opening_hours.close_lunch = datetime.time(hour=15)
            second_opening_hours.open_dinner = datetime.time(hour=20)
            second_opening_hours.close_dinner = datetime.time(hour=22)
            db.session.add(second_opening_hours)
            db.session.commit()

        # insert some opening hours
        q = (db.session.query(OpeningHours).filter(
            OpeningHours.restaurant_id == 1).filter(
                OpeningHours.week_day == 4))
        openinghour = q.first()
        if openinghour is None:
            q = db.session.query(Restaurant).filter(
                Restaurant.name == "Trial Restaurant")
            restaurant = q.first()
            third_opening_hours = OpeningHours()
            third_opening_hours.restaurant_id = restaurant.id
            third_opening_hours.week_day = 4
            third_opening_hours.open_lunch = datetime.time(hour=12)
            third_opening_hours.close_lunch = datetime.time(hour=15)
            third_opening_hours.open_dinner = datetime.time(hour=20)
            third_opening_hours.close_dinner = datetime.time(hour=22)
            db.session.add(third_opening_hours)
            db.session.commit()

        # a reservation
        q = db.session.query(Reservation).filter(Reservation.id == 1)
        reservation = q.first()
        if reservation is None:
            # insert the first table
            q = db.session.query(User).filter(
                User.email == "*****@*****.**")
            customer = q.first()
            q = db.session.query(RestaurantTable).filter(
                RestaurantTable.id == 1)
            table = q.first()
            q = db.session.query(Restaurant).filter(Restaurant.id == 1)
            restaurant = q.first()
            first_reservation = Reservation()
            first_reservation.reservation_date = datetime.datetime(2020,
                                                                   10,
                                                                   28,
                                                                   hour=12)
            first_reservation.reservation_end = (
                first_reservation.reservation_date +
                datetime.timedelta(minutes=restaurant.avg_time))
            first_reservation.customer_id = customer.id
            first_reservation.table_id = table.id
            first_reservation.people_number = 2
            db.session.add(first_reservation)
            db.session.commit()

        # insert a review
        q = db.session.query(Review).filter_by(id=1).first()
        if q is None:
            review = Review()
            q = db.session.query(Restaurant).filter(
                Restaurant.name == "Trial Restaurant")
            restaurant = q.first()

            q = db.session.query(User).filter(
                User.email == "*****@*****.**")
            user = q.first()
            review.restaurant_id = restaurant.id
            review.reviewer_id = user.id
            review.review = "ciao"
            review.stars = decimal.Decimal(4.5)

            db.session.add(review)
            db.session.commit()
    # CALCULATE_RATING_RESTAURANTS
    return app
Exemplo n.º 27
0
def create_app(test=False):
    app = Flask(__name__, static_url_path='/static')
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db'
    if test:
        app.config['TESTING'] = True
        app.config['CELERY_ALWAYS_EAGER'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    celery = celeryApp.make_celery(app)
    celeryApp.celery = celery

    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

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

    with app.app_context():
        # Create first admin user.
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

            example = Story()
            example.title = 'My first story!'
            example.rolls_outcome = '[["bike", "static/Mountain/bike.PNG"], ["bus", "static/Mountain/bus.PNG"]]'
            example.text = 'With my bike, I am faster than a bus!!!!'
            example.theme = 'Mountain'
            example.published = 1
            example.likes = 42
            example.dislikes = 5
            example.author_id = 1
            db.session.add(example)
            db.session.commit()

        # Create dice sets if missing.
        themes = retrieve_themes()
        if not themes:
            die1 = Die(
                ['angry', 'bag', 'bike', 'bird', 'crying', 'moonandstars'],
                "N/A")
            die2 = Die(['bus', 'coffee', 'happy', 'letter', 'paws', 'plate'],
                       "N/A")
            die3 = Die(
                ['caravan', 'clock', 'drink', 'mouth', 'tulip', 'whale'],
                "N/A")
            die4 = Die(
                ['baloon', 'bananas', 'cat', 'icecream', 'pencil', 'phone'],
                "N/A")
            dice_set = DiceSet([die1, die2, die3], "Mountain")
            store_dice_set(dice_set)
            dice_set = DiceSet([die2, die3, die4], "Late night")
            store_dice_set(dice_set)
            dice_set = DiceSet([die3, die1, die4], "Travelers")
            store_dice_set(dice_set)
            dice_set = DiceSet([die2, die1, die4], "Youth")
            store_dice_set(dice_set)
            die = Die(["1", "2", "3"], "test_theme")
            dice_set = DiceSet([die], "test_theme")

    return app
Exemplo n.º 28
0
def create_app():
    app = Flask(__name__)
    app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY'
    app.config['SECRET_KEY'] = 'ANOTHER ONE'
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@postgres:5432/postgres'
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URI']
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    
    # Flask-Mail configuration
    app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
    app.config['MAIL_PORT'] = 587
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USERNAME'] = '******'
    app.config['MAIL_PASSWORD'] = '******'
    app.config['MAIL_DEFAULT_SENDER'] = '*****@*****.**'
    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

    db.init_app(app)
    login_manager.init_app(app)
    try:
        db.create_all(app=app)
    except Exception as e:
        print(e)


    # TODO THIS SECTION MUST BE REMOVED, ONLY FOR DEMO
    # already tested EndPoints are used to create examples
    app.config['WTF_CSRF_ENABLED'] = False

    with app.app_context():
        
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        adm = q.first()
        if adm is None:
            try: 
                # create a first admin user 
                # test for a user defined in database.db
                example = User()
                example.email = '*****@*****.**'
                example.phone = '3333333333'
                example.firstname = 'Admin'
                example.lastname = 'Admin'
                example.set_password('admin')
                example.dateofbirth = datetime.date(2020, 10, 5)
                example.role = 'admin'           
                example.is_admin = True
                db.session.add(example)
                db.session.commit()

        

                test_client = app.test_client()

                insert_ha(db, app)
                
                for user in customers_example:
                    create_user_EP(test_client,**user)

                for user in restaurant_owner_example:
                    create_user_EP(test_client,**user)

                for usr_idx,restaurant in enumerate(restaurant_example):
                    user_login_EP(test_client, restaurant_owner_example[usr_idx]['email'], 
                                                restaurant_owner_example[usr_idx]['password'])

                    create_restaurant_EP(test_client,restaurant)

                    user_logout_EP(test_client)

            except Exception as e:
                print(e)

        

    app.config['WTF_CSRF_ENABLED'] = True

    

    return app