Exemple #1
0
def create():
    """Create application.
    """

    # Create application
    app = Flask('service', static_folder=None)
    app.config['DEBUG'] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['SECRET_KEY'] = 'openspending rocks'
    sess.init_app(app)

    # Register blueprints
    print("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix='/datastore')
    print("Creating API Loader Blueprint")
    app.register_blueprint(apiload.create(), url_prefix='/hooks/load/')
    print("Creating Authentication Blueprint")
    app.register_blueprint(authentication.create(), url_prefix='/oauth/')
    print("Creating Authorization Blueprint")
    app.register_blueprint(authorization.create(), url_prefix='/permit/')
    print("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix='/search/')

    # Return application
    return app
Exemple #2
0
def create():
    """Create application.
    """

    # Create application
    app = Flask("service", static_folder=None)
    app.config["DEBUG"] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config["SESSION_TYPE"] = "filesystem"
    app.config["SECRET_KEY"] = "openspending rocks"
    sess.init_app(app)

    # Register blueprints
    logger.info("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix="/datastore/")
    logger.info("Creating Package Blueprint")
    app.register_blueprint(package.create(), url_prefix="/package/")
    logger.info("Creating Authentication Blueprint")
    app.register_blueprint(user.oauth_create(), url_prefix="/oauth/")
    logger.info("Creating Users Blueprint")
    app.register_blueprint(user.create(), url_prefix="/user/")
    logger.info("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix="/search/")

    # Return application
    return app
Exemple #3
0
def create_app(**config):
    """
    Create the application and return it to the user
    :return: flask.Flask application
    """

    app = AbovlADSFlask('arxiv_biboverlay', local_config=config)
    app.url_map.strict_slashes = False
    app.register_blueprint(bp)

    sess = Session()
    sess.init_app(app)

    return app
Exemple #4
0
def create():
    """Create application.
    """

    # Create application
    app = Flask('service', static_folder=None)
    app.config['DEBUG'] = True

    # Respect X-Forwarding-* headers
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CORS support
    CORS(app, supports_credentials=True)

    # Exception logging
    Sentry(app, dsn=os.environ.get('SENTRY_DSN', ''))

    # Session
    sess = Session()
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['SECRET_KEY'] = 'openspending rocks'
    sess.init_app(app)

    # Register blueprints
    logger.info("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix='/datastore/')
    logger.info("Creating Package Blueprint")
    app.register_blueprint(package.create(), url_prefix='/package/')
    logger.info("Creating Authentication Blueprint")
    app.register_blueprint(user.oauth_create(), url_prefix='/oauth/')
    logger.info("Creating Users Blueprint")
    app.register_blueprint(user.create(), url_prefix='/user/')
    logger.info("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix='/search/')

    # Return application
    return app
Exemple #5
0
        else:
            name.append(word)

    recipeDict['name'] = " ".join(name)

    # clean ingredients
    for ingredient in recipeDict['ingredients']:
        if ingredient['name'] in substitutes.keys():
            ingredient['name'] = substitutes[ingredient['name']]

    return recipeDict


def make_easy(recipeDict, substitutes):
    for ingredient in recipeDict['ingredients']:
        if ingredient['name'] in substitutes.keys():
            ingredient['name'] = '<a href=\"' + substitutes[ingredient[
                'name']][0] + '\"" target=\"_blank\">' + 'DIY ' + ingredient[
                    'name'] + ' (click me!)</a>'

    return recipeDict


if __name__ == '__main__':
    app.secret_key = 'tangerine prophet'
    app.config['SESSION_TYPE'] = 'filesystem'

    sess.init_app(app)
    app.debug = True
    app.run()
Exemple #6
0
def send_to_indico():

    path = os.path.dirname(os.path.abspath(__file__)) + "/static/img/pictures/" + session['name']

    selfie_list = []
    for f in os.listdir(path):
        new_path = os.path.join(path, f)
        if os.path.isfile(new_path) and f[f.index('.')+1:] in ALLOWED_EXTENSIONS:
            selfie_list.append(new_path)
    print selfie_list

    emotion_scores = indicoio.batch_fer(selfie_list, api_key="0f73d0a7c698469192cbd74886b48615")

    emotions = []
    emotion_values = []
    [emotions.extend(snapshot.keys()+['break']) for snapshot in emotion_scores]
    [emotion_values.extend(snapshot.values()+[0]) for snapshot in emotion_scores]

    print 'emotions', emotions, '\n', 'emotion_values', emotion_values
    return json.dumps({'scores': emotion_values, 'labels': emotions})


if __name__ == '__main__':
    app.config["UPLOAD_FOLDER"] = "/static/img/pictures/"
    app.config["SESSION_TYPE"] = "filesystem"

    app.secret_key = "woah it's a secret!"
    sess.init_app(app)

    app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 5000)), processes=2)
Exemple #7
0
    # print(closest[np.where(centroids == [x_co, y_co])[0]-1])
    mylist = np.where(centroids == [x_co, y_co])
    print(mylist[0][0])
    return render_template("newindex.html", result=trained_minnow['Fname'][mylist[0][0]])

@application.route('/myrest', methods=['GET'])
def myrest():
    sse = []
    myrange = range(1, 10, 1)
    graph_x = []
    x_column = request.args['x_value']
    y_column = request.args['y_value']
    for k in myrange:
        km = KMeans(n_clusters=k)
        km.fit(trained_minnow[[x_column, y_column]])
        graph_x.append(k)
        sse.append(km.inertia_)
    graph_data = { 'x': graph_x, 'y': sse }
    return render_template('newindex.html', graph_data=graph_data)


# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    application.secret_key = 'super secret key'
    application.config['SESSION_TYPE'] = 'filesystem'

    sess.init_app(application)
    application.debug = True
    application.run()
Exemple #8
0
def init(conf=None, debug=0, logfile=None, gunicorn=True, unittest=False):
    """Initialize the whole application.

    :param conf: Configuration file to use
    :type conf: str

    :param debug: Enable verbose output
    :type debug: int

    :param logfile: Store the logs in the given file
    :type logfile: str

    :param gunicorn: Enable gunicorn engine instead of flask's default
    :type gunicorn: bool

    :returns: A :class:`burpui.server.BUIServer` object
    """
    from flask.ext.login import LoginManager
    from flask.ext.bower import Bower
    from .utils import basic_login_from_request
    from .server import BUIServer as BurpUI
    from .routes import view
    from .api import api, apibp

    if not unittest:
        from ._compat import patch_json
        patch_json()

    if gunicorn:
        from gevent import monkey
        monkey.patch_all()

    # We initialize the core
    app = BurpUI()
    app.gunicorn = gunicorn

    app.config['CFG'] = None

    app.secret_key = ('VpgOXNXAgcO81xFPyWj07ppN6kExNZeCDRShseNzFKV7ZCgmW2/eLn6x'
                      'Slt7pYAVBj12zx2Vv9Kw3Q3jd1266A==')
    app.jinja_env.globals.update(
        isinstance=isinstance,
        list=list,
        version_id='{}-{}'.format(__version__, __release__)
    )

    # The debug argument used to be a boolean so we keep supporting this format
    if isinstance(debug, bool):
        if debug:
            debug = logging.DEBUG
        else:
            debug = logging.NOTSET
    else:
        levels = [
            logging.NOTSET,
            logging.ERROR,
            logging.WARNING,
            logging.INFO,
            logging.DEBUG
        ]
        if debug >= len(levels):
            debug = len(levels) - 1
        if not debug:
            debug = 0
        debug = levels[debug]

    if debug != logging.NOTSET and not gunicorn:  # pragma: no cover
        app.config['DEBUG'] = True and not unittest
        app.config['TESTING'] = True and not unittest

    if logfile:
        from logging import Formatter
        from logging.handlers import RotatingFileHandler
        file_handler = RotatingFileHandler(
            logfile,
            maxBytes=1024 * 1024 * 100,
            backupCount=20
        )
        if debug < logging.INFO:
            LOG_FORMAT = (
                '-' * 80 + '\n' +
                '%(levelname)s in %(module)s.%(funcName)s ' +
                '[%(pathname)s:%(lineno)d]:\n' +
                '%(message)s\n' +
                '-' * 80
            )
        else:
            LOG_FORMAT = ('[%(asctime)s] %(levelname)s in '
                          '%(module)s.%(funcName)s: %(message)s')
        file_handler.setLevel(debug)
        file_handler.setFormatter(Formatter(LOG_FORMAT))
        app.logger.addHandler(file_handler)

    # Still need to test conf file here because the init function can be called
    # by gunicorn directly
    app.config['CFG'] = lookup_config(conf)

    app.setup(app.config['CFG'])

    if gunicorn:  # pragma: no cover
        from werkzeug.contrib.fixers import ProxyFix
        if app.storage and app.storage.lower() == 'redis':
            if app.redis:
                part = app.redis.split(':')
                host = part[0]
                try:
                    port = int(part[1])
                except:
                    port = 6379
            else:
                host = 'localhost'
                port = 6379
            try:
                from redis import Redis
                from flask.ext.session import Session
                red = Redis(host=host, port=port)
                app.config['SESSION_TYPE'] = 'redis'
                app.config['SESSION_REDIS'] = red
                ses = Session()
                ses.init_app(app)
            except:
                pass
            api.cache.init_app(
                app,
                config={
                    'CACHE_TYPE': 'redis',
                    'CACHE_REDIS_HOST': host,
                    'CACHE_REDIS_PORT': port,
                    'CACHE_REDIS_DB': 1
                }
            )
            # clear cache at startup in case we removed or added servers
            with app.app_context():
                api.cache.clear()
        else:
            api.cache.init_app(app)

        app.wsgi_app = ProxyFix(app.wsgi_app)
    else:
        api.cache.init_app(app)

    # Then we load our routes
    view.init_bui(app)
    view.__url__ = __url__
    view.__doc__ = __doc__
    app.register_blueprint(view)

    # We initialize the API
    api.init_bui(app)
    api.version = __version__
    api.release = __release__
    api.__url__ = __url__
    api.__doc__ = __doc__
    app.register_blueprint(apibp)

    # And the login_manager
    app.login_manager = LoginManager()
    app.login_manager.login_view = 'view.login'
    app.login_manager.login_message_category = 'info'
    app.login_manager.session_protection = 'strong'
    app.login_manager.init_app(app)

    app.config.setdefault(
        'BOWER_COMPONENTS_ROOT',
        os.path.join('static', 'vendor')
    )
    app.config.setdefault('BOWER_REPLACE_URL_FOR', True)
    bower = Bower()
    bower.init_app(app)

    @app.login_manager.user_loader
    def load_user(userid):
        """User loader callback"""
        if app.auth != 'none':
            return app.uhandler.user(userid)
        return None  # pragma: no cover

    @app.login_manager.request_loader
    def load_user_from_request(request):
        """User loader from request callback"""
        if app.auth != 'none':
            return basic_login_from_request(request, app)

    return app