Beispiel #1
1
def create_app(config=None):
    """Create an instance of the tentd flask application"""
    app = Flask("tentd")
    app.add_url_rule("/", "home", description)
    app.request_class = Request

    # Load the default configuration values
    import tentd.defaults as defaults

    app.config.from_object(defaults)

    # Load the user configuration values
    if isinstance(config, basestring):
        config = make_config(config)

    if not isinstance(config, dict):
        raise TypeError("Config argument must be a dict or string.")

    if config is not None:
        app.config.update(config)

    # Initialise the db for this app
    db.init_app(app)

    # Register the entity blueprints
    for blueprint in (entity, followers, posts):
        app.register_blueprint(blueprint, url_prefix=blueprint.prefix(app))

    return app
    def test_url_superclass_kwargs(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url(absolute=True, attribute='hey')

        with app.test_request_context("/hey"):
            self.assertEquals("http://localhost/3", field.output("hey", Foo()))
Beispiel #3
0
    def test_url_absolute(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", absolute=True)

        with app.test_request_context("/"):
            self.assertEquals("http://localhost/3", field.output("hey", Foo()))
Beispiel #4
0
class MethodViewLoginTestCase(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)
        self.login_manager._login_disabled = False

        class SecretEndpoint(MethodView):
            decorators = [
                login_required,
                fresh_login_required,
            ]

            def options(self):
                return u''

            def get(self):
                return u''

        self.app.add_url_rule('/secret',
                              view_func=SecretEndpoint.as_view('secret'))

    def test_options_call_exempt(self):
        with self.app.test_client() as c:
            result = c.open('/secret', method='OPTIONS')
            self.assertEqual(result.status_code, 200)
def test_instance_methods():
    class HelloWorldService:
        def get_value(self):
            return "test message 1"

    class HelloWorld:
        def from_injected_service(self, service: HelloWorldService):
            return service.get_value()

        def static_value(self):
            return "test message 2"

    app = Flask(__name__)
    hello_world = HelloWorld()
    app.add_url_rule('/from_injected_service', 'from_injected_service', hello_world.from_injected_service)
    app.add_url_rule('/static_value', 'static_value', hello_world.static_value)

    FlaskInjector(app=app)

    client = app.test_client()
    response = client.get('/from_injected_service')
    eq_(response.data.decode('utf-8'), "test message 1")

    response = client.get('/static_value')
    eq_(response.data.decode('utf-8'), "test message 2")
    def test_url_without_endpoint_absolute_scheme(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url(absolute=True, scheme='https')

        with app.test_request_context("/hey", base_url="http://localhost"):
            self.assertEquals("https://localhost/3", field.output("hey", Foo()))
Beispiel #7
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route('/')
    def index():
        return ('Main index ' +
                url_for('product', product_id='5', revision='b12ef20'))

    @app.route('/page/<name>/')
    def page(name):
        url_for('product', product_id='3')  # Pretend we’re adding a link
        url_for('product', product_id='4')  # Another link
        return u'Hello\xa0World! ' + name

    @app.route('/where_am_i/')
    def where_am_i():
        return (url_for('where_am_i') + ' ' +
                url_for('where_am_i', _external=True))

    @app.route('/robots.txt')
    def robots_txt():
        content = 'User-agent: *\nDisallow: /'
        return app.response_class(content, mimetype='text/plain')

    for asset in ("favicon.ico",):
        url = "/" + asset
        name = asset.replace(".", "_")
        _partial = partial(app.send_static_file, filename=asset)
        app.add_url_rule(url, name, _partial)

    @app.route('/product_<int:product_id>/')
    def product_route(product_id):
        return 'Product num %i' % product_id

    @app.route('/add/', methods=['POST'])
    def add_something(product_id):
        return 'This view should be ignored as it does not accept GET.'

    @freezer.register_generator
    def product_generator():
        # endpoint, values
        yield 'product', {'product_id': 0}
        yield 'page', {'name': 'foo'}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {'product_id': 1}
        # single string: url
        yield '/product_2/'

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
Beispiel #8
0
def get_flask_application(core):
    application = Flask(__name__)
    application.debug = True
    for app in core.apps:
        for url, view in app.get_urls():
            application.add_url_rule(url, view.__class__.__name__, view(core))
    return application
Beispiel #9
0
def create_app():
    app = Flask(__name__)
    api = Api(app)
    app.config.from_object('config.default')
    app.config.from_envvar('APP_SETTINGS', silent=False)
    app.add_url_rule('/api/login', 'login', _get_token)
    from models.base import db
    db.init_app(app)
    from controllers.index import Index
    from controllers.user import UsersList, UserSingle
    from controllers.tasks import TaskSingle, Tasks, AssignTask
    from controllers.comments import Comments
    from controllers.reports import UserComments, TaskStats
    app.before_request(db_connect.before_request)
    app.after_request(db_connect.after_request)
    app.add_url_rule('/api/tasks/<int:task_id>/comments',
                     view_func=Comments.as_view(COMMENTS))
    api.add_resource(Index, '/api/index')
    api.add_resource(UsersList, '/api/users')
    api.add_resource(UserSingle, '/api/users/<int:user_id>')
    api.add_resource(Tasks, '/api/tasks')
    api.add_resource(TaskSingle, '/api/tasks/<int:task_id>')
    api.add_resource(AssignTask, '/api/assign_task')
    api.add_resource(UserComments, '/api/reports/user_comments')
    api.add_resource(TaskStats, '/api/reports/task_stats')
    return app
def create_app(config={}):
    app = Flask("chassis")
    app.config.from_envvar("FLASK_CONFIG")
    app.config.update(config)

    #External
    sentry.init_app(app)
    api.init_app(app)
    cache.init_app(app)

    #Internal
    db.init_app(app)

    #API Endpoints
    api.add_resource(CatAPI, "/cats/<int:cat_id>")
    api.add_resource(TodoListAPI, "/todos")

    app.add_url_rule("/", view_func=show_todos)

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

    #Debug tools
    if app.debug:
        DebugToolbarExtension(app)
        if app.config.get("PROFILE", False):
            app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
                                              restrictions=[30],
                                              sort_by=("time", "cumulative"))

    return app
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite')
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)
    
    # ensure the isntance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass
    
    @app.route('/hello')
    def hello():
        return 'Hello, World!'
    
    from . import db
    db.init_app(app)

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

    from . import blog
    app.register_blueprint(blog.bp)
    app.add_url_rule('/', endpoint='index')

    return app
Beispiel #12
0
def startAPIs(plugin_manager, model_controller, mapper_manager, hostname=None, port=None):
    global _rest_controllers
    global _http_server
    _rest_controllers = [PluginControllerAPI(plugin_manager, mapper_manager), ModelControllerAPI(model_controller)]

    #TODO: some way to get defaults.. from config?
    if str(hostname) == "None":
        hostname = "localhost"
    if str(port) == "None":
        port = 9977

    if CONF.getApiRestfulConInfo() is None:
        CONF.setApiRestfulConInfo(hostname, port)

    app = Flask('APISController')

    _http_server = HTTPServer(WSGIContainer(app))
    _http_server.listen(port,address=hostname) 

    routes = [r for c in _rest_controllers for r in c.getRoutes()]

    for route in routes: 
        app.add_url_rule(route.path, view_func=route.view_func, methods=route.methods) 

    logging.getLogger("tornado.access").addHandler(logger.getLogger(app))
    logging.getLogger("tornado.access").propagate = False
    threading.Thread(target=startServer).start()
Beispiel #13
0
class WebServer (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.ioLoop = IOLoop.instance()
        self.app = Flask(__name__)
        self.app.add_url_rule(rule='/icnaas/api/v1.0/fmc_manager', methods=['POST'], view_func=self.groupMigration)

    #@self.app.route('/icnaas/api/v1.0/fmc_manager', methods=['POST'])
    def groupMigration(self):

        if not request.json or not 'mobility_prediction' in request.json:
            abort(400)

        print "Received Migration from MP_MIDDLEWARE"
        #print json.loads(request.data)

        mig = Migration()
        code = mig.processMigrationInfo(request.json)

        return jsonify({'result': code}), code
        #return jsonify({'result': 200}), 200

    def stop(self):
        self.ioLoop.stop()

    def run(self):
        http_server = HTTPServer(WSGIContainer(self.app))
        http_server.listen(5000)
        self.ioLoop.start()
Beispiel #14
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route("/")
    def index():
        return "Main index " + url_for("product", product_id="5", revision="b12ef20")

    @app.route("/page/<name>/")
    def page(name):
        url_for("product", product_id="3")  # Pretend we’re adding a link
        url_for("product", product_id="4")  # Another link
        return u"Hello\xa0World! " + name

    @app.route("/where_am_i/")
    def where_am_i():
        return url_for("where_am_i") + " " + url_for("where_am_i", _external=True)

    @app.route("/robots.txt")
    def robots_txt():
        content = "User-agent: *\nDisallow: /"
        return app.response_class(content, mimetype="text/plain")

    for asset in ("favicon.ico",):
        url = "/" + asset
        name = asset.replace(".", "_")
        app.add_url_rule(url, name, partial(app.send_static_file, filename=asset))

    @app.route("/product_<int:product_id>/")
    def product(product_id):
        return "Product num %i" % product_id

    @freezer.register_generator
    def product():
        # endpoint, values
        yield "product", {"product_id": 0}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {"product_id": 1}
        # single string: url
        yield "/product_2/"

        yield "page", {"name": u"I løvë Unicode"}

    @app.errorhandler(404)
    def not_found(e):
        return "Page not found", 404

    freezer.error_handler_spec[None] = {404: "/404.html"}

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
Beispiel #15
0
def make_oauth_wsgi(oauth, next_app, config=None):
    app = Flask(__name__, static_folder=None)
    app.config['PROPAGATE_EXCEPTIONS'] = True

    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('OAUTH_SETTINGS')

    app.next_app = next_app
    oauth.init_app(app)
    app.add_url_rule('/login', endpoint=None, view_func=login)
    app.add_url_rule('/logout', endpoint=None, view_func=logout)
    app.add_url_rule('/login/oauth_callback', endpoint=None, view_func=authorized)
    app.add_url_rule(
        '/',
        endpoint=None, view_func=default_handler,
        methods=['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
    )
    app.add_url_rule(
        '/<path:any>',
        endpoint=None, view_func=default_handler,
        methods=['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],

    )

    auth = get_auth_provider(oauth)
    if not auth._tokengetter:
        auth.tokengetter(get_oauth_token)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app
    def test_url_parameters(self):
        app = Flask(__name__)
        app.add_url_rule("/<foo>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", attributes={'foo': 'hey'})

        with app.test_request_context("/"):
            self.assertEquals("/3", field.output("hey", Foo()))
Beispiel #17
0
def create_app():
    app = Flask(
        __name__.split('.')[0],
        template_folder='../templates',
        static_url_path=None,
        static_folder=None
    )

    env = Development
    if os.environ.get('APPLICATION_ENV', '') == 'Production':
        env = Production

    app.config.from_object(env)

    # Load config items into jinja settings
    for key, val in app.config.items():
        if key.startswith('JINJA'):
            setattr(app.jinja_env, key[6:].lower(), val)

    register_controllers(app)
    register_errorhandlers(app)
    register_extensions(app)

    app.static_folder = '../public/'
    app.add_url_rule(app.config['STATIC_URL_PATH'] + '/<path:filename>',
                     endpoint='static',
                     view_func=app.send_static_file
                     )

    signal.signal(signal.SIGUSR1, sig_handler)
    signal.signal(signal.SIGUSR2, sig_handler)

    return app
Beispiel #18
0
 def setUp(self):
     app = Flask(__name__)
     app.debug = True
     toybox = ToyBox(app)
     app.add_url_rule("/test", view_func=DummyModelView.as_view("test"))
     app.add_url_rule("/test-base", view_func=DummyBaseModelView.as_view("test_base"))
     self.app = app.test_client()
    def create_app(self):
        
        class DefaultView(MethodView):
            '''Default route docstring'''
            def put(self):
                return "put on default route"
            def post(self):
                return "post on default route"
        
        class ScopedView(MethodView):
            '''Scoped route docstring'''
            scopes = ['default']
            decorators = [advertise('scopes')]
            def get(self):
                return "scoped route"

        app = Flask(__name__,static_folder=None)
        app.add_url_rule('/default',view_func=DefaultView.as_view('default'))
        app.add_url_rule('/scoped',view_func=ScopedView.as_view('scoped'))
        discoverer = Discoverer(app)

        self.expected_resources = {
            '/scoped': {
                'scopes':['default'],
                'description': 'Scoped route docstring',
                'methods': ['HEAD','OPTIONS','GET'],
            },
            '/default': {
                'description': 'Default route docstring',
                'methods': ['PUT','POST','OPTIONS'],
            },
        }
        return app
Beispiel #20
0
    def __init__(self, default_format, directory, *default_configs):
        app = Flask("configurator")
        view = ConfigView.as_view("config", default_format,
                                  directory, *default_configs)
        app.add_url_rule("/", view_func=view)

        self.app = app
    def test_url_without_endpoint(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url()

        with app.test_request_context("/hey"):
            self.assertEquals("/3", field.output("hey", Foo()))
Beispiel #22
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config = True)

    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'grub.sqlite')
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Db
    from . import db
    db.init_app(app)

    # Orders
    from . import orders
    app.register_blueprint(orders.bp)
    app.add_url_rule('/', endpoint='index')

    # Orders
    from . import users
    app.register_blueprint(users.bp)

    return app
class PointOfInterestSearchEndpointTest(unittest.TestCase):

    def setUp(self):
        self._poi_service = Mock()
        self._poi_service.name_search = Mock(return_value=[])

        self._app = Flask(__name__)
        self._endpoint = PointOfInterestSearchEndpoint('test', self._poi_service)
        self._app.add_url_rule('/search', 'test.search', self._endpoint.get)
        self._app.add_url_rule('/<slug>', 'test.poi', self._endpoint.get)

    def test_making_search_passes_it_to_service(self):
        self._poi_service.search_name.return_value = []
        search_terms = "test search"
        self._make_search_request(search_terms)
        self._poi_service.search_name.assert_called_once_with(search_terms)

    def test_return_value_from_service_is_serialised_to_json(self):
        self._poi_service.search_name.return_value = [PointOfInterest(slug='test:test')]
        response = self._make_search_request("test")
        self.assertEquals('test:test', response['results'][0]['poi']['slug'])

    def _make_search_request(self, search_terms):
        with self._app.test_request_context(
            '/search?q={q}'.format(q=quote_plus(search_terms)), headers=[('Accept', 'application/json')]
        ):
            response = self._endpoint.get()
        return json.loads(response.data)
Beispiel #24
0
def startAPIs(plugin_controller, model_controller, hostname, port):
    global _rest_controllers
    global _http_server
    _rest_controllers = [PluginControllerAPI(plugin_controller), ModelControllerAPI(model_controller)]

    app = Flask('APISController')

    _http_server = HTTPServer(WSGIContainer(app))
    while True:
        try:
            _http_server.listen(port, address=hostname)
            logger.getLogger().info(
                    "REST API server configured on %s" % str(
                        CONF.getApiRestfulConInfo()))
            break
        except socket.error as exception:
            if exception.errno == 98:
                # Port already in use
                # Let's try the next one
                port += 1
                if port > 65535:
                    raise Exception("No ports available!")
                CONF.setApiRestfulConInfoPort(port)
                CONF.saveConfig()
            else:
                raise exception

    routes = [r for c in _rest_controllers for r in c.getRoutes()]

    for route in routes:
        app.add_url_rule(route.path, view_func=route.view_func, methods=route.methods)

    logging.getLogger("tornado.access").addHandler(logger.getLogger(app))
    logging.getLogger("tornado.access").propagate = False
    threading.Thread(target=startServer).start()
Beispiel #25
0
def start(application):
    """Start the web frontend"""

    # Make sure our views can access the main application
    global app
    app = application

    static_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        '../static/'
    )

    config = app.get_config()

    frontend = Flask(__name__, static_folder=static_path)

    # Make sure we crash if there's some bug in the frontend code, this is so
    # we'll find the bugs
    frontend.config['PROPAGATE_EXCEPTIONS'] = True

    frontend.add_url_rule('/', view_func=MainView.as_view('index'))
    frontend.add_url_rule('/data.json', view_func=DataView.as_view('data'))

    # Set up the route for static files
    @frontend.route('/static/<path:filename>')
    def send_static(filename):
        return send_from_directory(static_path, filename)

    frontend.run(host='0.0.0.0', port=config.http_port)

    return frontend
Beispiel #26
0
def create_backend_app(service):
    from werkzeug.routing import Map

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

    # 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

        if endpoint in backend_app.view_functions:
            # HACK: Sometimes we map the same view to multiple url_paths. Flask
            # requries us to have different names.
            endpoint += "2"

        backend_app.add_url_rule(
            url_path,
            endpoint=endpoint,
            methods=HTTP_METHODS,
            view_func=convert_flask_to_httpretty_response(handler),
            strict_slashes=False,
        )

    backend_app.test_client_class = AWSTestHelper
    return backend_app
Beispiel #27
0
    def test_url_invalid_object(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar")

        with app.test_request_context("/"):
            self.assertRaises(MarshallingException, lambda: field.output("hey", None))
Beispiel #28
0
class FyPress():
    def __init__(self, config, manager=False):
        from flask.ext.babel import Babel
        from utils.mysql import FlaskFyMySQL

        self.prepared = False
        self.config = config
        self.app = Flask(
            __name__,
            template_folder=self.config.TEMPLATE_FOLDER,
            static_folder=self.config.STATIC_FOLDER
        )
        self.app.config.from_object(config)
        self.app.wsgi_app = ProxyFix(self.app.wsgi_app)
        self.babel = Babel(self.app)
        self.db    = FlaskFyMySQL(self.app)

        if not manager:
            self.prepare()

    def run(self, host='0.0.0.0', port=5000):
        if self.prepared == False:
            self.prepare()
        self.app.run(host=host, port=port, debug=self.config.DEBUG)

    def prepare(self):
        local.fp = self
        self.prepared = True

        @self.app.before_request
        def before_request():
            g.start = time.time()
            
        if self.config.DEBUG:
            @self.app.after_request
            def after_request(response):
                diff = time.time() - g.start
                if (response.response):
                    response.headers["Execution-Time"] = str(diff)
                return response

        self.app.add_url_rule(self.app.config['UPLOAD_DIRECTORY_URL']+'<filename>', 'FyPress.uploaded_file', build_only=True)
        self.app.wsgi_app = SharedDataMiddleware(self.app.wsgi_app, {self.app.config['UPLOAD_DIRECTORY_URL']: self.app.config['UPLOAD_DIRECTORY']})

        self.blueprint()

    def blueprint(self):
        ### Blueprints ###
        from user import user_blueprint
        from admin import admin_blueprint
        from public import public_blueprint

        ### Load Blueprints ###
        self.app.register_blueprint(user_blueprint)
        self.app.register_blueprint(admin_blueprint)
        self.app.register_blueprint(public_blueprint)

    @staticmethod
    def uploaded_file(filename):
        return send_from_directory(self.app.config['UPLOAD_DIRECTORY'], filename)
Beispiel #29
0
	def create_app(self):
		app = Flask(__name__)
		app.config.from_object(config['unit_test'])
		app.add_url_rule('/test', view_func=test_route)
		app.add_url_rule('/', view_func=index)
		#print "app.view_functions: {}".format(app.view_functions)
		return app
Beispiel #30
0
class app:
    """
    """

    controller_list = {}

    def __init__(self, name):
        self.app = Flask(name)
        self.app.debug = True
        self.app.secret_key = "this is a key"
        # app.run(host='0.0.0.0')

    def run(self, port):
        for k, v in self.controller_list.iteritems():
            print "Start Controller: %s" % (k)

        self.app.run(host="0.0.0.0", port=port)

    def add_controller(self, controller):
        self.controller_list[controller.name] = controller
        for k, v in controller.function_list.iteritems():
            route_path = "/" + controller.name + k
            if v.type == 1:
                route_path = "/" + controller.name + k + "/<path:url_var>"
            print "Reg function: %s" % (route_path)

            self.app.add_url_rule(route_path, None, v.func, **v.options)