Exemple #1
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.json_encoder = CustomJSONEncoder
    config[config_name].init_app(app)

    db.init_app(app)
    csrf.init_app(app)
    babel.init_app(app)
    mail.init_app(app)
    breadcrumbs.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)

    if not app.debug and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    return app
Exemple #2
0
def create_base_app(config):
    """Init configuration and extensions"""
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)

    app._logger = init_logger(syslogtag=app.config['LOGGER_SYSLOGTAG'],
                              logger_name=app.config['LOGGER_NAME'])

    db.init_app(app)
    bcrypt.init_app(app)

    if app.config['DEBUG']:
        admin_extension.init_app(app)
        debug_toolbar.init_app(app)

    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous
    # Change these views to fit your app
    login_manager.login_view = "auth.login"
    login_manager.refresh_view = "auth.login"
    login_manager.login_message = "You do not have access to that page."
    login_manager.user_loader(load_user)

    app.json_encoder = CustomJSONEncoder

    return app
Exemple #3
0
def create_api_app(config=None):
    app = Flask(__name__)

    if config:
        app.config.from_pyfile(config)

    app.config['JSONSCHEMA_DIR'] = os.path.abspath('doorbot/views/api/schemas')

    app.url_map.strict_slashes = False

    jsonschema.init_app(app)
    db.init_app(app)

    from .container import container
    container.init_app(app)

    from .views.api import (
        account, auth, devices, doors, integrations, notifications, people
    )
    from .views.api.lib.json_serializer import ApiJsonEncoder

    app.json_encoder = ApiJsonEncoder
    app.register_blueprint(auth)
    app.register_blueprint(account)
    app.register_blueprint(devices)
    app.register_blueprint(doors)
    app.register_blueprint(integrations)
    app.register_blueprint(notifications)
    app.register_blueprint(people)

    return app
Exemple #4
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.secret_key = 'this is a secret'
    app.json_encoder = Jsonifier

    app.file_root = os.path.abspath(os.path.dirname(__file__))

    app.before_request(before_request)
    app.after_request(after_request)
    app.context_processor(context_processor)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

    db.init_app(app)
    with app.app_context():
        init_all()
    app.register_blueprint(admin_app, url_prefix='/admin')
    app.register_blueprint(campaign_app, url_prefix='/')
    app.register_blueprint(character_app, url_prefix='/character')
    app.register_blueprint(dm_app, url_prefix='/dm')
    app.register_blueprint(chat_app, url_prefix='/chat')
    app.register_blueprint(items_app, url_prefix='/item-type')
    app.register_blueprint(knowledge_app, url_prefix='/knowledge')

    return app
Exemple #5
0
def create_app(config_file):
    app = Flask(__name__)
    load_config(app, config_file)
    create_logging(app)
    configure_extensions(app)
    app.jobs = []  # FIXME: Need to handle scheduled jobs better.
    app.needs_catalog = {'core': needs}
    app.register_blueprint(core_main)
    app.register_blueprint(core_api)
    for plugin in load_plugins(app):
        validate_config(app, plugin=plugin)
        app.needs_catalog[plugin.name] = plugin.needs
        plugin.register_blueprints(app)
    app.json_encoder = OpsyJSONEncoder
    app.plugin_links = [{
        'name': 'About',
        'id': 'about',
        'content': 'core_main.about',
        'get_vars': None,
        'type': 'link'
    }]

    @app.before_first_request
    def load_plugin_links():  # pylint: disable=unused-variable
        for plugin in load_plugins(app):
            plugin.register_link_structure(app)

    @app.context_processor
    def inject_links():  # pylint: disable=unused-variable
        return dict(link_structures=app.plugin_links)
    return app
Exemple #6
0
def create_app(settings_override=None):
    """Returns a :class:`Flask` application instance.
    :param settings_override: a dictionary of settings to override.
    :return: Flask application instance.
    """
    app = Flask(__name__, instance_relative_config=True)
    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3sso.settings")
    app.config.from_object(settings_override)

    # something need init
    db.init_app(app)
    lm.init_app(app)
    Bootstrap(app)

    @lm.user_loader
    def load_user(user_id):
        user = UserProfile.objects.get(id=user_id)
        return user

    app.register_blueprint(bp_main)
    app.register_blueprint(bp_sso)
    app.register_blueprint(bp_api)
    app.register_blueprint(bp_api_1_0)

    for e in [500, 404]:
        app.errorhandler(e)(handle_error)

    return app
Exemple #7
0
def create_app():
    """Create an application instance."""
    cfg = os.path.join(os.getcwd(), 'config.py') if os.path.exists('config.py') else os.path.join(os.getcwd(), 'mopa/config.py')

    app = Flask(__name__)
    app.json_encoder = CustomJSONEncoder
    app.config['JSON_PRETTYPRINT_REGULAR'] = False
    app.config.from_pyfile(cfg)
    setup_logging(app)

    # initialize extensions
    db.init_app(app)
    reggie.init_app(app)
    # cors.init_app(app, resources={r"/api/*": {"origins": "*"}})

    # One line of code to cut our Flask page load times by 60%
    # https://blog.socratic.org/the-one-weird-trick-that-cut-our-flask-page-load-time-by-70-87145335f679#.8r14wvy5w
    app.jinja_env.cache = {}

    # register blueprints
    from .views import bp as api_blueprint
    app.register_blueprint(api_blueprint)

    from .tasks import bp as tasks_blueprint
    app.register_blueprint(tasks_blueprint, url_prefix='/tasks')

    return app
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.json_encoder = JSONEncoder
    config[config_name].init_app(app)

    babel = Babel(app)

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .field_storage import field_storage as field_storage_blueprint
    app.register_blueprint(field_storage_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .unis import unis as unis_blueprint
    app.register_blueprint(unis_blueprint)

    return app
Exemple #9
0
def create_app(package_name, package_path, settings_override=None,
               register_security_blueprint=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Tcc3Portal platform.

    :param package_name: application package name.
    :param package_path: application package path.
    :param settings_override: a dictionary of settings to override.
    :param register_security_blueprint: flag to specify if the Flask-Security
                                        Blueprint should be registered. Defaults
                                        to `True`.
    :return: Flask application instance.
    """
    app = Flask(package_name, instance_relative_config=True)

    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3portal.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    # something need init
    # security.init_app(app, None, register_blueprint=register_security_blueprint)
    db.init_app(app)
    bootstrap.init_app(app)
    lm.init_app(app)
    babel.init_app(app)
    sso_client.init_app(app, lm)
    TccFrontend(app)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Exemple #10
0
def create_app(config_override=None, environment=None):
    app = Flask(__name__)
    app.config['ENVIRONMENT'] = environment
    config.init_app(app)
    app.config.update(config_override or {})

    severity.init_app(app)
    key_helper.init_app(app)

    cors.init_app(app)
    compress.init_app(app)
    handlers.register(app)

    db.init_db(app)
    qb.init_app(app)
    sentry.init_app(app)

    from alerta.utils.format import CustomJSONEncoder
    app.json_encoder = CustomJSONEncoder

    from alerta.views import api
    app.register_blueprint(api)

    from alerta.webhooks import webhooks
    app.register_blueprint(webhooks)

    from alerta.auth import auth
    app.register_blueprint(auth)

    from alerta.management import mgmt
    app.register_blueprint(mgmt)

    plugins.register(app)

    return app
def create_base_app(config):
    """Init configuration and extensions"""
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)

    file_handler = SysLogHandler()
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

    db.init_app(app)
    bcrypt.init_app(app)

    if app.config['DEBUG']:
        admin_extension.init_app(app)
        debug_toolbar.init_app(app)

    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous
    # Change these views to fit your app
    login_manager.login_view = "auth.login"
    login_manager.refresh_view = "auth.login"
    login_manager.login_message = "You do not have access to that page."
    login_manager.user_loader(load_user)

    app.json_encoder = CustomJSONEncoder

    return app
Exemple #12
0
 def test_custom_json_encoder(self):
     from datetime import datetime
     from flask.json import JSONEncoder
     class JsonEncoder(JSONEncoder):
         def default(self, obj):
             if hasattr(obj, '__json__'):
                 return obj.__json__()
             if isinstance(obj, datetime):
                 return obj.isoformat()
             return super(JsonEncoder, self).default(obj)
     class Custom:
         def __init__(self, custom):
             self.custom = custom
         def __json__(self):
             return dict(custom=self.custom)
     date = datetime(2014,5,26,23,59,59)
     class DateResource(flask_restful.Resource):
         def get(self):
             return Custom(date)
     app = Flask(__name__)
     app.json_encoder = JsonEncoder
     api = flask_restful.Api(app)
     api.add_resource(DateResource, '/date')
     client = app.test_client()
     resp = client.get('/date')
     self.assertEquals(resp.data.decode(), '{"custom": "2014-05-26T23:59:59"}')
Exemple #13
0
def create_app(config):

    """A factory that returns an application object from the passed config.

    The factory accepts further configuration from ENV variables. Some simple
    checks for core configuration settings are made to raise errors early
    if vital information is missing.

    """

    import os
    from flask import Flask
    from flask.ext.babel import Babel
    from flask.ext.cors import CORS
    from flask.ext.markdown import Markdown
#    from flask.ext.assets import Environment, Bundle
    from .components import api, pages
    from .components.commons import context_processors, encoders

    app_label = 'web'

    # Get the static and template folder for the passed theme
    static_folder = os.path.join('theme', 'static')
    template_folder = os.path.join('theme', 'templates')

    # Construct app and service objects
    app = Flask(app_label, template_folder=template_folder,
                static_folder=static_folder, static_url_path='/static')
    trans = Babel()
    cors = CORS(resources=r'/api/*', allow_headers='Content-Type')
#    assets = Environment()

    # Configure the app with defaults
    app.config.from_object(config)

    # Set app core services
    trans.init_app(app)
    cors.init_app(app)
#    assets.init_app(app)
    Markdown(app)

    # Register routable components
    app.register_blueprint(api.blueprint)
    app.register_blueprint(pages.blueprint)

    # Set additional jinja2 extensions
    app.jinja_env.add_extension('jinja2.ext.do')

    # Set custom context processors
    app.context_processor(context_processors.inject_app_data)

    # Set custom encoders
    app.json_encoder = encoders.JSONEncoder

    # Register webassets bundles
#    sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css')
#    assets.register('sass', sass)

    return app
Exemple #14
0
def create_app():
  from views.index import index_view
  from views.api import api_view

  app = Flask(__name__)
  app.register_blueprint(api_view)
  app.register_blueprint(index_view)
  app.json_encoder = SetJSONEncoder
  return app
Exemple #15
0
    def create_app(self):
        app = Flask(__name__)
        app.json_encoder = _JSONEncoder
        app.secret_key = "secret"

        @app.route("/", methods=("GET", "POST"))
        def index():

            form = MyForm()
            if form.validate_on_submit():
                name = form.name.data.upper()
            else:
                name = ''

            return render_template("index.html",
                                   form=form,
                                   name=name)

        @app.route("/simple/", methods=("POST",))
        def simple():
            form = SimpleForm()
            form.validate()
            assert form.csrf_enabled
            assert not form.validate()
            return "OK"

        @app.route("/two_forms/", methods=("POST",))
        def two_forms():
            form = SimpleForm()
            assert form.csrf_enabled
            assert form.validate()
            assert form.validate()
            form2 = SimpleForm()
            assert form2.csrf_enabled
            assert form2.validate()
            return "OK"

        @app.route("/hidden/")
        def hidden():

            form = HiddenFieldsForm()
            return render_template("hidden.html", form=form)

        @app.route("/ajax/", methods=("POST",))
        def ajax_submit():
            form = MyForm()
            if form.validate_on_submit():
                return jsonify(name=form.name.data,
                               success=True,
                               errors=None)

            return jsonify(name=None,
                           errors=form.errors,
                           success=False)

        return app
Exemple #16
0
def init_app():
    """Init flask app"""

    app = Flask(__name__)
    app.config.from_object(base_config)
    # Production or local config
    app.config.from_envvar('QFOOD_CONFIG', silent = True)
    # set json encoder capable serializing MongoDB ObjectId
    app.json_encoder = JSONEncoder

    return app
 def setUp(self):
     app = Flask(__name__)
     app.session_interface = CheckerSessionInterface()
     app.json_encoder = CustomJSONEncoder
     app.config["SECRET_KEY"] = "test"
     app.add_url_rule("/<step>", view_func=TestWizard.as_view("wizard"))
     app.add_url_rule(
         "/session-expired", endpoint="base.session_expired", view_func=lambda request: "Session expired"
     )
     self.client = app.test_client()
     with self.client.session_transaction() as sess:
         sess.checker["foo"] = "bar"
Exemple #18
0
def create_app():
    flask_app = Flask(__name__)

    # load site settings from the database
    setup_settings(flask_app)

    # environment-aware configuration
    setup_config(flask_app)

    # custom NDB model serializer
    flask_app.json_encoder = NDBModelJSONEncoder

    return flask_app
Exemple #19
0
def create_app(config_from_object=None, config_from_env=None):
  """A factory function to produce a Flask application instance

  This will create the one true application, in a flexible and extensible way.
  The app is being created via a factory function in order to facilitate custom
  or manual configurations.  In this fashion, the app could be configured
  automatically by the Flask-Script file ``manage.py`` during development using
  an environment variable on a local workstation prescribing a
  ``DevelopmentConfig``, while on the production machine, it will resolve to a
  ``ProductionConfig``, or manually specified in the tests directory during set-
  up as ``TestingConfig`` as defined in the :mod:`foodtruck.config` module.

  The app will register the :mod:`foodtruck.backend` module at the endpoint
  specified by``API_ENDPOINT`` using a Flask blueprint in a self-contained
  backend sub-package, demonstrating the flexibility Flask provides.

  Args:
    config_from_object (str, optional): A string representing the name of an
      object to import
    config_from_env  (str, optional): A string representing the name of the
      environment variable to pull the name of the object to import

  Note:
    While both arguments are optional, at least **one** is mandatory.
    Otherwise, where will we get our configs??
  """
  setup_log()
  log = logging.getLogger(__name__)

  app = Flask(__name__)

  if config_from_env:
    app.config.from_object(os.environ[config_from_env])
  # While the ENVIRONMENT configures first, the config object can be used to
  # merge and overwrite settings, providing additional flexibility
  if config_from_object:
    app.config.from_object(config_from_object)

  # We'll be mounting our API right on this endpoint here:
  app.register_blueprint(api_blueprint,
                         url_prefix='/'+app.config['API_ENDPOINT'])
  app.register_blueprint(frontend_blueprint)

  # Register our JSON encoder too
  app.json_encoder = UltraJSONEncoder

  db.init_app(app)

  return app
Exemple #20
0
 def test_jsonencoder(self):
     from api import api
     app = Flask(__name__)
     app.json_encoder = api.CustomJSONEncoder
     @app.route('/test_json_basic')
     def json_basic():
         return jsonify(result='test')
     now = datetime.datetime.now()
     @app.route('/test_json_datetime')
     def json_datetime():
         return jsonify(result=now)
     @app.route('/test_json_iter')
     def json_iter():
         class Counter:
             def __init__(self, value):
                 self._value = value
                 self._current = 0
             def __iter__(self):
                 return self
             def __next__(self):
                 if self._current > self._value:
                     raise StopIteration
                 else:
                     self._current += 1
                     return self._current - 1
             def next(self):
                 return self.__next__()
         return jsonify(result=Counter(5))
     @app.route('/test_json_error')
     def json_error():
         class NewObject:
             def __init__(self, value):
                 self._value = value
         return jsonify(result=NewObject(5))
     test_app = app.test_client()
     rv = test_app.get('/test_json_basic')
     assert rv.status_code == 200
     res = json.loads(rv.data.decode('utf-8'))
     assert res == {'result': 'test'}
     rv = test_app.get('/test_json_datetime')
     assert rv.status_code == 200
     res = json.loads(rv.data.decode('utf-8'))
     assert res == {'result': now.strftime(api.time_format)}
     rv = test_app.get('/test_json_iter')
     assert rv.status_code == 200
     res = json.loads(rv.data.decode('utf-8'))
     assert res == {'result': [0, 1, 2, 3, 4, 5]}
     rv = test_app.get('/test_json_error')
     assert rv.status_code == 500
def create_app(_config='development'):
    app = Flask(__name__)

    CORS(app)

    app.config.from_object(config[_config])
    app.json_encoder = MyJSONEncoder

    from app.inventory import views
    from app.cart import views
    from app import views

    app.register_blueprint(api)

    return app
Exemple #22
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.json_encoder = AlchemyEncoder

    app.config.from_object(Config)

    DebugToolbarExtension(app)

    init_flask_config(app)
    init_extensions(app)
    init_session(app)
    init_blueprints(app)
    init_state(app)

    return app
def create_app(config_name):
    application = Flask(__name__)
    application.config['DM_ENVIRONMENT'] = config_name

    init_app(
        application,
        configs[config_name],
        db=db,
        search_api_client=search_api_client
    )

    if not application.config['DM_API_AUTH_TOKENS']:
        raise Exception("No DM_API_AUTH_TOKENS provided")

    # FIXME: The service broker adds a 'reconnect' parameter that's rejected by Postgres and
    # doesn't seem to be in the Postgres documentation anyway.  We need to patch the broker to fix
    # the username stability issue anyway.
    import os
    if 'DATABASE_URL' in os.environ:
        application.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'].replace('reconnect=true', '')

    url_prefix = application.config['URL_PREFIX']
    url_prefix_v2 = application.config['URL_PREFIX_V2']
    from .main import main as main_blueprint
    application.register_blueprint(main_blueprint, url_prefix=url_prefix)
    from .status import status as status_blueprint
    application.register_blueprint(status_blueprint, url_prefix=url_prefix)
    from .api import api as api_blueprint
    application.register_blueprint(api_blueprint, url_prefix=url_prefix_v2)
    from .admin import blueprint as admin_blueprint
    application.register_blueprint(admin_blueprint.admin)

    application.json_encoder = CustomEncoder

    # maximum POST request length http://flask.pocoo.org/docs/0.12/patterns/fileuploads/#improving-uploads
    application.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024  # 32 megabytes

    swag.init_app(application)

    if application.config['DEBUG']:
        # enable raise to raise exception on ORM misconfigured queries
        # application.config['NPLUSONE_RAISE'] = True
        application.config['NPLUSONE_LOGGER'] = logging.getLogger('app.nplusone')
        application.config['NPLUSONE_LOG_LEVEL'] = logging.ERROR
        NPlusOne(application)
        application.wsgi_app = SQLTapMiddleware(application.wsgi_app)

    return application
def create_app(config):
    """
    Application Factories - http://flask.pocoo.org/docs/patterns/appfactories/
    :param config: Path to config.py file.
    """

    app = Flask(__name__)
    app.config.from_pyfile(config)
    db.init_app(app)
    api = Api(app)

    from application.json_encoder import AlchemyEncoder
    app.json_encoder = AlchemyEncoder

    # Register middlewares here
    from application.middlewares import require_login, apply_cors_headers
    app.before_request(require_login)
    app.after_request(apply_cors_headers)

    # Register blueprints here
    from application.views import bp as bp_auth
    app.register_blueprint(bp_auth)

    from application.views import UserList, UserResource, GroupList, SubjectList, SubjectSignupList, \
        SubjectSignupResource, TermSignupAction, SettingList
    
    api.add_resource(UserList, '/api/users')
    api.add_resource(UserResource, '/api/users/<int:id>')
    api.add_resource(GroupList, '/api/groups')
    api.add_resource(SubjectList, '/api/subjects')
    api.add_resource(SubjectSignupList, '/api/subjects_signup')
    api.add_resource(SubjectSignupResource, '/api/subjects_signup/<int:subject_id>')
    api.add_resource(TermSignupAction, '/api/terms/signup')
    api.add_resource(SettingList, '/api/settings')

    # Admin panel
    from application.models import User, Group, Subject, Term, TermSignup, Setting
    from application.admin import UserAdminView, SubjectAdminView, TermAdminView, TermSignupAdminView, SettingAdminView

    admin = Admin(app)
    admin.add_view(UserAdminView(User, db.session))
    admin.add_view(ModelView(Group, db.session))
    admin.add_view(SubjectAdminView(Subject, db.session))
    admin.add_view(TermAdminView(Term, db.session))
    admin.add_view(TermSignupAdminView(TermSignup, db.session))
    admin.add_view(SettingAdminView(Setting, db.session))

    return app
Exemple #25
0
def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'THIS IS JUST A TEST WEBPAGE !'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@[email protected]/maizi'
    app.config['BABEL_DEFAULT_LOCALE'] = 'en'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    from flask.json import JSONEncoder

    class CustomJSONEncoder(JSONEncoder):
        """This class adds support for lazy translation texts to Flask's
        JSON encoder. This is necessary when flashing translated texts."""

        def default(self, obj):
            from speaklater import is_lazy_string
            if is_lazy_string(obj):
                try:
                    return unicode(obj)  # python 2
                except NameError:
                    return str(obj)  # python 3
            return super(CustomJSONEncoder, self).default(obj)

    app.json_encoder = CustomJSONEncoder

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
    Gravatar(app, size=64)
    babel.init_app(app)

    from auth import auth as auth_blueprint
    from main import main as main_blueprint
    app.register_blueprint(auth_blueprint)
    app.register_blueprint(main_blueprint)

    app.permanent_session_lifetime = timedelta(minutes=5)

    @app.template_test('current_link')
    def is_current_link(link):
        return link == request.path

    @babel.localeselector
    def get_locale():
        return current_user.locale

    return app
Exemple #26
0
def create_app(testing=False):
    app = Flask(__name__)

    try:
        app.config.from_object('config')
    except:
        app.config.from_object('configdist')
    if testing:
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False

    app.json_encoder = ExtensibleJSONEncoder
    app.secret_key = app.config['SECRET_KEY']
    app.register_blueprint(user_bp)

    csrf = CsrfProtect()
    csrf.init_app(app)

    # Initialize login manager
    login_manager.init_app(app)

    # Assets bundles: js, jsx, css
    env = Environment(app)
    root = os.path.dirname(os.path.abspath(__file__)) + '/../'
    env.load_path = [
        root + 'node_modules',
        root + 'client/style'
    ]
    env.register('css', css)

    @app.teardown_appcontext
    def shutdown_session(response):
        database.session.remove()

    @app.route('/')
    @app.route('/<path:path>')
    def index(path=None):
        """Main route for the single page app"""
        data = dict(
            user=anonymous_user_data,
            alerts=[]
        )
        if current_user.is_authenticated():
            data['user'] = current_user
        return render_template('index.html', app_data=dumps(data))

    return app
Exemple #27
0
def create_app(config_object=ProdConfig):
    """An application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

  :param config_object: The configuration object to use.
  """
    app = Flask(__name__)
    app.config.from_object(config_object)
    app.json_encoder = JSONEncoder
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)

    if app.config["ADMIN_ENABLED"]:
        register_admin_interface(app)

    return app
Exemple #28
0
def create_app(config_override: Mapping = None) -> Flask:
    """Create the flask app for the debug server.

    Parameters:
        config_override:
            Dict containing custom configuration to apply after loading the
            normal config. Useful for testing.
    """
    config_override = {} if config_override is None else config_override
    # TODO: Rename app, no longer used only for debugging
    app = Flask('stuffrdebugserver',
                instance_relative_config=True,
                static_url_path='',
                template_folder='static')
    app.config.from_object('config.default')
    app.config.from_envvar('STUFFR_SETTINGS')
    app.config.from_mapping(config_override)
    app.json_encoder = StuffrJSONEncoder
    logger.set_logger(app.logger)

    db.init_app(app)
    security = Security(app, user_store, confirm_register_form=StuffrRegisterForm)
    security.unauthorized_handler(api_unauthenticated_handler)
    Mail(app)

    # In debug mode Swagger documentation is served at root
    if not app.config['DEBUG']:
        def api_root_view():
            """Provide a link to API documentation if root accessed."""
            return error_response(
                'TODO: Link to documentation here', HTTPStatus.NOT_FOUND)
        blueprint_api.add_url_rule('/', 'apiindex', api_root_view)

    app.register_blueprint(blueprint_simple, url_prefix='/simple')
    app.register_blueprint(blueprint_api, url_prefix='/api')

    def default404(e):
        """Default handler for 404."""
        # TODO: Conditional JSON/HTML response (for simple mode)
        return error_response(e.description, HTTPStatus.NOT_FOUND)
    app.register_error_handler(HTTPStatus.NOT_FOUND, default404)

    # TODO: Make friendlier error message (40x or 50x?)
    app.add_url_rule('/', 'index', lambda: "You probably shouldn't be here")

    return app
Exemple #29
0
def create_app(config=None):
    app = Flask(__name__)

    app.config.from_object('wedding_site.default_config')
    if 'WEDDING_SITE_CONFIG' in os.environ:
        app.config.from_envvar('WEDDING_SITE_CONFIG')
    if config:
        app.config.from_object(config)

    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.json_encoder = CustomJSONEncoder
    app.jinja_env.globals['momentjs'] = momentjs

    init_extensions(app)
    init_views(app)

    return app
Exemple #30
0
def create_app(config=config.Local):
    app = Flask(__name__)
    app.config.from_object(config)
    app.json_encoder = CustomJSONEncoder
    db.init_app(app)


    register_blueprints(app)

    @app.before_request
    def set_logging_context():
        """
        Extract the logging context from the request and add it to the kloggyr factory.
        """
        # TODO add these for anti_charity. Standard analytics logging requirements are specified in
        #   the 'Standard Analytics Kloggyr Event Names' document on Confluence.
        #   https://kyruus.jira.com/wiki/display/ANL/Standard+Analytics+Kloggyr+Events

    @app.context_processor
    def get_landing_page_js_url():
        if app.config.get('LOCAL_JS'):
            url = 'static/js/anticharity_landing_page.js'
        else:
            url = 'https://s3-us-west-2.amazonaws.com/anticharity/js/manual_upload/anticharity_landing_page.min.js'
        return {'landing_page_js_url': url}

    @app.context_processor
    def get_app_js_url():
        if app.config.get('LOCAL_JS'):
            url = 'static/js/anti_charity.js'
        else:
            url = 'https://s3-us-west-2.amazonaws.com/anticharity/js/manual_upload/anti_charity.min.js'
        return {'app_js_url': url}


    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        """A handler for any endpoint that raises an InvalidUsage exception"""
        return jsonify(error.to_dict()), error.status_code

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db.session.remove()

    return app
Exemple #31
0
from flask import Flask, request, jsonify, g
from flask_api import status
from waitress import serve
import grpc
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import get_model_metadata_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
from google.protobuf import json_format

from cortex.lib import util, Context, api_utils
from cortex.lib.log import cx_logger, debug_obj
from cortex.lib.exceptions import UserRuntimeException, UserException, CortexException
from cortex.lib.stringify import truncate

app = Flask(__name__)
app.json_encoder = util.json_tricks_encoder

local_cache = {
    "ctx": None,
    "stub": None,
    "api": None,
    "signature_key": None,
    "parsed_signature": None,
    "model_metadata": None,
    "request_handler": None,
    "class_set": set(),
}

DTYPE_TO_VALUE_KEY = {
    "DT_INT32": "intVal",
    "DT_INT64": "int64Val",
Exemple #32
0
    logger.critical(
        'Exception encountered during parsing of config (.yml file). '
        'See console above for details...')
    sys.exit(1)

# Update the logging based on the parsed config
configure_logging(app.config['DIRBS_CONFIG'].log_config)

# Initialize file logging
setup_file_logging(app.config['DIRBS_CONFIG'].log_config, 'dirbs-api')

# Init statsd client
statsd = StatsClient(app.config['DIRBS_CONFIG'].statsd_config)

# Init custom JSONEncoder (handles dates, etc.)
app.json_encoder = utils.JSONEncoder

# setup redis as cache with dirbs apis app
cache.init_app(app,
               config={
                   'CACHE_TYPE':
                   'redis',
                   'CACHE_REDIS_HOST':
                   app.config['DIRBS_CONFIG'].redis_config.hostname,
                   'CACHE_REDIS_PORT':
                   app.config['DIRBS_CONFIG'].redis_config.port,
                   'CACHE_REDIS_PASSWORD':
                   app.config['DIRBS_CONFIG'].redis_config.password,
                   'CACHE_REDIS_DB':
                   app.config['DIRBS_CONFIG'].redis_config.db,
                   'CACHE_DEFAULT_TIMEOUT':
            return str(o)                               
        if isinstance(o, datetime.datetime):
            return str(o)
        return json.JSONEncoder.default(self, o)


app = Flask(__name__)
CORS(app)   # This will enable CORS for all routes


app.config['MONGO_DBNAME'] = 'userslist' # Name of database on mongo
app.config["MONGO_URI"] = "mongodb+srv://sysadm:[email protected]/userslist" #URI to Atlas cluster  + Auth Credentials


mongo = PyMongo(app)
app.json_encoder = JSONEncoder # Use the modified encoder class to handle ObjectId & datetime object while jsonifying the response.


@app.route('/', methods=['GET']) # Hello message
def index():
    
    return 'Hello! It works!'



@app.route('/get-data', methods=['GET'])  # Find all data in my collection
def getAllData():
    user = mongo.db.users # Connect to my collection

    output = []
Exemple #34
0
from fava.util import resource_path
from fava.util import send_file_inline
from fava.util import setup_logging
from fava.util import slugify
from fava.util.date import Interval
from fava.util.excel import HAVE_EXCEL

setup_logging()
app = Flask(  # pylint: disable=invalid-name
    __name__,
    template_folder=str(resource_path("templates")),
    static_folder=str(resource_path("static")),
)
app.register_blueprint(json_api, url_prefix="/<bfile>/api")

app.json_encoder = FavaJSONEncoder
app.jinja_options["extensions"].append("jinja2.ext.do")
app.jinja_options["extensions"].append("jinja2.ext.loopcontrols")
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

app.config["HAVE_EXCEL"] = HAVE_EXCEL
app.config["HELP_PAGES"] = HELP_PAGES
app.config["ACCOUNT_RE"] = ACCOUNT_RE

REPORTS = [
    "_context",
    "balance_sheet",
    "commodities",
    "documents",
    "events",
Exemple #35
0
    def default(self, obj) -> Union[str, int]:
        if isinstance(obj, bytes):
            try:
                return obj.decode()
            except UnicodeDecodeError:
                return obj.decode('utf-8', 'ignore')

        return super(JsonEncoder, self).default(obj)


app = Flask(
    APP_NAME,
    static_folder=path.join(CLIENT_ROOT, 'static'),
    template_folder=path.join(CLIENT_ROOT, 'templates'),
)
app.json_encoder = JsonEncoder
app.config['JSON_SORT_KEYS'] = False

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'connect_args': {'timeout': 30}}
app.config['SQLALCHEMY_BINDS'] = {
    'contacts': f'sqlite:///{CONTACTS_CACHE_DB_FILE}',
    'folders': f'sqlite:///{FOLDER_CACHE_DB_FILE}',
}
db = SQLAlchemy(app)


@app.before_request
def validate_session_token() -> None:
    if DEBUG and not IS_APP:  # don't apply in full dev mode
        return
Exemple #36
0
import boto3
from boto3.dynamodb.conditions import Key, Attr
import bcrypt
from flask import Flask, jsonify, request, Response
from flask_cors import CORS
from flask_jwt_extended import JWTManager, create_access_token, create_refresh_token, get_jwt_identity, jwt_required
from typing import List, Dict, Any
from dataclasses import dataclass, field

# Create the logger for this module
logger = utils.create_logger(__name__)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TRACKER_TABLE_NAME'])
'''Create a Flask App'''
app = Flask(__name__)
app.json_encoder = utils.DecimalEncoder
CORS(app)

# Setting JWT Settings
# app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY')
app.config['JWT_SECRET_KEY'] = 'aIQOrIk5a110FCeMZdfNo7BwXuAwgtAW'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=1)
jwt = JWTManager(app)


@dataclass
class APIResponse:
    status: str
    result: Dict[str, Any] = field(default_factory=dict)
    messages: List[str] = field(default_factory=list)
Exemple #37
0
def create_app(db_config = None):
    app = Flask(__name__)
    app.json_encoder = CustomJSONEncoder

    if db_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(db_config)

    database = create_engine(app.config['DB_URL'], encoding = 'utf-8', max_overflow = 0)
    app.database = database

    @app.route('/ping', methods=['GET'])
    def ping():
        return 'pong'

    @app.route('/sign-up', methods=['POST'])
    def sign_up():
        new_user = request.get_json()
        new_user_id = app.database.execute(text("""
            INSERT INTO users(
                name,
                email,
                profile,
                hashed_password
            ) VALUES(
                :name,
                :email,
                :profile,
                :password
            )
        """), new_user).lastrowid # lastrowid: AUTO_INCREMENT를 사용하는 테이블일 겨우 새 행에 대한 AUTO_INCREMENT 값을 리턴

        row = app.database.execute(text("""
            SELECT
                id,
                name,
                email,
                profile
            FROM users
            WHERE id = :user_id
        """), {
            'user_id' : new_user_id
        }).fetchone()

        created_user = {
            'id': row['id'],
            'name': row['name'],
            'email': row['email'],
            'profile': row['profile']
        } if row else None

        return jsonify(created_user)

    @app.route('/tweet', methods=['POST'])
    def tweet():
        # 페이로드는 사용에 있어서 전송되는 데이터를 뜻한다.
        payload = request.json
        user_id = int(payload['id'])
        tweet = payload['tweet']

        if user_id not in app.users:
            return '사용자가 존재하지 않습니다', 400

        if len(tweet) > 300:
            return '300자를 초과했습니다.', 400

        app.tweets.append({
            'user_id' : user_id,
            'tweet' : tweet
        })

        return '', 200

    @app.route('/follow', methods = ['POST'])
    def follow():
        payload = request.json
        user_id = int(payload['id'])
        to_follow = int(payload['follow'])

        if user_id not in app.users or to_follow not in app.users:
            return jsonify({'err': '사용자가 존재하지 않습니다.'}), 400

        user = app.users[user_id]
        user.setdefault('follow', set()).add(to_follow)

        return jsonify(user)

    @app.route('/unfollow', methods = ['POST'])
    def unfollow():
        payload = request.json
        user_id = int(payload['id'])
        to_follow = int(payload['unfollow'])

        if user_id not in app.users or to_follow not in app.users:
            return jsonify({'err': '사용자가 존재하지 않습니다.'}), 400

        user = app.users[user_id]

    # discard 메소드는 remove 메소드와 다르게 없는 값의 경우에 대한 예외처리를 하지 않아도 된다.
        user.setdefault('follow', set()).discard(to_follow)

        return jsonify(user)

    @app.route('/timeline/<int:user_id>', methods = ['GET'])
    def timeline(user_id):
        if user_id not in app.users:
            return jsonify({'err':'사용자가 존재하지 않습니다..'}), 400

        follow_list = app.users[user_id].get('follow', set())
        follow_list.add(user_id)
        timeline = [tweet for tweet in app.tweets if tweet['user_id'] in follow_list]

        return jsonify({
            'user_id': user_id,
            'timeline': timeline
        })

    return app # END create_app
Exemple #38
0
#NEEDS PYTHON2 NOT 3
from flask import Flask  #pip install flask
from flask import jsonify
from flask import request
import folder_asset
import s3_rest_handler
import platform
import dyanmodb_handler

app = Flask(__name__)
app.json_encoder = folder_asset.FolderAssetJSONEncoder


@app.route('/')
def base_page_handler():
    return "api:" \
           "\n" \
           "GET [base_url]/everything\n" \
           "returns every asset in s3" \
           "\n\n" \
           "GET [base_url]/filter?=[unix_timestamp]\n" \
           "returns every asset uploaded after [unix_timestamp] argument" \
           "\n\n" \
           "GET [base_url]/timeline \n" \
           "returns the mission timeline"


@app.route('/everything')
def everything_page_handler():
    output = s3_rest_handler.retrieve_assets()
    return jsonify(output)
Exemple #39
0
def create_app():
    # Initialize Flask instance and enable static file serving
    app = Flask(__name__)
    app.config.from_object(config[ENV_CONFIG]())  # instance is for __init__
    app.wsgi_app = WhiteNoise(app.wsgi_app, root='static/')

    # Initialize Sentry for error tracking
    sentry.init_app(app)

    # Custom Json
    app.json_encoder = CustomJSONEncoder
    compress.init_app(app)

    # Inintialize webpack support
    webpack.init_app(app)

    # Initialize Mail by Flask-Mail
    mail.init_app(app)

    # Initialize Database and Migration by Flask-Sqlalchey and Flask-Migrate
    db.init_app(app)
    migrate.init_app(
        app,
        db,
        directory=join(
            abspath(dirname(project.__file__)),
            'migrations'))  # set directory for compatible with Heroku

    # Initialize DebugToolbar
    if app.config['DEBUG']:
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension()
        toolbar.init_app(app)

    # Initialize app blueprint
    from .blueprints.app import app as app_blueprint
    app.register_blueprint(app_blueprint, url_prefix='')

    # Initialize CLI shell command
    @app.shell_context_processor
    def make_shell_context():
        return dict(app=app, db=db)

    # Initialize CLI command for Celery
    @app.cli.command()
    @click.argument('queue', nargs=1, default=PROJECT_NAME)
    def celeryworker(queue):
        sys.argv = [
            'celery', 'worker', '-n {}@%h'.format(uuid.uuid4()), '-A',
            '{}.celery_app:celery_application'.format(PROJECT_NAME), '-E',
            '-Q', queue, '--loglevel=info'
        ]
        sys.exit(celery_main())

    @app.cli.command()
    def celerybeat():
        sys.argv = [
            'celery', 'beat', '-A',
            '{}.celery_app:celery_application'.format(PROJECT_NAME),
            '--loglevel=info'
        ]
        sys.exit(celery_main())

    # Initialize CLI command for pytest-cov
    @app.cli.command(name='py.test')
    @click.option('--cov')
    @click.option('--cov-report')
    def pytest_cov(cov, cov_report):
        """Run pytest with pytest-cov plugin."""
        import pytest

        sys.argv = ['py.test', '-s']
        sys.argv += ['--cov={}'.format(cov)] if cov else []
        sys.argv += ['--cov-report={}'.format(cov_report)
                     ] if cov_report else []

        sys.exit(pytest.main())

    return app
Exemple #40
0
class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        try:
            if isinstance(obj, datetime):
                return obj.isoformat()

            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        return JSONEncoder.default(self, obj)


app.json_encoder = CustomJSONEncoder

welcome_message = 'Welcome in the Fake News Recognition API. Please see ' \
                  'https://github.com/several27/FakeNewsRecognition to learn more!'


@app.route('/api/', methods=['GET'])
def home():
    return jsonify({'message': welcome_message})


@app.route('/api/v1', methods=['GET'])
def home_v1():
    return jsonify({'message': welcome_message})

Exemple #41
0
"""
Created on Sep 12, 2016

@author: Hamed Zekri
"""

from flask import Flask

from deltapy.packaging.package import Package
import deltapy.application.services as services
from server.utils.json_encoder import CustomJsonEncoder

from server.wsdl.service_manager import PyroServer


SERVER_FLASK_WEB_SERVICES_PROVIDER_MANAGER = 'server.flask.web_services.provider.manager'
SERVER_FLASK_WEB_SERVICES_SECURITY_MANAGER = 'server.flask.web_services.security.manager'
SERVER_FLASK_WEB_SERVICES_PRODUCTS_MANAGER = 'server.flask.web_services.products.manager'
SERVER_FLASK_WEB_SERVICES_INVOICE_MANAGER = 'server.flask.web_services.invoice.manager'
SUCCESS_RESPONSE = "SUCCESSFUL"
FAILED_RESPONSE = "FAILED"

pyro_server = PyroServer("127.0.0.1", "6082")
flask_app = Flask("flask-{0}".format(services.get_name()))
flask_app.json_encoder = CustomJsonEncoder


class FlaskWebServicesPackage(Package):
    """
    Flask Web Services Package
    """
Exemple #42
0
from flask import Flask
from flask_apscheduler import APScheduler
from flask_cors import CORS
from flask_migrate import Migrate
from flask_pymongo import PyMongo
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy

from .google.credentials import GoogleClientCredentials
from .spotify.credentials import SpotifyClientCredentials
from .utils.json import JSONEncoder

app = Flask(__name__)
app.config.from_pyfile('flaskapp.cfg')
app.json_encoder = JSONEncoder

CORS(app, supports_credentials=True)

my_scheduler = APScheduler(app=app)
my_scheduler.start()

mongodb = PyMongo(app)
mysqldb = SQLAlchemy(app)
session = Session(app)

mysqldb.create_all()
session.app.session_interface.db.create_all()

migrate_mongodb = Migrate(app, mongodb)
migrate_mysqldb = Migrate(app, mysqldb)
Exemple #43
0
from flask import Flask, session, render_template, request, jsonify
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

app = Flask(__name__)

class MyJSONEncoder(flask.json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            # Convert decimal instances to strings.
            return str(obj)
        return super(MyJSONEncoder, self).default(obj)
app.json_encoder = MyJSONEncoder
# SQLalchemy
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False


# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

#Goodreads key:
Exemple #44
0
import os

from flask import Flask, jsonify
from flask_pymongo import PyMongo

from .utils.encoder import MongoJSONEncoder

APP = Flask(__name__, static_folder="../client")
APP.json_encoder = MongoJSONEncoder
APP.config["JSON_AS_ASCII"] = False
APP.config[
    "MONGO_URI"] = "mongodb+srv://amd:[email protected]/photorun?retryWrites=true&w=majority"
MONGO = PyMongo(APP)

from .db.database import create_collections

create_collections()

from .db.start_value_db import add_start_values

if os.environ.get(
        "FLASK_ENV") == "development" or MONGO.db.posts.count_documents(
            {}) == 0:
    add_start_values()

from . import views
from .api import feed_printer, post_operations, register_user
Exemple #45
0
def create_app(test_config=None):
    app = Flask(__name__)

    app.config['JWT_SECRET_KEY'] = 'super-secret'

    #CORS(app)
    app.json_encoder = CustomJSONEncoder

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)
    app.database = database

    ## =============================================
    # health check
    @app.route("/ping", methods=['GET'])
    def ping():
        return "pong"

    ## =============================================
    # sign up
    @app.route('/sign-up', methods=['POST'])
    def sign_up():
        new_user = request.json
        new_user['password'] = bcrypt.hashpw(
            new_user['password'].encode('UTF-8'), bcrypt.gensalt())

        new_user_id = insert_user(new_user)
        new_user = get_user(new_user_id)

        return jsonify(new_user)

    ## =============================================
    # login
    @app.route('/login', methods=['POST'])
    def login():
        credential = request.json
        email = credential['email']
        password = credential['password']
        user_credential = get_user_id_and_password(email)

        if user_credential and bcrypt.checkpw(
                password.encode('UTF-8'),
                user_credential['hashed_password'].encode('UTF-8')):
            user_id = user_credential['id']
            payload = {
                'user_id': user_id,
                'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24)
            }

            token = jwt.encode(payload, app.config['JWT_SECRET_KEY'], 'HS256')

            return jsonify({'access_token': token.decode('UTF-8')})
        else:
            return '', 401

    ## =============================================
    # tweet 300 char
    @app.route('/tweet', methods=['POST'])
    @login_required
    def tweet():
        user_tweet = request.json
        tweet = user_tweet['tweet']

        if len(tweet) > 300:
            return '300자를 초과했습니다.', 400

        insert_tweet(user_tweet)

        return '', 200

    ## =============================================
    # Follow
    @app.route('/follow', methods=['POST'])
    @login_required
    def follow():
        payload = request.json
        insert_follow(payload)

        return '', 200

    ## =============================================
    # Unfollow
    @app.route('/unfollow', methods=['POST'])
    @login_required
    def unfollow():
        payload = request.json
        insert_unfollow(payload)

        return '', 200

    ## =============================================
    # Timeline
    @app.route('/timeline/<int:user_id>', methods=['GET'])
    def timeline(user_id):
        return jsonify({'user_id': user_id, 'timeline': get_timeline(user_id)})

    return app
Exemple #46
0
api.config.from_pyfile('config.cfg')
logging.basicConfig(level=logging.DEBUG)
# Connector to running database
mongo = MongoClient(api.config['MONGO_HOST'], api.config['MONGO_PORT'])
db = mongo.database
authentication = api.config['AUTHENTICATION_ENABLED']


class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)


api.json_encoder = JSONEncoder

import repositories

api.repository_collection = repositories.RepositoryCollection(db)

api.user_repository = api.repository_collection.user_repository
api.house_repository = api.repository_collection.house_repository
api.room_repository = api.repository_collection.room_repository
api.device_repository = api.repository_collection.device_repository
api.trigger_repository = api.repository_collection.trigger_repository
api.theme_repository = api.repository_collection.theme_repository
api.token_repository = api.repository_collection.token_repository


def get_request_token():
Exemple #47
0
from utils.DbLoader import dbLoader
from utils.scan_compression import ScanCompressor
from utils.db import db
from utils.encoder import NumpyNumberEncoder
from utils.app_insights_client import app_insights_client

static_dir = os.path.join(os.path.abspath(os.getcwd()),'static')
template_dir = os.path.join(static_dir, 'templates')
app = Flask(__name__, static_url_path='', instance_relative_config=True, template_folder=template_dir)
app.config.from_object('config')
if os.path.isdir(app.config.root_path):
    app.config.from_pyfile('config.py')
else:
    logging.warning('Cannot find instance directory - using default configuration')

app.json_encoder = NumpyNumberEncoder
app.secret_key = app.config.get('SECRET_KEY')

db.init_app(app)

app_insights_client.init_app(app.config.get('APPLICATION_INSIGHTS_INSTRUMENTATION_KEY'))

db_loader_logger = logging
if not app.debug:
    from logging.handlers import RotatingFileHandler

    formatter = logging.Formatter("[%(asctime)s] {%(module)s:%(lineno)d} %(levelname)s - %(message)s")
    log_dir = app.config.get('LOG_DIRECTORY', '.')
    os.makedirs(log_dir, exist_ok=True)
    logfile = os.path.join(log_dir, 'aidoc-viewer.log')
    file_handler = RotatingFileHandler(logfile, maxBytes=5 * 1024 * 1024, backupCount=10)
Exemple #48
0
def create_app():
    app = Flask(__name__,
                template_folder='../templates',
                static_folder='../static')
    app.json_encoder = CustomJSONEncoder
    cache = Cache(app,
                  config={
                      'CACHE_TYPE': 'simple',
                      'CACHE_DEFAULT_TIMEOUT': 0
                  })
    cache_buster = CacheBuster(config={'extensions': ['.js', '.css']})
    cache_buster.init_app(app)
    Compress(app)
    if args.cors:
        CORS(app)

    db_uri = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(
        args.db_user, args.db_pass, args.db_host, args.db_port, args.db_name)
    app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
        'pool_size': 0  # No limit.
    }
    app.config['SQLALCHEMY_POOL_RECYCLE'] = args.db_pool_recycle
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    if args.client_auth:
        app.config['SESSION_TYPE'] = 'redis'
        r = redis.Redis(args.redis_host, args.redis_port)
        app.config['SESSION_REDIS'] = r
        app.config['SESSION_USE_SIGNER'] = True
        app.secret_key = args.secret_key
        Session(app)
        if args.discord_auth:
            accepted_auth_types.append('discord')
            for config in args.discord_access_configs:
                length = len(config.split(':'))
                name = (config.split(':')[2]
                        if length == 3 else config.split(':')[1])
                if name not in valid_access_configs:
                    valid_access_configs.append(name)
        if args.telegram_auth:
            accepted_auth_types.append('telegram')
            for config in args.telegram_access_configs:
                name = config.split(':')[1]
                if name not in valid_access_configs:
                    valid_access_configs.append(name)

    if not args.disable_blacklist:
        log.info('Retrieving blacklist...')
        ip_blacklist = get_ip_blacklist()
        # Sort & index for binary search
        ip_blacklist.sort(key=lambda r: r[0])
        ip_blacklist_keys = [dottedQuadToNum(r[0]) for r in ip_blacklist]
    else:
        log.info('Blacklist disabled for this session.')

    @app.before_request
    def validate_request():
        # Get real IP behind trusted reverse proxy.
        ip_addr = request.remote_addr
        if ip_addr in args.trusted_proxies:
            ip_addr = request.headers.get('X-Forwarded-For', ip_addr)

        # Make sure IP isn't blacklisted.
        if ip_is_blacklisted(ip_addr):
            log.debug('Denied access to %s: blacklisted IP.', ip_addr)
            abort(403)

        if args.client_auth:
            session['ip'] = ip_addr
            session['last_active'] = datetime.utcnow()

    @app.route('/')
    @auth_required
    def map_page(*_args, **kwargs):
        if not kwargs['has_permission']:
            return redirect(kwargs['redirect_uri'])

        user_args = get_args(kwargs['access_config'])

        settings = {
            'centerLat':
            user_args.center_lat,
            'centerLng':
            user_args.center_lng,
            'maxZoomLevel':
            user_args.max_zoom_level,
            'showAllZoomLevel':
            user_args.show_all_zoom_level,
            'clusterZoomLevel':
            user_args.cluster_zoom_level,
            'clusterZoomLevelMobile':
            user_args.cluster_zoom_level_mobile,
            'maxClusterRadius':
            user_args.max_cluster_radius,
            'spiderfyClusters':
            user_args.spiderfy_clusters,
            'isStartMarkerMovable':
            not user_args.lock_start_marker,
            'generateImages':
            user_args.generate_images,
            'statsSidebar':
            not user_args.no_stats_sidebar,
            'twelveHourClock':
            user_args.twelve_hour_clock,
            'mapUpdateInverval':
            user_args.map_update_interval,
            'motd':
            user_args.motd,
            'motdTitle':
            user_args.motd_title,
            'motdText':
            user_args.motd_text,
            'motdPages':
            user_args.motd_pages,
            'showMotdAlways':
            user_args.show_motd_always,
            'pokemons':
            not user_args.no_pokemon,
            'upscaledPokemon':
            ([int(i) for i in user_args.upscaled_pokemon.split(',')]
             if user_args.upscaled_pokemon is not None else []),
            'pokemonValues': (not user_args.no_pokemon
                              and not user_args.no_pokemon_values),
            'catchRates':
            user_args.catch_rates,
            'rarity': (not user_args.no_pokemon and user_args.rarity
                       and user_args.rarity_update_frequency),
            'rarityFileName':
            user_args.rarity_filename,
            'pokemonCries': (not user_args.no_pokemon
                             and user_args.pokemon_cries),
            'gyms':
            not user_args.no_gyms,
            'gymSidebar': ((not user_args.no_gyms or not user_args.no_raids)
                           and not user_args.no_gym_sidebar),
            'gymFilters': (not user_args.no_gyms
                           and not user_args.no_gym_filters),
            'raids':
            not user_args.no_raids,
            'raidFilters': (not user_args.no_raids
                            and not user_args.no_raid_filters),
            'pokestops':
            not user_args.no_pokestops,
            'quests':
            not user_args.no_pokestops and not user_args.no_quests,
            'invasions': (not user_args.no_pokestops
                          and not user_args.no_invasions),
            'lures':
            not user_args.no_pokestops and not user_args.no_lures,
            'weather':
            not user_args.no_weather,
            'spawnpoints':
            not user_args.no_spawnpoints,
            'scannedLocs':
            not user_args.no_scanned_locs,
            's2Cells':
            not user_args.no_s2_cells,
            'ranges':
            not user_args.no_ranges,
            'nestParks':
            user_args.nest_parks,
            'nestParksFileName':
            user_args.nest_parks_filename,
            'exParks':
            user_args.ex_parks,
            'exParksFileName':
            user_args.ex_parks_filename
        }

        return render_template(
            'map.html',
            version=version,
            lang=user_args.locale,
            map_title=user_args.map_title,
            custom_favicon=user_args.custom_favicon,
            header_image=not user_args.no_header_image,
            header_image_name=user_args.header_image,
            client_auth=user_args.client_auth,
            logged_in=is_logged_in(),
            admin=is_admin(),
            madmin_url=user_args.madmin_url,
            donate_url=user_args.donate_url,
            patreon_url=user_args.patreon_url,
            discord_url=user_args.discord_url,
            messenger_url=user_args.messenger_url,
            telegram_url=user_args.telegram_url,
            whatsapp_url=user_args.whatsapp_url,
            pokemon_history_page=(settings['pokemons']
                                  and not user_args.no_pokemon_history_page),
            quest_page=settings['quests'] and not user_args.no_quest_page,
            analytics_id=user_args.analytics_id,
            settings=settings,
            i18n=i8ln)

    @app.route('/pokemon-history')
    @auth_required
    def pokemon_history_page(*_args, **kwargs):
        if not kwargs['has_permission']:
            return redirect(kwargs['redirect_uri'])

        user_args = get_args(kwargs['access_config'])

        if user_args.no_pokemon or user_args.no_pokemon_history_page:
            if args.client_auth:
                if is_logged_in():
                    abort(403)
                else:
                    return redirect(url_for('login_page'))
            else:
                abort(404)

        settings = {
            'centerLat': user_args.center_lat,
            'centerLng': user_args.center_lng,
            'generateImages': user_args.generate_images,
            'motd': user_args.motd,
            'motdTitle': user_args.motd_title,
            'motdText': user_args.motd_text,
            'motdPages': user_args.motd_pages,
            'showMotdAlways': user_args.show_motd_always
        }

        return render_template('pokemon-history.html',
                               version=version,
                               lang=user_args.locale,
                               map_title=user_args.map_title,
                               custom_favicon=user_args.custom_favicon,
                               header_image=not user_args.no_header_image,
                               header_image_name=user_args.header_image,
                               client_auth=user_args.client_auth,
                               logged_in=is_logged_in(),
                               admin=is_admin(),
                               madmin_url=user_args.madmin_url,
                               donate_url=user_args.donate_url,
                               patreon_url=user_args.patreon_url,
                               discord_url=user_args.discord_url,
                               messenger_url=user_args.messenger_url,
                               telegram_url=user_args.telegram_url,
                               whatsapp_url=user_args.whatsapp_url,
                               quest_page=(not user_args.no_pokestops
                                           and not user_args.no_quests
                                           and not user_args.no_quest_page),
                               analytics_id=user_args.analytics_id,
                               settings=settings)

    @app.route('/quests')
    @auth_required
    def quest_page(*_args, **kwargs):
        if not kwargs['has_permission']:
            return redirect(kwargs['redirect_uri'])

        user_args = get_args(kwargs['access_config'])

        if (user_args.no_pokestops or user_args.no_quests
                or user_args.no_quest_page):
            if args.client_auth:
                if is_logged_in():
                    abort(403)
                else:
                    return redirect(url_for('login_page'))
            else:
                abort(404)

        settings = {
            'generateImages': user_args.generate_images,
            'motd': user_args.motd,
            'motdTitle': user_args.motd_title,
            'motdText': user_args.motd_text,
            'motdPages': user_args.motd_pages,
            'showMotdAlways': user_args.show_motd_always
        }

        return render_template(
            'quest.html',
            version=version,
            lang=user_args.locale,
            map_title=user_args.map_title,
            custom_favicon=user_args.custom_favicon,
            header_image=not user_args.no_header_image,
            header_image_name=user_args.header_image,
            client_auth=user_args.client_auth,
            logged_in=is_logged_in(),
            admin=is_admin(),
            madmin_url=user_args.madmin_url,
            donate_url=user_args.donate_url,
            patreon_url=user_args.patreon_url,
            discord_url=user_args.discord_url,
            messenger_url=user_args.messenger_url,
            telegram_url=user_args.telegram_url,
            whatsapp_url=user_args.whatsapp_url,
            pokemon_history_page=(not user_args.no_pokemon
                                  and not user_args.no_pokemon_history_page),
            analytics_id=user_args.analytics_id,
            settings=settings)

    @app.route('/mobile')
    @auth_required
    def mobile_page(*_args, **kwargs):
        if not kwargs['has_permission']:
            return redirect(kwargs['redirect_uri'])

        user_args = get_args(kwargs['access_config'])

        # todo: Check if client is Android/iOS/Desktop for geolink, currently
        # only supports Android.
        pokemon_list = []

        settings = {
            'motd': user_args.motd,
            'motdTitle': user_args.motd_title,
            'motdText': user_args.motd_text,
            'motdPages': user_args.motd_pages,
            'showMotdAlways': user_args.show_motd_always
        }

        # Allow client to specify location.
        lat = request.args.get('lat', user_args.center_lat, type=float)
        lon = request.args.get('lon', user_args.center_lng, type=float)
        origin_point = LatLng.from_degrees(lat, lon)

        for pokemon in convert_pokemon_list(
                Pokemon.get_active(None, None, None, None)):
            pokemon_point = LatLng.from_degrees(pokemon['latitude'],
                                                pokemon['longitude'])
            diff = pokemon_point - origin_point
            diff_lat = diff.lat().degrees
            diff_lng = diff.lng().degrees
            direction = (('N' if diff_lat >= 0 else 'S')
                         if abs(diff_lat) > 1e-4 else '') +\
                        (('E' if diff_lng >= 0 else 'W')
                         if abs(diff_lng) > 1e-4 else '')
            entry = {
                'id':
                pokemon['pokemon_id'],
                'name':
                get_pokemon_name(pokemon['pokemon_id']),
                'card_dir':
                direction,
                'distance':
                int(
                    origin_point.get_distance(pokemon_point).radians *
                    6366468.241830914),
                'time_to_disappear':
                '%d min %d sec' % (divmod(
                    (pokemon['disappear_time'] - datetime.utcnow()).seconds,
                    60)),
                'disappear_time':
                pokemon['disappear_time'],
                'disappear_sec':
                (pokemon['disappear_time'] - datetime.utcnow()).seconds,
                'latitude':
                pokemon['latitude'],
                'longitude':
                pokemon['longitude']
            }
            pokemon_list.append((entry, entry['distance']))
        pokemon_list = [y[0] for y in sorted(pokemon_list, key=lambda x: x[1])]

        return render_template('mobile.html',
                               version=version,
                               custom_favicon=user_args.custom_favicon,
                               pokemon_list=pokemon_list,
                               origin_lat=lat,
                               origin_lng=lon,
                               analytics_id=user_args.analytics_id,
                               settings=settings)

    @app.route('/login')
    def login_page():
        if not args.client_auth:
            abort(404)

        if is_logged_in():
            return redirect(url_for('map_page'))

        settings = {
            'motd': args.motd,
            'motdTitle': args.motd_title,
            'motdText': args.motd_text,
            'motdPages': args.motd_pages,
            'showMotdAlways': args.show_motd_always
        }

        return render_template(
            'login.html',
            version=version,
            lang=args.locale,
            map_title=args.map_title,
            custom_favicon=args.custom_favicon,
            header_image=not args.no_header_image,
            header_image_name=args.header_image,
            madmin_url=args.madmin_url,
            donate_url=args.donate_url,
            patreon_url=args.patreon_url,
            discord_url=args.discord_url,
            messenger_url=args.messenger_url,
            telegram_url=args.telegram_url,
            whatsapp_url=args.whatsapp_url,
            analytics_id=args.analytics_id,
            discord_auth=args.discord_auth,
            telegram_auth=args.telegram_auth,
            pokemon_history_page=(not args.no_pokemon
                                  and not args.no_pokemon_history_page),
            quest_page=(not args.no_pokestops and not args.no_quests
                        and not args.no_quest_page),
            settings=settings)

    @app.route('/login/<auth_type>')
    def login(auth_type):
        if not args.client_auth:
            abort(404)

        if is_logged_in():
            return redirect(url_for('map_page'))

        if auth_type not in accepted_auth_types:
            abort(404)

        authenticator = auth_factory.get_authenticator(auth_type)
        auth_uri = authenticator.get_authorization_url()

        return redirect(auth_uri)

    @app.route('/login/telegram')
    def telegram_login_page():
        if not args.telegram_auth:
            abort(404)

        settings = {
            'motd': args.motd,
            'motdTitle': args.motd_title,
            'motdText': args.motd_text,
            'motdPages': args.motd_pages,
            'showMotdAlways': args.show_motd_always
        }

        return render_template(
            'telegram.html',
            version=version,
            lang=args.locale,
            map_title=args.map_title,
            custom_favicon=args.custom_favicon,
            header_image=not args.no_header_image,
            header_image_name=args.header_image,
            madmin_url=args.madmin_url,
            donate_url=args.donate_url,
            patreon_url=args.patreon_url,
            discord_url=args.discord_url,
            messenger_url=args.messenger_url,
            telegram_url=args.telegram_url,
            whatsapp_url=args.whatsapp_url,
            pokemon_history_page=(not args.no_pokemon
                                  and not args.no_pokemon_history_page),
            quest_page=(not args.no_pokestops and not args.no_quests
                        and not args.no_quest_page),
            analytics_id=args.analytics_id,
            telegram_bot_username=args.telegram_bot_username,
            server_uri=args.server_uri,
            settings=settings)

    @app.route('/auth/<auth_type>')
    def auth(auth_type):
        if not args.client_auth:
            abort(404)

        if is_logged_in():
            return redirect(url_for('map_page'))

        if auth_type not in accepted_auth_types:
            abort(404)

        auth_factory.get_authenticator(auth_type).authorize()

        if args.no_multiple_logins:
            r = app.config['SESSION_REDIS']
            sessions = get_sessions(r)
            for s in sessions:
                if 'auth_type' in s and 'id' in s:
                    if (s['auth_type'] == session['auth_type']
                            and s['id'] == session['id']):
                        r.delete('session:' + s['session_id'])

        return redirect(url_for('map_page'))

    @app.route('/logout')
    def logout():
        if not args.client_auth:
            abort(404)

        if is_logged_in():
            if session['auth_type'] in accepted_auth_types:
                a = auth_factory.get_authenticator(session['auth_type'])
                a.end_session()
            else:
                session.clear()

        return redirect(url_for('map_page'))

    @app.route('/admin')
    def admin_page():
        return redirect(url_for('users_page'))

    @app.route('/admin/users')
    @auth_required
    def users_page(*_args, **kwargs):
        if not args.client_auth:
            abort(404)

        if not kwargs['has_permission']:
            return redirect(kwargs['redirect_uri'])

        if not is_admin():
            abort(403)

        user_args = get_args(kwargs['access_config'])

        settings = {
            'motd': user_args.motd,
            'motdTitle': user_args.motd_title,
            'motdText': user_args.motd_text,
            'motdPages': user_args.motd_pages,
            'showMotdAlways': user_args.show_motd_always
        }

        return render_template(
            'users.html',
            version=version,
            lang=user_args.locale,
            map_title=user_args.map_title,
            custom_favicon=user_args.custom_favicon,
            header_image=not user_args.no_header_image,
            header_image_name=user_args.header_image,
            madmin_url=user_args.madmin_url,
            donate_url=user_args.donate_url,
            patreon_url=user_args.patreon_url,
            discord_url=user_args.discord_url,
            messenger_url=user_args.messenger_url,
            telegram_url=user_args.telegram_url,
            whatsapp_url=user_args.whatsapp_url,
            analytics_id=user_args.analytics_id,
            pokemon_history_page=(not user_args.no_pokemon
                                  and not user_args.no_pokemon_history_page),
            quest_page=(not user_args.no_pokestops and not user_args.no_quests
                        and not user_args.no_quest_page),
            settings=settings)

    @app.route('/raw-data')
    @auth_required
    def raw_data(*_args, **kwargs):
        if not kwargs['has_permission']:
            abort(401)

        user_args = get_args(kwargs['access_config'])

        # Make sure fingerprint isn't blacklisted.
        fingerprint_blacklisted = any([
            fingerprints['no_referrer'](request),
            fingerprints['iPokeGo'](request)
        ])

        if fingerprint_blacklisted:
            log.debug('User denied access: blacklisted fingerprint.')
            abort(403)

        d = {}

        # Request time of this request.
        d['timestamp'] = datetime.utcnow()

        # Request time of previous request.
        if request.args.get('timestamp'):
            timestamp = int(request.args.get('timestamp'))
            timestamp -= 1000  # Overlap, for rounding errors.
        else:
            timestamp = 0

        swLat = request.args.get('swLat')
        swLng = request.args.get('swLng')
        neLat = request.args.get('neLat')
        neLng = request.args.get('neLng')

        oSwLat = request.args.get('oSwLat')
        oSwLng = request.args.get('oSwLng')
        oNeLat = request.args.get('oNeLat')
        oNeLng = request.args.get('oNeLng')

        # Previous switch settings.
        lastpokemon = request.args.get('lastpokemon')
        lastgyms = request.args.get('lastgyms')
        lastpokestops = request.args.get('lastpokestops')
        lastspawns = request.args.get('lastspawns')
        lastscannedlocs = request.args.get('lastscannedlocs')
        lastweather = request.args.get('lastweather')

        # Current switch settings saved for next request.
        if request.args.get('pokemon', 'true') == 'true':
            d['lastpokemon'] = True

        if (request.args.get('gyms', 'true') == 'true'
                or request.args.get('raids', 'true') == 'true'):
            d['lastgyms'] = True

        if (request.args.get('pokestops', 'true') == 'true'
                and (request.args.get('pokestopsNoEvent', 'true') == 'true'
                     or request.args.get('quests', 'true') == 'true'
                     or request.args.get('invasions', 'true') == 'true'
                     or request.args.get('lures', 'true') == 'true')):
            d['lastpokestops'] = True

        if request.args.get('spawnpoints', 'false') == 'true':
            d['lastspawns'] = True

        if request.args.get('scannedLocs', 'false') == 'true':
            d['lastscannedlocs'] = True

        if request.args.get('weather', 'false') == 'true':
            d['lastweather'] = True

        if (oSwLat is not None and oSwLng is not None and oNeLat is not None
                and oNeLng is not None):
            # If old coords are not equal to current coords we have
            # moved/zoomed!
            if (oSwLng < swLng and oSwLat < swLat and oNeLat > neLat
                    and oNeLng > neLng):
                newArea = False  # We zoomed in no new area uncovered.
            elif not (oSwLat == swLat and oSwLng == swLng and oNeLat == neLat
                      and oNeLng == neLng):
                newArea = True
            else:
                newArea = False

        # Pass current coords as old coords.
        d['oSwLat'] = swLat
        d['oSwLng'] = swLng
        d['oNeLat'] = neLat
        d['oNeLng'] = neLng

        if (request.args.get('pokemon', 'true') == 'true'
                and not user_args.no_pokemon):
            verified_despawn = user_args.verified_despawn_time
            eids = None
            ids = None
            if (request.args.get('eids')
                    and request.args.get('prionotif', 'false') == 'false'):
                request_eids = request.args.get('eids').split(',')
                eids = [int(i) for i in request_eids]
            elif not request.args.get('eids') and request.args.get('ids'):
                request_ids = request.args.get('ids').split(',')
                ids = [int(i) for i in request_ids]

            if lastpokemon != 'true':
                # If this is first request since switch on, load
                # all pokemon on screen.
                d['pokemons'] = convert_pokemon_list(
                    Pokemon.get_active(swLat,
                                       swLng,
                                       neLat,
                                       neLng,
                                       eids=eids,
                                       ids=ids,
                                       verified_despawn_time=verified_despawn))
            else:
                # If map is already populated only request modified Pokemon
                # since last request time.
                d['pokemons'] = convert_pokemon_list(
                    Pokemon.get_active(swLat,
                                       swLng,
                                       neLat,
                                       neLng,
                                       timestamp=timestamp,
                                       eids=eids,
                                       ids=ids,
                                       verified_despawn_time=verified_despawn))

                if newArea:
                    # If screen is moved add newly uncovered Pokemon to the
                    # ones that were modified since last request time.
                    d['pokemons'] += (convert_pokemon_list(
                        Pokemon.get_active(
                            swLat,
                            swLng,
                            neLat,
                            neLng,
                            oSwLat=oSwLat,
                            oSwLng=oSwLng,
                            oNeLat=oNeLat,
                            oNeLng=oNeLng,
                            eids=eids,
                            ids=ids,
                            verified_despawn_time=verified_despawn)))

            if request.args.get('reids'):
                request_reids = request.args.get('reids').split(',')
                reids = [int(x) for x in request_reids]
                d['pokemons'] += convert_pokemon_list(
                    Pokemon.get_active(swLat,
                                       swLng,
                                       neLat,
                                       neLng,
                                       ids=ids,
                                       verified_despawn_time=verified_despawn))
                d['reids'] = reids

        if request.args.get('seen', 'false') == 'true':
            d['seen'] = Pokemon.get_seen(int(request.args.get('duration')))

        if request.args.get('appearances', 'false') == 'true':
            d['appearances'] = Pokemon.get_appearances(
                request.args.get('pokemonid'), request.args.get('formid'),
                int(request.args.get('duration')))

        if request.args.get('appearancesDetails', 'false') == 'true':
            d['appearancesTimes'] = (
                Pokemon.get_appearances_times_by_spawnpoint(
                    request.args.get('pokemonid'),
                    request.args.get('spawnpoint_id'),
                    request.args.get('formid'),
                    int(request.args.get('duration'))))

        gyms = (request.args.get('gyms', 'true') == 'true'
                and not user_args.no_gyms)
        raids = (request.args.get('raids', 'true') == 'true'
                 and not user_args.no_raids)
        if gyms or raids:
            if lastgyms != 'true':
                d['gyms'] = Gym.get_gyms(swLat,
                                         swLng,
                                         neLat,
                                         neLng,
                                         raids=raids)
            else:
                d['gyms'] = Gym.get_gyms(swLat,
                                         swLng,
                                         neLat,
                                         neLng,
                                         timestamp=timestamp,
                                         raids=raids)
                if newArea:
                    d['gyms'].update(
                        Gym.get_gyms(swLat,
                                     swLng,
                                     neLat,
                                     neLng,
                                     oSwLat=oSwLat,
                                     oSwLng=oSwLng,
                                     oNeLat=oNeLat,
                                     oNeLng=oNeLng,
                                     raids=raids))

        pokestops = (request.args.get('pokestops', 'true') == 'true'
                     and not user_args.no_pokestops)
        pokestopsNoEvent = (request.args.get('pokestopsNoEvent',
                                             'true') == 'true')
        quests = (request.args.get('quests', 'true') == 'true'
                  and not user_args.no_quests)
        invasions = (request.args.get('invasions', 'true') == 'true'
                     and not user_args.no_invasions)
        lures = (request.args.get('lures', 'true') == 'true'
                 and not user_args.no_lures)
        if (pokestops and (pokestopsNoEvent or quests or invasions or lures)):
            if lastpokestops != 'true':
                d['pokestops'] = Pokestop.get_pokestops(
                    swLat,
                    swLng,
                    neLat,
                    neLng,
                    eventless_stops=pokestopsNoEvent,
                    quests=quests,
                    invasions=invasions,
                    lures=lures)
            else:
                d['pokestops'] = Pokestop.get_pokestops(
                    swLat,
                    swLng,
                    neLat,
                    neLng,
                    timestamp=timestamp,
                    eventless_stops=pokestopsNoEvent,
                    quests=quests,
                    invasions=invasions,
                    lures=lures)
                if newArea:
                    d['pokestops'].update(
                        Pokestop.get_pokestops(
                            swLat,
                            swLng,
                            neLat,
                            neLng,
                            oSwLat=oSwLat,
                            oSwLng=oSwLng,
                            oNeLat=oNeLat,
                            oNeLng=oNeLng,
                            eventless_stops=pokestopsNoEvent,
                            quests=quests,
                            invasions=invasions,
                            lures=lures))

        if (request.args.get('weather', 'false') == 'true'
                and not user_args.no_weather):
            if lastweather != 'true':
                d['weather'] = Weather.get_weather(swLat, swLng, neLat, neLng)
            else:
                d['weather'] = Weather.get_weather(swLat,
                                                   swLng,
                                                   neLat,
                                                   neLng,
                                                   timestamp=timestamp)
                if newArea:
                    d['weather'] += Weather.get_weather(swLat,
                                                        swLng,
                                                        neLat,
                                                        neLng,
                                                        oSwLat=oSwLat,
                                                        oSwLng=oSwLng,
                                                        oNeLat=oNeLat,
                                                        oNeLng=oNeLng)

        if (request.args.get('spawnpoints', 'false') == 'true'
                and not user_args.no_spawnpoints):
            if lastspawns != 'true':
                d['spawnpoints'] = TrsSpawn.get_spawnpoints(swLat=swLat,
                                                            swLng=swLng,
                                                            neLat=neLat,
                                                            neLng=neLng)
            else:
                d['spawnpoints'] = TrsSpawn.get_spawnpoints(
                    swLat=swLat,
                    swLng=swLng,
                    neLat=neLat,
                    neLng=neLng,
                    timestamp=timestamp)
                if newArea:
                    d['spawnpoints'] += TrsSpawn.get_spawnpoints(swLat,
                                                                 swLng,
                                                                 neLat,
                                                                 neLng,
                                                                 oSwLat=oSwLat,
                                                                 oSwLng=oSwLng,
                                                                 oNeLat=oNeLat,
                                                                 oNeLng=oNeLng)

        if (request.args.get('scannedLocs', 'false') == 'true'
                and not user_args.no_scanned_locs):
            if lastscannedlocs != 'true':
                d['scannedlocs'] = ScannedLocation.get_recent(
                    swLat, swLng, neLat, neLng)
            else:
                d['scannedlocs'] = ScannedLocation.get_recent(
                    swLat, swLng, neLat, neLng, timestamp=timestamp)
                if newArea:
                    d['scannedlocs'] += ScannedLocation.get_recent(
                        swLat,
                        swLng,
                        neLat,
                        neLng,
                        oSwLat=oSwLat,
                        oSwLng=oSwLng,
                        oNeLat=oNeLat,
                        oNeLng=oNeLng)

        return jsonify(d)

    @app.route('/raw-data/users')
    def users_data():
        if not args.client_auth:
            abort(404)

        # Make sure fingerprint isn't blacklisted.
        fingerprint_blacklisted = any([
            fingerprints['no_referrer'](request),
            fingerprints['iPokeGo'](request)
        ])

        if fingerprint_blacklisted:
            log.debug('User denied access: blacklisted fingerprint.')
            abort(403)

        if not is_admin():
            abort(403)

        sessions = get_sessions(app.config['SESSION_REDIS'])
        users = []
        for s in sessions:
            if 'auth_type' not in s or 'access_data_updated_at' not in s:
                continue
            del s['_permanent']
            del s['has_permission']
            del s['access_data_updated_at']
            if s['auth_type'] == 'discord':
                del s['token']
            users.append(s)

        return jsonify(users)

    @app.route('/pkm_img')
    def pokemon_img():
        raw = 'raw' in request.args
        pkm = int(request.args.get('pkm'))
        weather = int(
            request.args.get('weather')) if 'weather' in request.args else 0
        gender = int(
            request.args.get('gender')) if 'gender' in request.args else None
        form = int(
            request.args.get('form')) if 'form' in request.args else None
        costume = int(
            request.args.get('costume')) if 'costume' in request.args else None
        shiny = 'shiny' in request.args

        if raw:
            filename = get_pokemon_raw_icon(pkm,
                                            gender=gender,
                                            form=form,
                                            costume=costume,
                                            weather=weather,
                                            shiny=shiny)
        else:
            filename = get_pokemon_map_icon(pkm,
                                            weather=weather,
                                            gender=gender,
                                            form=form,
                                            costume=costume)
        return send_file(filename, mimetype='image/png')

    @app.route('/gym_img')
    def gym_img():
        team = request.args.get('team')
        level = request.args.get('level')
        raidlevel = request.args.get('raidlevel')
        pkm = request.args.get('pkm')
        form = request.args.get('form')
        costume = int(
            request.args.get('costume')) if 'costume' in request.args else None
        is_in_battle = 'in_battle' in request.args
        is_ex_raid_eligible = 'is_ex_raid_eligible' in request.args

        if level is None or raidlevel is None:
            return send_file(get_gym_icon(team, level, raidlevel, pkm,
                                          is_in_battle, form, costume,
                                          is_ex_raid_eligible),
                             mimetype='image/png')

        elif (int(level) < 0 or int(level) > 6 or int(raidlevel) < 0
              or int(raidlevel) > 5):
            return abort(416)

        else:
            return send_file(get_gym_icon(team, level, raidlevel, pkm,
                                          is_in_battle, form, costume,
                                          is_ex_raid_eligible),
                             mimetype='image/png')

    @app.route('/robots.txt')
    def render_robots_txt():
        return render_template('robots.txt')

    @app.route('/serviceWorker.min.js')
    def render_service_worker_js():
        return send_from_directory('../static/dist/js', 'serviceWorker.min.js')

    return app
Exemple #49
0
from flask import Flask, g, jsonify, render_template, json, request
import psycopg2
import psycopg2.pool
import psycopg2.extras
from oauth2client.client import flow_from_clientsecrets

from . import db
from .config import config, ISO8601Encoder
from .data import FULL_CAP_DATA

app = Flask(__name__)
app.config.update(**config)

# change the default JSON encoder to handle datetime's properly
app.json_encoder = ISO8601Encoder

CU_EMAIL_REGEX = r"^(?P<uni>[a-z\d]+)@.*(columbia|barnard)\.edu$"
request_date_format = '%Y-%m-%d'

# create a pool of postgres connections
pg_pool = psycopg2.pool.SimpleConnectionPool(
    5,  # min connections
    20,  # max connections
    database=app.config['PG_DB'],
    user=app.config['PG_USER'],
    password=app.config['PG_PASSWORD'],
    host=app.config['PG_HOST'],
    port=app.config['PG_PORT'],
)
from flask import Flask
import asyncio
import json
from bson.objectid import ObjectId
from flask_pymongo import PyMongo
from datetime import datetime


class JSONEncoder(json.JSONEncoder):
    ''' extend json-encoder class '''
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        if isinstance(o, datetime):
            return str(o)
        return json.JSONEncoder.default(self, o)


app = Flask(__name__, template_folder='public')

app.config.from_object(
    'app.conf.Config')  # Loading conf from Config class in conf.py
mongo = PyMongo(app)  # Loadig mongo client using app.conf
db = mongo.db.tracker

app.json_encoder = JSONEncoder  # Using custom encoder

from app import routes  # Loading routes
Exemple #51
0
# -*- coding: utf-8 -*-
'''
Created on 11.01.2018

@author: Sebastian.Thiems
'''

from flask import Flask, render_template, send_from_directory, jsonify, make_response

from ConfigurationService import ConfigurationService
from DashJSONEncoder import DashJSONEncoder

app = Flask(__name__, template_folder='html/')
app.json_encoder = DashJSONEncoder
configuration_service = ConfigurationService()


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')


@app.route('/js/<path:path>')
def get_javascript_files(path):
    return send_from_directory('js', path)


@app.route('/css/<path:path>')
def get_css_files(path):
    return send_from_directory('css', path)
Exemple #52
0
from pydoc import locate
from uuid import uuid4

import click
import datetime
import json
import os
import requests
import sys
import time

os.environ['TZ'] = 'UTC'

app = Flask(__name__)
app.config.from_pyfile("{}/app.cfg".format(os.getcwd()))
app.json_encoder = GerritJSONEncoder

db = MongoEngine(app)
cache = Cache(app)
gerrit = GerritServer(app.config['GERRIT_URL'])


def api_key_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(request.headers)
        if 'Apikey' in request.headers:
            if ApiKey.objects(apikey=request.headers.get('Apikey')).first():
                return f(*args, **kwargs)
        return abort(403)
Exemple #53
0
from flask_swagger import swagger

# setup the configuration for the application
from habt.config import Config
from habt.database import session
from habt.manager import PackageManager

# Configure the logger
config = Config()
config.setup_logger()
log = logging.getLogger(__name__)

app = Flask(__name__)
app.debug = config.debug
# uses the <obj>.__json__() method to encode json
app.json_encoder = DynamicJSONEncoder


@app.teardown_appcontext
def shutdown_session(exception=None):
    """
        Destroy the Database session at the end of a request
    """
    session.remove()


@app.route("/spec")
@cross_origin()
def spec():
    """
        returns:
Exemple #54
0
                "description":
                "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\""
            }
        },
        "security": [{
            "Bearer": []
        }]
    }

    app.config['SWAGGER'] = {
        'title': 'My API',
        'uiversion': 3,
        "specs_route": "/swagger/"
    }

    app.json_encoder = my_json_encoder.MyJSONEncoder

    swagger = Swagger(app, template=template)
    app.config.from_object(config.Config)

    # app.config['JSON_SORT_KEYS'] = False
    api = Api(app)

    # api.add_resource(Quote, "/ai-quotes", "/ai-quotes/", "/ai-quotes/<int:id>")

    # api.add_resource(user_profile.UserProfile, '/users', endpoint='/users')
    api.add_resource(user_profile.UserProfile,
                     '/users/<user_id>',
                     endpoint='/users/<user_id>')

    api.add_resource(advertisement.Advertisement, '/advertises')
Exemple #55
0
def create_app(config=None, testing=False):
    """Create a new instance of Airflow WWW app"""
    flask_app = Flask(__name__)
    flask_app.secret_key = conf.get('webserver', 'SECRET_KEY')

    flask_app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(
        minutes=settings.get_session_lifetime_config())
    flask_app.config.from_pyfile(settings.WEBSERVER_CONFIG, silent=True)
    flask_app.config['APP_NAME'] = conf.get(section="webserver",
                                            key="instance_name",
                                            fallback="Airflow")
    flask_app.config['TESTING'] = testing
    flask_app.config['SQLALCHEMY_DATABASE_URI'] = conf.get(
        'core', 'SQL_ALCHEMY_CONN')
    flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    flask_app.config['SESSION_COOKIE_HTTPONLY'] = True
    flask_app.config['SESSION_COOKIE_SECURE'] = conf.getboolean(
        'webserver', 'COOKIE_SECURE')

    cookie_samesite_config = conf.get('webserver', 'COOKIE_SAMESITE')
    if cookie_samesite_config == "":
        warnings.warn(
            "Old deprecated value found for `cookie_samesite` option in `[webserver]` section. "
            "Using `Lax` instead. Change the value to `Lax` in airflow.cfg to remove this warning.",
            DeprecationWarning,
        )
        cookie_samesite_config = "Lax"
    flask_app.config['SESSION_COOKIE_SAMESITE'] = cookie_samesite_config

    if config:
        flask_app.config.from_mapping(config)

    if 'SQLALCHEMY_ENGINE_OPTIONS' not in flask_app.config:
        flask_app.config[
            'SQLALCHEMY_ENGINE_OPTIONS'] = settings.prepare_engine_args()

    # Configure the JSON encoder used by `|tojson` filter from Flask
    flask_app.json_encoder = AirflowJsonEncoder

    csrf.init_app(flask_app)

    init_wsgi_middleware(flask_app)

    db = SQLA()
    db.session = settings.Session
    db.init_app(flask_app)

    init_dagbag(flask_app)

    init_api_experimental_auth(flask_app)

    init_robots(flask_app)

    cache_config = {
        'CACHE_TYPE': 'flask_caching.backends.filesystem',
        'CACHE_DIR': gettempdir()
    }
    Cache(app=flask_app, config=cache_config)

    init_flash_views(flask_app)

    configure_logging()
    configure_manifest_files(flask_app)

    with flask_app.app_context():
        init_appbuilder(flask_app)

        init_appbuilder_views(flask_app)
        init_appbuilder_links(flask_app)
        init_plugins(flask_app)
        init_connection_form()
        init_error_handlers(flask_app)
        init_api_connexion(flask_app)
        init_api_experimental(flask_app)

        sync_appbuilder_roles(flask_app)

        init_jinja_globals(flask_app)
        init_xframe_protection(flask_app)
        init_airflow_session_interface(flask_app)
    return flask_app
Exemple #56
0
def create_app(config: "SDConfig") -> Flask:
    app = Flask(
        __name__,
        template_folder=config.JOURNALIST_TEMPLATES_DIR,
        static_folder=path.join(config.SECUREDROP_ROOT, "static"),
    )

    app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS)
    app.session_interface = JournalistInterfaceSessionInterface()

    csrf = CSRFProtect(app)

    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI
    db.init_app(app)

    class JSONEncoder(json.JSONEncoder):
        """Custom JSON encoder to use our preferred timestamp format"""

        def default(self, obj: "Any") -> "Any":
            if isinstance(obj, datetime):
                return obj.strftime(API_DATETIME_FORMAT)
            super(JSONEncoder, self).default(obj)

    app.json_encoder = JSONEncoder

    # TODO: enable type checking once upstream Flask fix is available. See:
    # https://github.com/pallets/flask/issues/4295
    @app.errorhandler(CSRFError)  # type: ignore
    def handle_csrf_error(e: CSRFError) -> "Response":
        app.logger.error("The CSRF token is invalid.")
        session.clear()
        msg = gettext("You have been logged out due to inactivity.")
        flash(msg, "error")
        return redirect(url_for("main.login"))

    def _handle_http_exception(
        error: "HTTPException",
    ) -> "Tuple[Union[Response, str], Optional[int]]":
        # Workaround for no blueprint-level 404/5 error handlers, see:
        # https://github.com/pallets/flask/issues/503#issuecomment-71383286
        # TODO: clean up API error handling such that all except 404/5s are
        # registered in the blueprint and 404/5s are handled at the application
        # level.
        handler = list(app.error_handler_spec["api"][error.code].values())[0]
        if request.path.startswith("/api/") and handler:
            return handler(error)  # type: ignore

        return render_template("error.html", error=error), error.code

    for code in default_exceptions:
        app.errorhandler(code)(_handle_http_exception)

    i18n.configure(config, app)

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True
    app.jinja_env.globals["version"] = version.__version__
    app.jinja_env.filters["rel_datetime_format"] = template_filters.rel_datetime_format
    app.jinja_env.filters["filesizeformat"] = template_filters.filesizeformat
    app.jinja_env.filters["html_datetime_format"] = template_filters.html_datetime_format
    app.jinja_env.add_extension("jinja2.ext.do")

    @app.before_first_request
    def expire_blacklisted_tokens() -> None:
        cleanup_expired_revoked_tokens()

    @app.before_request
    def update_instance_config() -> None:
        InstanceConfig.get_default(refresh=True)

    @app.before_request
    def setup_g() -> "Optional[Response]":
        """Store commonly used values in Flask's special g object"""
        if "expires" in session and datetime.now(timezone.utc) >= session["expires"]:
            session.clear()
            flash(gettext("You have been logged out due to inactivity."), "error")

        uid = session.get("uid", None)
        if uid:
            user = Journalist.query.get(uid)
            if user and "nonce" in session and session["nonce"] != user.session_nonce:
                session.clear()
                flash(gettext("You have been logged out due to password change"), "error")

        session["expires"] = datetime.now(timezone.utc) + timedelta(
            minutes=getattr(config, "SESSION_EXPIRATION_MINUTES", 120)
        )

        uid = session.get("uid", None)
        if uid:
            g.user = Journalist.query.get(uid)  # pylint: disable=assigning-non-slot

        i18n.set_locale(config)

        if InstanceConfig.get_default().organization_name:
            g.organization_name = (  # pylint: disable=assigning-non-slot
                InstanceConfig.get_default().organization_name
            )
        else:
            g.organization_name = gettext("SecureDrop")  # pylint: disable=assigning-non-slot

        try:
            g.logo = get_logo_url(app)  # pylint: disable=assigning-non-slot
        except FileNotFoundError:
            app.logger.error("Site logo not found.")

        if request.path.split("/")[1] == "api":
            pass  # We use the @token_required decorator for the API endpoints
        else:  # We are not using the API
            if request.endpoint not in _insecure_views and not logged_in():
                return redirect(url_for("main.login"))

        if request.method == "POST":
            filesystem_id = request.form.get("filesystem_id")
            if filesystem_id:
                g.filesystem_id = filesystem_id  # pylint: disable=assigning-non-slot
                g.source = get_source(filesystem_id)  # pylint: disable=assigning-non-slot

        return None

    app.register_blueprint(main.make_blueprint(config))
    app.register_blueprint(account.make_blueprint(config), url_prefix="/account")
    app.register_blueprint(admin.make_blueprint(config), url_prefix="/admin")
    app.register_blueprint(col.make_blueprint(config), url_prefix="/col")
    api_blueprint = api.make_blueprint(config)
    app.register_blueprint(api_blueprint, url_prefix="/api/v1")
    csrf.exempt(api_blueprint)

    return app
Exemple #57
0
from flask import Flask, render_template, session, redirect, request, url_for, g, jsonify
from flask_restful import reqparse, Resource, Api
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_script import Manager, Server
from flask_oauthlib.client import OAuth
from flask_socketio import SocketIO

from utils import DecimalEncoder
from config import DevConfig, ProdConfig
from tweepy import OAuthHandler
import boto

application = Flask(__name__)
application.json_encoder = DecimalEncoder

conn = None
s3_bucket = None
if not 'FLASK_DEBUG' in os.environ or os.environ['FLASK_DEBUG'] == '1':
    application.config.from_object(DevConfig)
elif os.environ['FLASK_DEBUG'] == '0':
    application.config.from_object(ProdConfig)
conn = boto.connect_s3(application.config['AWS_ACCESS_KEY_ID'],
                       application.config['AWS_SECRET_ACCESS_KEY'])
s3_bucket = conn.get_bucket(application.config['S3_BUCKET'])

twitter = OAuthHandler(application.config['TWITTER_KEY'],
                       application.config['TWITTER_SECRET'])
socketio = SocketIO(application)
db = SQLAlchemy(application)
Exemple #58
0
from flask import Flask, render_template, request, send_from_directory, jsonify
from flask_socketio import SocketIO, emit

from skep.json import DelegatingJSONEncoder

application = Flask(__name__,
                    template_folder=os.path.join(
                        os.path.dirname(os.path.abspath(__file__)),
                        'templates'))

if os.environ.get('FLASK_SECRET_KEY', None):
    application.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY']
else:
    application.config['SECRET_KEY'] = secrets.token_hex(32)

application.json_encoder = DelegatingJSONEncoder
socketio = SocketIO(application)
cache = {}

SECRET = os.environ.get('SKEP_SECRET', None)


@application.route('/files/<path:path>')
def files(path):
    return send_from_directory('files', path)


@application.route("/")
def root():
    return render_template('layout.html',
                           env=os.environ.get('SKEP_ENV', 'production'),
Exemple #59
0
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, redirect, url_for
from control.dbimagecontrol import ImageControl
from control.dbimagesourcecontrol import ImageSourceControl
from control.dbtagcontrol import TagControl
from control.dbaditagcontrol import AdiTagControl
from model.tag import Tag
from model.image import Image
from model.imagesource import ImageSource
from model.aditag import AdiTag
import control.formats as formats

app = Flask(__name__, static_url_path='')
app.json_encoder = formats.JSONDateEncoder

ctrImage = ImageControl()
ctrImgSource = ImageSourceControl()
ctrTag = TagControl()
ctrAdiTag = AdiTagControl()


@app.route('/')
def index():
    return app.send_static_file("index.html")


@app.route('/image', methods=['GET'])
def image_list():
    jsonImageList = []

    page = request.args.get('page', 1, type=int)
Exemple #60
0
from app.notifications.builder import NotificationBuilder
from app.notifications.templates import TemplateManager
from app.orm import *
from app.sc_logging import web_logger as log
from app.util import SC, Clock, get_tmp_dir
from ui import UI

BASE_DIR = os.path.join(sc_dir(), 'view')
STATIC_DIR = os.path.join(sc_dir(), 'view', 'assets')
app = Flask(__name__, template_folder=BASE_DIR, static_folder=STATIC_DIR)

################################ Login ################################

app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
app.json_encoder = AlchemyEncoder
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'index'


# send Angular 2 files
@app.route('/<path:filename>')
def client_app_angular2_folder(filename):
    return send_from_directory(os.path.join(BASE_DIR), filename)


@login_manager.user_loader
@dbconnect
def load_user(user_id, session=None):
    user = session.query(User).filter(