Beispiel #1
1
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 #2
1
def create_app(config="config.ProductionDevelopmentConfig"):
    app = Flask(__name__)

    app.config.from_object(config)

    db.init_app(app)

    mixer.init_app(app)

    app.before_request(setup_authomatic(app))
    app.before_request(load_user)

    app.add_url_rule("/", "index", index)

    app.register_blueprint(auth_bp, url_prefix="/auth")
    app.register_blueprint(issues_bp, url_prefix="/issues")
    app.register_blueprint(comments_bp, url_prefix="/comments")
    app.register_blueprint(organizations_bp, url_prefix="/organizations")

    admin = Admin(app)

    # add admin views.
    admin.add_view(AdminView(User, db.session))
    admin.add_view(AdminView(Issue, db.session))
    admin.add_view(AdminView(Comment, db.session))
    admin.add_view(AdminView(Organization, db.session))
    admin.add_view(AdminView(Vote, db.session))

    return app
Beispiel #3
1
def init(config_args):
    app = Flask(__name__)
    slack = flask_slack.Slack(app)
    config = slackbot.load_config(config_args.config)
    if not config:
        slackbot.save_config()
        print """Looks like we can't find config.yaml-
        we've gone ahead and generated a sample one for you in the current directory.
        Please edit it according to the instructions in it and re-run parsely_slackbot!"""
        sys.exit()
    parsely_bot = slackbot.SlackBot(config)
    parsely_alert = alerts.SlackAlert(parsely_bot)
    # run this on a timer so that trending alerts don't happen the moment the bot is kicked off
    alerts_thread = threading.Timer(300.0, parsely_alert.run)
    alerts_thread.daemon = True
    alerts_thread.start()

    @slack.command("parsely", token=config["slack_token"], team_id=config["team_id"], methods=["POST"])
    def parsely(text=None, channel=None, **kwargs):
        parsed_commands = parsely_bot.parse(text)
        if not parsed_commands:
            return slack.response("Sorry, I didn't understand that query! Maybe try /parsely help?")
        if parsed_commands["meta"] == "help":
            return slack.response(parsely_bot.help())
        post_list, header_text = parsely_bot.realtime(parsed_commands)
        if not header_text:
            return slack.response("Sorry, didn't recognize that command!")
        if not post_list:
            return slack.response("Sorry, no posts found with that query!")
        attachments = parsely_bot.build_meta_attachments(post_list, header_text)
        return slack.response(text="", response_type="in_channel", attachments=attachments)

    app.add_url_rule("/", view_func=slack.dispatch)
    app.run("0.0.0.0", config_args.port, debug=False, threaded=True)
Beispiel #4
1
class App(object):
    """Represents the Flask App"""

    def __init__(self):
        self.dir = os.path.dirname(__file__)

        self.app = Flask(__name__, static_folder="../app")
        self.api = Api(self.app, prefix="/api/v1")

        self.app.add_url_rule("/bower_components/<path:path>", "bower_components", self.bower)

        self.api.add_resource(canyonero.Root, "/")
        self.api.add_resource(canyonero.NameSetEndpointIndex, "/nameset")
        self.api.add_resource(canyonero.NameSetEndpointDetail, "/nameset/<string:id>")
        self.api.add_resource(canyonero.NameSetEndpointAbbrev, "/nameset/<string:id>/abbrev")
        self.api.add_resource(canyonero.NameSetEndpointIgnore, "/nameset/<string:id>/ignore")
        self.api.add_resource(canyonero.NameSetEndpointCanon, "/nameset/<string:id>/canon")
        self.api.add_resource(canyonero.ClusterEndpointIndex, "/nameset/<string:id>/cluster")
        self.api.add_resource(canyonero.ClusterEndpointDetail, "/nameset/<string:id>/cluster/<string:key>")

    def bower(self, path):
        fullPath = os.path.join(self.dir, "../bower_components", path)
        return send_file(fullPath)

    def run(self, debug):
        self.app.run(debug=debug)

    def absoluteUrl(self, relative):
        f = "{0}{1}" if relative[0] == "/" else "{0}/{1}"
        return f.format(self.api.prefix, relative)
Beispiel #5
1
def create_app(config=None):
    app = Flask(__name__.split(".")[0])
    app_config = {  # Defaults
        "GALLERY_ROOT": os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "gallery")),
        "REDIS_URL": "redis://localhost:6379/0",
    }

    if config is not None:
        app_config.update({key.upper(): value for key, value in config.items()})
        if "DEBUG" in app_config:
            if app_config["DEBUG"] in ("0", "n", "no", "False", "false"):
                app_config.update({"DEBUG": False})
            else:
                app_config.update({"DEBUG": True})

    app.config.update(app_config)

    app.add_url_rule("/galleries/<path:path>", view_func=send_pic, methods=["GET"])

    babel = Babel(app)
    babel.localeselector(get_locale)
    app.jinja_env.filters["date"] = format_date
    app.jinja_env.filters["datetime"] = format_datetime

    GalleryView.register(app)
    return app
Beispiel #6
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
Beispiel #7
1
 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()
Beispiel #8
1
class clientmain:

    JSON_HEADER = {"Content-Type": "application/json"}

    def __init__(self, server_ip, server_port, local_ip, local_folder_path, local_ctl_port, local_trans_port):

        self.server_ip = server_ip  # 192.168.1.10
        self.server_port = server_port  # 8000
        self.local_ip = local_ip  # 192.168.1.15
        self.local_folder_path = local_folder_path  # /home/shaw/Develop/snlab/simple-tracker/client
        self.local_ctl_port = local_ctl_port  # 8000
        self.local_trans_port = local_trans_port  # 9000
        self.stc = STClientInstance(
            "http://" + self.server_ip + ":" + str(self.server_port),
            self.local_folder_path,
            "http://" + self.local_ip + ":" + str(self.local_trans_port),
        )
        self.swd = SimpleWatchDog(self.local_folder_path, self.stc, self.local_ip)
        self.web_app = Flask(__name__)
        self.web_app.add_url_rule("/transfer", "transfer", self.transfer, methods=["post"])
        self.threads = []

    def success(self):
        return '{"status":"OK"}', 200, clientmain.JSON_HEADER

    def run(self):
        self.stc.register(self.local_ip, str(self.local_ctl_port))
        self.stc.update(self.local_ip)
        t1 = threading.Thread(target=self.start_HTTPServer)
        t2 = threading.Thread(target=self.start_simplewatchdog)
        t3 = threading.Thread(target=self.start_flask_server)
        self.threads.append(t1)
        self.threads.append(t2)
        self.threads.append(t3)
        for t in self.threads:
            t.setDaemon(True)
            t.start()
        try:
            while True:
                pass
        except KeyboardInterrupt:
            self.stc.deregister(self.local_ip)

    def start_HTTPServer(self):
        global ROUTES
        ROUTES.append(("/", self.local_folder_path))
        httpd = HTTPServer(("127.0.0.1", self.local_trans_port), MyHandler)
        httpd.serve_forever()
        print("start HTTPServer")

    def start_simplewatchdog(self):
        self.swd.start()
        print("start simplewatchdog")

    def transfer(self):
        print("I received transfer message")
        return self.success()

    def start_flask_server(self):
        self.web_app.run(host="0.0.0.0", port=self.local_ctl_port)
Beispiel #9
1
    def test_url(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.assertEquals("/3", field.output("hey", Foo()))
    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 #11
0
class WebServer(object):
    """
    Web router for http requests.
    """

    def __init__(self, database):
        self._web_handlers = {}
        for c in get_all_classes(["web_handlers.py"], WebHandler):
            obj = c(database)
            self._web_handlers[obj.url] = obj
        self._web_server = Flask("web_server")
        self._register(database)

    def _register(self, database):
        logger.info("Handlers register start !")
        for handler_name, handler_obj in self._web_handlers.items():
            self._web_server.add_url_rule(
                "/%s/<string:parameters>" % handler_name, view_func=handler_obj.as_view(handler_name, database)
            )
            logger.info("Handler register: '%s'" % handler_name)
        logger.info("Handlers register done !")

    @property
    def web_server(self):
        Compress().init_app(self._web_server)
        return self._web_server
Beispiel #12
0
class Drawbridge(object):
    def __init__(self):

        self.create_app()
        self.add_routes()

        self.app.debug = True
        self.app.config["SERVER_NAME"] = "localhost:3000"
        self.app.static_folder = "drawbridge/static"
        self.app.template_folder = "drawbridge/templates"
        self.run = self.app.run

    def create_app(self):

        self.app = Flask("Drawbridge")

    def add_routes(self):

        self.app.add_url_rule("/", "index", self.index, methods=["GET", "POST"])

    def index(self):
        if request.method == "GET":
            return render_template("index.html")
        else:
            print(action_from_string(unicode_base64(request.form["data"])))
            return ""
Beispiel #13
0
class App(object):
    def __init__(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.slack = Slack(self.app)
        self.app.add_url_rule("/", view_func=self.slack.dispatch)
        self.client = self.app.test_client()
Beispiel #14
0
def main():
    try:
        # init
        #        lModel = RangeManager(int(sys.argv[1]), int(sys.argv[2]))

        monkey.patch_all()
        lApp = Flask(__name__)
        lApp.debug = True
        lApi = Api(lApp)
        #        FetchRange.sModel = lModel
        #        Report.sModel = lModel
        #        Progress.sModel = lModel
        #        Reset.sModel = lModel
        #        PushNamespace.sModel = lModel

        #  routes
        lApp.add_url_rule("/", "start", start)
        #        lApp.add_url_rule('/socket.io/<path:path>', 'socket.io', run_socketio)

        lApi.add_resource(Busses, "/busses")
        lApi.add_resource(IOConfig, "/ioconfig")
        lApi.add_resource(Set, "/set")
        lApi.add_resource(Get, "/get")
        lApi.add_resource(Dump, "/dump")
        lApi.add_resource(Detect, "/detect")

        # go
        #        lApp = SharedDataMiddleware(lApp, {})
        lServer = SocketIOServer(("0.0.0.0", 5000), lApp, resource="socket.io", policy_server=False)
        lServer.serve_forever()
    except IndexError:
        print "Usage: " + sys.argv[0] + " <number of ranges> <timeout per range>"
    except KeyboardInterrupt:
        lServer.stop()
Beispiel #15
0
    def test_url_with_extra(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>/<what>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", extra={"what": "hello"})

        with app.test_request_context("/hey"):
            self.assertEquals("/3/hello", field.output("hey", Foo()))
Beispiel #16
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 #17
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 #18
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)
Beispiel #19
0
class HTTPServer(object):

    FORM_DATA_MIME = "application/x-www-form-urlencoded"
    JSON_DATA_MIME = "application/json"

    def __init__(self, jockey):
        self.jockey = jockey
        self.app = Flask("horse-http-server")
        self.app.add_url_rule("/", "handler", self.handle_request, methods=["GET", "POST"], defaults={"path": ""})
        self.app.add_url_rule("/<path:path>", "handler", self.handle_request, methods=["GET", "POST"])

    def handle_request(self, path):
        logging.info("Inbound request: {0}".format(path))
        if path == "command":
            response = self.jockey.handle_command(request.form)
        else:
            if request.method == "GET":
                response = self.jockey.handle_http_get(path, request.args)
            elif request.method == "POST":
                if request.headers["Content-Type"] == self.FORM_DATA_MIME:
                    response = self.jockey.handle_http_post(path, request.form)
                elif request.headers["Content-Type"] == self.JSON_DATA_MIME:
                    data = json.loads(request.body)
                    response = self.jockey.handle_http_post(path, data)
        logging.info("Outbound response: {0}".format(response))
        if response is None:
            response = ""
        return str(response)

    def start(self):
        def run(*args):
            self.app.run(host="0.0.0.0", port=5000)

        logging.info("Starting HTTP server on new thread.")
        thread.start_new_thread(run, ())
Beispiel #20
0
    def setUp(self):
        app = Flask(__name__)
        app.secret_key = "N4buDSXfaHx2oO8g"
        self.app = app
        auth = Auth(app)

        @login_required
        def needs_login():
            return "needs_login"

        app.add_url_rule("/needs_login/", "needs_login", needs_login)

        @permission_required(resource="post", action="view")
        def post_view():
            return "needs_post_view"

        app.add_url_rule("/post_view/", "post_view", post_view)

        @app.route("/login_view/")
        def login_view():
            return "login_view"

        user = AuthUser(username="user")
        user.role = "testuser"
        testuser_role = Role("testuser", [Permission("post", "view")])
        auth.load_role = lambda _: testuser_role
        self.user = user
Beispiel #21
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 #22
0
class RESTInterface(object):
    def __init__(self, ip_addr, port, conn_obj, output_dir):
        self.conn = conn_obj
        self.ip_addr = ip_addr
        self.port = port
        self.output_dir = output_dir
        self.app = Flask("eyes")

    def status(self):
        resp = json.jsonify(status=str(self.conn))
        resp.status_code = 200
        return resp

    def start_test(self, test_num):
        self.conn.remove_handler()
        test_str = "test-{0}".format(test_num)
        filename = os.path.join(os.path.abspath(self.output_dir), test_str)
        self.conn.add_handler(filename)
        resp = json.jsonify(status="START - SUCCESS")
        resp.status_code = 200
        return resp

    def run_test(self):
        json_data = request.get_json(force=True)
        status = self.conn.run_cmd(json_data["cmd_str"])
        resp = None
        if status is True:
            resp = json.jsonify(status="TEST - SUCCESS")
            resp.status_code = 200
        else:
            resp = json.jsonify(status="TEST - FAILED")
            resp.status_code = 520
        return resp

    def stop_test(self):
        self.conn.remove_handler()
        resp = json.jsonify(status="STOP - SUCCESS")
        resp.status_code = 200
        return resp

    def shutdown(self):
        self.conn.stop()
        resp = json.jsonify(status="SHUTDOWN - SUCCESS")
        resp.status_code = 200
        return resp

    def reconnect(self):
        self.conn.reconnect()
        resp = json.jsonify(status="Reconnect - SUCCESS")
        resp.status_code = 200
        return resp

    def start(self):
        self.app.add_url_rule("/", "index", self.status)
        self.app.add_url_rule("/start_test/<int:test_num>", "start_test", self.start_test, methods=["POST"])
        self.app.add_url_rule("/stop_test", "stop_test", self.stop_test)
        self.app.add_url_rule("/run_test", "run_test", self.run_test, methods=["POST"])
        self.app.add_url_rule("/shutdown", "shutdown", self.shutdown, methods=["POST"])
        self.app.add_url_rule("/reconnect", "reconnect", self.reconnect, methods=["POST"])
        self.app.run(host=self.ip_addr, port=self.port)
Beispiel #23
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 #24
0
    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 #25
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 #26
0
def main():
    try:
        # init
        lModel = RangeManager(int(sys.argv[1]), int(sys.argv[2]))

        monkey.patch_all()
        lApp = Flask(__name__)
        lApp.debug = True
        lApi = Api(lApp)
        FetchRange.sModel = lModel
        Report.sModel = lModel
        Progress.sModel = lModel
        Reset.sModel = lModel
        PushNamespace.sModel = lModel

        # routes
        lApp.add_url_rule("/", "poll", poll)
        lApp.add_url_rule("/socket.io/<path:path>", "socket.io", run_socketio)
        lApi.add_resource(FetchRange, "/fetch")
        lApi.add_resource(Report, "/report")
        lApi.add_resource(Progress, "/progress")
        lApi.add_resource(Reset, "/reset")

        # go
        lApp = SharedDataMiddleware(lApp, {})
        lServer = SocketIOServer(("0.0.0.0", 5000), lApp, resource="socket.io", policy_server=False)
        lServer.serve_forever()
    except IndexError:
        print "Usage: " + sys.argv[0] + " <number of ranges> <timeout per range>"
    except KeyboardInterrupt:
        lServer.stop()
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 #28
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 #29
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 #30
0
class Flasky(object):
    """
    Flasky - Lazy man's Flask Application

    Convert your class into a flask app.

    """

    def __init__(self, rule=None):
        self.app = Flask(__name__)

        if rule:
            self.rule = rule
        else:
            self.rule = {"ignore": ["__init__"], "map": {"index": "/"}}

        for name, func in inspect.getmembers(self, inspect.ismethod):

            if name in self.rule["ignore"]:
                continue
            elif name in self.rule["map"]:
                self.app.add_url_rule(self.rule["map"][name], view_func=func)
                continue

            url_prefix = [""] + name.split("_")
            args = inspect.getargspec(func).args

            for x in xrange(len(args), 0, -1):
                url = "/".join(url_prefix + ["<%s>" % _ for _ in args[1:x]])
                self.app.add_url_rule(url, view_func=func)

                if not func.func_defaults:
                    break
                elif x <= len(args) - len(func.func_defaults):
                    break