Beispiel #1
1
def get_flask_app(project_dir):
    static_folder = os.path.join(project_dir, "build", "assets")
    app = Flask(__name__, static_folder=static_folder, static_url_path="/static")
    app.populus_project_dir = project_dir

    app.route("/")(index_view)
    return app
Beispiel #2
1
def create_app(config, oidc_overrides=None):
    app = Flask(__name__)
    app.config.update(config)
    if oidc_overrides is None:
        oidc_overrides = {}
    oidc = OpenIDConnect(app, **oidc_overrides)
    app.route("/")(oidc.check(index))
    return app
Beispiel #3
0
class Server(Greenlet):
    def __init__(self, name, addr, *args, **kwargs):
        Greenlet.__init__(self)
        self._application = Flask(name)
        self._server = WSGIServer(addr, self._application, *args, **kwargs)

        @self._application.errorhandler(404)
        def error_404(error):
            log.warning('web handler(%s) not found', request.path)
            return str(error), 404

        @self._application.errorhandler(Exception)
        def error_500(error):
            log.exception('web handler(%s) is error(%s)', request.path, error)
            return str(error), 500

    def _run(self):
        self._server.serve_forever()

    def close(self):
        self._server.stop()

    def getServer(self):
        return self._server

    def getApplication(self):
        return self._application

    def setHandler(self, handler, url=None, **kwargs):
        if not url:
            url = '/' + handler.__name__
        self._application.route(url, **kwargs)(handler)
Beispiel #4
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object("purepage.config_default")
    if config:
        app.config.from_object(config)
    app.url_map.converters['no'] = NoConverter
    app.route("/webhooks")(Webhooks())
    route_views(app)
    db.init_app(app)
    github.init_app(app)
    mail.init_app(app)
    limiter.init_app(app)

    bp_api = Blueprint('api', __name__, static_folder='static')
    api.init_app(app, blueprint=bp_api, docs=__doc__)
    for x in resources:
        api.add_resource(x)
    api.add_resource(Permission, auth=auth)
    auth.init_api(api, fn_user_role=fn_user_role)
    app.register_blueprint(bp_api, url_prefix='/api')

    gen = Gen(api)
    gen.resjs()
    gen.resdocs()
    gen.permission()
    return app
Beispiel #5
0
class S3Proxy(object):
    def __init__(self, bucket_name, path, key, secret, host, port):
        self.bucket_name = bucket_name
        self.path = path
        self.key = key
        self.secret = secret
        self.host = host
        self.port = port

        logging.basicConfig(
            format='%(asctime)s: %(name)s/%(levelname)-9s: %(message)s', level=logging.INFO)

        self.s3 = boto.s3.connection.S3Connection(self.key, self.secret)
        self.bucket = self.s3.get_bucket(self.bucket_name)

        self.app = Flask(self.__class__.__name__)
        #self.app.debug = True

        self.status = self.app.route('/__status')(self.status)
        self.handle = self.app.route('/<path:path>')(self.handle)

    def run(self):
        return self.app.run(
            host=self.host,
            port=self.port,
        )

    def status(self):
        return Response('{"status": "ok"}', mimetype='application/json')

    def handle(self, path):
        self.app.logger.debug('Request for path %r', path)
        self.app.logger.debug('s3://%s/%s%s', self.bucket_name, self.path, path)
        try:
            full_path = self.path + path
            self.app.logger.debug('full_path %r', full_path)
            if path.endswith('/'):
                return self.handle_directory(path)

            key = self.bucket.get_key(full_path)
            if key is None:
                # If we can't find a file, try it as a directory
                ### Note: Some versions of pip will make some requests for what
                ### should be directories without the trailing slash.
                keys = self.bucket.list(full_path + '/', '/')
                try:
                    iter(keys).next()
                    # there are keys to list, so send back a redirect so the client
                    # knows it should be treating this as a directory.
                    self.app.logger.warning(
                        'path does not end in / but is a directory, redirecting %r', path)
                    return redirect(path + '/')
                except StopIteration:
                    self.app.logger.warning('Key not found for path and not a directory %r', path)
                    return ('', 404)

            self.app.logger.info('Found key for path %r', path)
            return Response(key, mimetype='application/octet-stream')
        except Exception, e:
            return (str(e), 404)
Beispiel #6
0
def create_backend_app(service):
    from werkzeug.routing import Map

    # Create the backend_app
    backend_app = Flask(__name__)
    backend_app.debug = True

    # Reset view functions to reset the app
    backend_app.view_functions = {}
    backend_app.url_map = Map()
    backend_app.url_map.converters['regex'] = RegexConverter

    backend = BACKENDS[service]
    for url_path, handler in backend.flask_paths.items():
        if handler.__name__ == 'dispatch':
            endpoint = '{0}.dispatch'.format(handler.__self__.__name__)
        else:
            endpoint = None

        backend_app.route(
            url_path,
            endpoint=endpoint,
            methods=HTTP_METHODS)(convert_flask_to_httpretty_response(handler))

    return backend_app
Beispiel #7
0
def create_app():
    app = Flask(__name__)
    app.config["SQLITE"] = "todos.db"
    app.config["API_BOOTSTRAP"] = "/static/bootstrap.min.css"
    app.config["API_BOOTSTRAP"] = "/static/bootstrap.min.css"
    app.config["ADMIN_EMAIL"] = "admin@todos.com"
    app.config["ADMIN_PASSWORD"] = "123456"

    bp_api = Blueprint('api', __name__, static_folder='static')
    api.init_app(bp_api, fn_user_role=fn_user_role, docs=__doc__)
    api.config(app.config)

    api.add_resource(Todos)
    api.add_resource(User)
    api.add_permission_resource()

    api.before_request(connect_db)
    api.after_request(close_db)

    def make_view(filename):
        return lambda *args, **kwargs: app.send_static_file(filename)
    for url, filename in url_views:
        end = os.path.splitext(filename)[0]
        app.route(url, endpoint=end)(make_view(filename))

    app.before_first_request(before_first_request)
    app.register_blueprint(bp_api, url_prefix='/api')
    return app
Beispiel #8
0
def main():
	app = Flask(__name__)
	logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(message)s")
	logger = logging.getLogger("Extract english terms")

	extractor = WEBTermExtractor(logger)
	app.route('/', methods = ['POST'])(extractor.POST) 
	app.route('/', methods = ['GET'])(extractor.GET)
	app.run(host='', port=8500, threaded=True)
Beispiel #9
0
def create_app(config, oidc_overrides=None):
    app = Flask(__name__)
    app.config.update(config)
    if oidc_overrides is None:
        oidc_overrides = {}
    oidc = OpenIDConnect(app, **oidc_overrides)
    app.route('/')(oidc.check(index))
    app.route('/api', methods=['GET', 'POST'])(
        oidc.accept_token(True, ['openid'])(api))
    return app
Beispiel #10
0
def main():
    app = Flask(__name__)
    logfile, rootFolder = sys.argv[1:3]
    server = Server(logfile, rootFolder)
    app.route("/")(server.index)
    app.route("/loop")(server.loop)
    app.route("/expansion")(server.expansion)
    app.route("/directory")(server.getDirectory)
    app.route("/getFile")(server.getFile)
    app.run("0.0.0.0",5001,debug=True)
Beispiel #11
0
def flask_app(request, caplog):
    # Disable flask server logging
    caplog.setLevel(logging.ERROR, 'werkzeug')

    app = Flask(__name__)
    if request.param == 200:
        # Add root handler to test that FlaskApp processor can detect running
        # flask app properly both with and without root handler.
        app.route('/')(lambda: 'Homepage')

    return app
Beispiel #12
0
def create_app(db_uri, datadir=DEFAULT_DATA_DIR, echo=True, pull_password=None,
               host=None, port=5000):
    datadir = os.path.abspath(datadir)

    app = Flask(__name__)
    app.config.setdefault('SQLALCHEMY_DATABASE_URI', db_uri)
    app.config.setdefault('SQLALCHEMY_ECHO', echo)
    app.config.setdefault('PYVO_DATADIR', datadir)
    app.config.setdefault('PYVO_PULL_PASSWORD', pull_password)
    if host:
        server_name = host
        if port != 80:
            server_name += ':{}'.format(port)
        app.config['SERVER_NAME'] = server_name
    app.jinja_env.undefined = StrictUndefined
    db.init_app(app)

    for filter_name in filters.__all__:
        app.jinja_env.filters[filter_name] = getattr(filters, filter_name)

    @app.template_global()
    def url_for_lang(lang_code):
        args = dict(request.view_args)
        args['lang_code'] = lang_code
        return url_for(request.endpoint, **args)

    @app.template_global()
    def tr(cs, en):
        if g.lang_code == 'cs':
            return cs
        elif g.lang_code == 'en':
            return en
        raise ValueError(g.lang_code)

    @app.before_first_request
    def setup():
        db_setup(datadir)

    @app.url_value_preprocessor
    def pull_lang_code(endpoint, values):
        if values:
            g.lang_code = values.pop('lang_code', None)

    @app.url_defaults
    def add_language_code(endpoint, values):
        if 'lang_code' in values or not g.lang_code:
            return
        if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
            values['lang_code'] = g.lang_code

    for url, func, options in routes:
        app.route(url, **options)(func)

    return app
Beispiel #13
0
def test_meta_view():
    app = Flask(__name__)
    api = Api(app)
    app.route('/')(api.meta_view)
    with app.test_client() as c:
        resp = c.get("/")
        assert resp.status_code == 200
        assert resp.mimetype == 'text/html'
        resp = c.get("/?json")
        assert resp.status_code == 200
        assert resp.mimetype == 'application/json'
    def app():
        """App, that registers if request teardown was happened."""
        app = Flask(__name__)
        app.route('/spam')(lambda: 'eggs')

        app.teardown_happened = False

        @app.teardown_request
        def teardown(*_, **__):
            app.teardown_happened = True

        return app
Beispiel #15
0
    def test_flask(self):
        from flask import Flask, g # nolint
        from dealer.contrib.flask import Dealer

        app = Flask('test')
        Dealer(app)
        self.assertTrue(app.revision)
        app.route('/')(lambda: g.revision)
        with app.test_request_context():
            client = app.test_client()
            response = client.get('/')
            self.assertTrue(app.revision in response.data)
Beispiel #16
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)
    app.debug = app.config.get('DEBUG', False)

    # Setup semi-permanent cache stored in os temp directory
    try:
        app.cache_file = os.path.join(
            tempfile.gettempdir(), 'spectrometer-cache.p')
        app.cache = pickle.load(open(app.cache_file, "rb"))
    except IOError:
        app.cache = {}

    # Flask profiler is only active when in debug mode
    profiler = Profiler()
    profiler.init_app(app)

    if not app.debug:
        # Setup Logger
        logdir = app.config.get('LOG_DIR', '/var/log/spectrometer')
        logfile = os.path.join(logdir, 'spectrometer.log')

        logging.getLogger().setLevel(logging.NOTSET)
        formatter = logging.Formatter('%(asctime)s (%(levelname)8s) %(name)-40s: %(message)s')
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logging.getLogger().addHandler(console_handler)

        try:
            file_handler = RotatingFileHandler(logfile, maxBytes=20000000, backupCount=20)
            file_handler.setFormatter(formatter)
            logging.getLogger().addHandler(file_handler)
            log.info('File logger activated.')
        except IOError:
            log.warn('Unable to activate File logger. Please ensure that the '
                     'log directory ({0}) is writable by the spectrometer user.'.format(logdir))

    # Prep resource handlers
    app.gerrithandler = GerritHandler(app.config['GERRIT_URL'])
    app.githandlers = {}

    # Stop Flask debug mode from running the scheduler twice
    if not app.debug or os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        run_scheduler(app)

    app.route('/')(views.status)

    app.register_blueprint(gitapi, url_prefix='/git')
    app.register_blueprint(gerritapi, url_prefix='/gerrit')

    return app
Beispiel #17
0
def create_app(config, oidc_overrides=None):
    global oidc

    app = Flask(__name__)
    app.config.update(config)
    if oidc_overrides is None:
        oidc_overrides = {}
    oidc = OpenIDConnect(app, **oidc_overrides)
    app.route('/')(oidc.check(index))
    app.route('/at')(oidc.check(get_at))
    app.route('/rt')(oidc.check(get_rt))
    # Check standalone usage
    rendered = oidc.accept_token(True, ['openid'])(api)
    app.route('/api', methods=['GET', 'POST'])(rendered)

    # Check combination with an external API renderer like Flask-RESTful
    unrendered = oidc.accept_token(True, ['openid'], render_errors=False)(raw_api)
    def externally_rendered_api(*args, **kwds):
        inner_response = unrendered(*args, **kwds)
        if isinstance(inner_response, tuple):
            raw_response, response_code, headers = inner_response
            rendered_response = json.dumps(raw_response), response_code, headers
        else:
            rendered_response = json.dumps(inner_response)
        return rendered_response
    app.route('/external_api', methods=['GET', 'POST'])(externally_rendered_api)
    return app
Beispiel #18
0
class HydroWebServer():
    def __init__(self, crop_id):
        print("Initializing web server")
        self.svr = Flask(__name__)
        self.crop_id = crop_id
        # If HYDRO_SETTINGS environment value points to a config file
        # override the default configuration
        self.svr.config.from_envvar('HYDRO_SETTINGS', silent=True)
        Bootstrap(self.svr)
        self.svr.route('/', methods=['GET'])(web.views.index.index)

    def start(self, debug=False):
        print("Starting web server")
        self.svr.run(host=HOST, port=PORT, debug=debug)
Beispiel #19
0
def test_flask():
    from flask import Flask, g
    from dealer.contrib.flask import Dealer

    app = Flask('test')
    Dealer(app)
    assert app.revision

    app.route('/')(lambda: "%s - %s" % (g.revision, g.tag))
    with app.test_request_context():
        client = app.test_client()
        response = client.get('/')
        assert app.revision in response.data.decode('utf-8')
        assert app.tag in response.data.decode('utf-8')
 def build_app(self):
     """Build app. Put url-map type converters in place, and then setup
     REST API."""
     app = Flask(self.index.name)
     app.url_map.converters['list'] = ListConverter
     app.url_map.converters['float'] = FloatConverter
     
     def finder(*args, **kwargs):
         return self.find_response(*args, **kwargs)
     def sleeper(*args, **kwargs):
         return self.sleep_response(*args, **kwargs)
     
     app.route(self.find_rule)(finder)
     app.route(self.sleep_rule)(sleeper)
     
     return app
Beispiel #21
0
def app():
    _app = Flask(__name__)
    obscure.Obscure(_app, SALT)  # works for test, but use flask.config

    def invoice(customer_id):
        """Show obfuscated customer number.
        Routes for each filter are created like:
            /invoice/b32/<b32:customer_id>
            /invoice/b64/<b64:customer_id>
            /invoice/hex/<hex:customer_id>
            /invoice/tame/<tame:customer_id>

        Arg:
            customer_id: actual customer number

            This number, while obfuscated in the URL, has been converted
            by the in the url_map.converters at this point.

        Return string:
            {obscure method}#{obscured customerID}
        """
        encoder = request.url_rule.endpoint
        template = '{{ encoder }}#{{ customer_id|%s }}' % encoder
        return render_template_string(template, **locals())
    for f in FILTERS:
        url = '/invoice/%s/<%s:customer_id>' % (f, f)
        invoice = _app.route(url, endpoint=f)(invoice)
    return _app
Beispiel #22
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    api.init_app(app)

    app.route('/',)
    api.add_resource(AutocompleteAPI.AutoCompleteLocation, '/film/locations/autocomplete', endpoint = 'filmlocations_auto_complete')
    api.add_resource(FilmsAtLocationsAPI.FilmsAtLocations, '/film/locations/<string:location>', endpoint = 'film_locations')
    api.add_resource(FindNearestFilmsAtLocationAPI.FindNearest7FilmsAtLocation, '/film/7nearme/lat/<float:lat>/<string:lat_sign>/lng/<float:lng>/<string:lng_sign>', endpoint = 'films_near_me')

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

    return app
Beispiel #23
0
class AppConfigTest(object):
    def setUp(self):
        self.app = Flask(import_name=__name__)

    def tearDown(self):
        self.app = None

    def add_route(self, path):

        # Flask checks the name of the function to ensure that iew mappings
        # do not collide. We work around it by generating a new function name
        # for the path
        def function_to_rename():
            return 'STUBBED: %s' % path
        function_to_rename.__name__ = 'func_%s' % path

        self.app.route(path)(function_to_rename)
Beispiel #24
0
 def decorator(f):
     @wraps(f)
     @handle_client_errors
     def wrapped_f(*f_args, **f_kwargs):
         data = f(*f_args, **f_kwargs)
         if isinstance(data, PaginatedResult):
             return jsonify(serialize(data, PaginatedResultSchema))
         return jsonify(data=data)
     return Flask.route(app, url, *args, **kwargs)(wrapped_f)
Beispiel #25
0
 def get_app(cls):
     """
     Contruct a Flask object from the bound methods.
     """
     app = Flask(__name__)
     for func, data, kwdata in cls.bound:
         @functools.wraps(func)
         def wrapper(*args, **kwargs):
             if u'serverid' in kwargs:
                 serverid = int(kwargs[u'serverid'])
                 for server in Server.get_instances():
                     if server.id == serverid:
                         del kwargs[u'serverid']
                         return json.dumps(func(server, *args, **kwargs))
                 return abort(404)
             return json.dumps(func(*args, **kwargs))
         wrapper.__name__ = unicode(id(wrapper))
         print(data[0])
         app.route(*data, **kwdata)(wrapper)
     return app
Beispiel #26
0
class Logicoma(object):

    def __init__(self, config_path='configs/logicoma.json', other_opts={}):
        self.app = Flask('Logicoma')
        self.app.route('/', methods=['post'])(self.hook)
        self.other_opts = other_opts
        self.load_config(config_path)

    def load_config(self, config_path):
        with open(config_path) as fp:
            conf = json.load(fp)
        conf.update(self.other_opts)
        self.token = conf['token']
        self.debug = conf.get('debug', False)
        self.handlers = [handlers.load_from_config(s) for s in conf['handlers']]

    def run(self, *args, **kwargs):
        return self.app.run(*args, **kwargs)

    def dispatch(self, text):
        for h in self.handlers:
            response = h.handle(text)
            if response is not None:
                response_json = json.dumps(response)
                return (response_json, 200, {'Content-Type': 'application/json'})
        return ('', 200, {})

    def hook(self):
        try:
            payload = request.form
            logger.debug("payload: %s", payload)
            if self.debug or payload and payload.get('token') == self.token:
                if 'text' in payload and payload.get('user_id') != 'USLACKBOT':
                    return make_response(self.dispatch(payload.get('text')))
                else:
                    return Response(status=200)
            else:
                return Response(status=400)
        except:
            logger.exception('got exception on handler')
            return Response(status=500)
Beispiel #27
0
def test_metafile(tmpdir):
    metafile = tmpdir.join("meta.json")
    json.dump({"$xxx": "test", "$roles": {}}, metafile.open("w"))
    app = Flask(__name__)
    api = Api(app, metafile=metafile.strpath)

    class Hello:
        """docstring for Hello"""

        def get(self):
            """Get hello"""
    api.add_resource(Hello)
    app.route('/')(api.meta_view)

    with app.test_client() as c:
        resp = c.get("/", headers={'Accept': 'application/json'})
        assert resp.status_code == 200
        assert resp_json(resp)["$xxx"] == "test"
        assert resp_json(resp)["$roles"] == {}
        assert resp_json(resp)["hello"]["$desc"] == "docstring for Hello"
        assert resp_json(resp)["hello"]["get"]["$desc"] == "Get hello"
Beispiel #28
0
class Perfume(object):

    def __init__(self, name, debug=False):
        ''
        self.app = Flask(name)
        self.app.debug = debug
        self._load()

    def _load(self):
        "Updates the app's routes with all methods."
        for name in dir(self):
            method = self.__getattribute__(name)
            try:
                route = method.perfume_route
                args = method.perfume_args
            except AttributeError:
                continue

            self.app.route(route, **args)(method)

    def run(self, *args, **kwds):
        self.app.run(*args, **kwds)
Beispiel #29
0
    def route(self, *args, **kwargs):
        ''' route:
        Wraps the regular Flask.route functionality, takes the methods out of
        the route and adds them to the dictionary of endpoints, used for the
        discovery request.
        '''
        route = args[0]
        for info in self.endpoints.values():
            if info['url'] == route:
                info['methods'] += kwargs['methods']
                break

        return Flask.route(self, *args, **kwargs)
Beispiel #30
0
def create_app(test=False):
    app = Flask(__name__)
    app.config["ADMIN_EMAIL"] = "admin@todos.com"
    app.config["ADMIN_PASSWORD"] = "123456"

    if test:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
        app.config["SQLALCHEMY_ECHO"] = True
    else:
        db_path = os.path.join(app.root_path, "todos.db")
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_path
    db.init_app(app)

    bp_api = Blueprint('api', __name__, static_folder='static')
    api.init_app(app, blueprint=bp_api, docs=__doc__)
    auth.init_api(api, fn_user_role=fn_user_role)

    api.add_resource(Todos)
    api.add_resource(User)
    api.add_resource(Permission, auth=auth)
    api.add_resource(ApiInfo, api=api)

    def make_view(filename):
        return lambda *args, **kwargs: app.send_static_file(filename)
    for url, filename in url_views:
        end = os.path.splitext(filename)[0]
        app.route(url, endpoint=end)(make_view(filename))

    app.before_first_request(before_first_request)
    app.register_blueprint(bp_api, url_prefix='/api')

    gen = Gen(api)
    gen.resjs('static/js/res.js')
    gen.resdocs('static/resdocs.html', resjs='/static/js/res.js',
                bootstrap='/static/css/bootstrap.min.css')
    gen.permission('static/permission.html', resjs='/static/js/res.js',
                   bootstrap='/static/css/bootstrap.min.css',
                   vuejs='/static/js/vue.js')
    return app