Python bottle.route() Examples

The following are 13 code examples of bottle.route(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bottle , or try the search function .
Example #1
Source File: test_ext_bottle.py    From apispec-webframeworks with MIT License 6 votes vote down vote up
def test_path_with_multiple_methods(self, spec):
        @route("/hello", methods=["GET", "POST"])
        def hello():
            return "hi"

        spec.path(
            view=hello,
            operations=dict(
                get={"description": "get a greeting", "responses": {"200": {}}},
                post={"description": "post a greeting", "responses": {"200": {}}},
            ),
        )
        paths = get_paths(spec)
        get_op = paths["/hello"]["get"]
        post_op = paths["/hello"]["post"]
        assert get_op["description"] == "get a greeting"
        assert post_op["description"] == "post a greeting" 
Example #2
Source File: sm_ansible_server.py    From contrail-server-manager with Apache License 2.0 6 votes vote down vote up
def __init__(self, args_str=None):
        try:
            self._smgr_log = ServerMgrlogger()
        except:
            print "Error Creating logger object"

        self._smgr_log.log(self._smgr_log.INFO, "Starting SM Ansible Server")
        if not args_str:
            args_str = sys.argv[1:]
        self._parse_args(args_str)
        self.joinq  = Queue.Queue()
        self.joiner = Joiner(self.joinq)
        self.joiner.start()
        self._smgr_log.log(self._smgr_log.INFO,  'Initializing Bottle App')
        self.app = bottle.app()
        bottle.route('/run_ansible_playbooks', 'POST',
                self.start_ansible_playbooks) 
Example #3
Source File: weblcds.py    From artisan with GNU General Public License v3.0 6 votes vote down vote up
def send_all(msg):
    socks = wsocks[:]
    for ws in socks:
        try:
            with Timeout(time_to_wait, TooLong):
                if ws.closed:
                    try:
                        wsocks.remove(ws)
                    except:
                        pass
                else:
                    ws.send(msg)
        except Exception:
            try:
                wsocks.remove(ws)
            except:
                pass

# route to push new data to the client 
Example #4
Source File: httpserver.py    From openmano with Apache License 2.0 5 votes vote down vote up
def http_delete_vnf_id(tenant_id,vnf_id):
    '''delete a vnf from database, and images and flavors in VIM when appropriate, can use both uuid or name'''
    #check valid tenant_id and deletes the vnf, including images, 
    result, data = nfvo.delete_vnf(mydb,tenant_id,vnf_id)
    if result < 0:
        print "http_delete_vnf_id error %d %s" % (-result, data)
        bottle.abort(-result, data)
    else:
        #print json.dumps(data, indent=4)
        return format_out({"result":"VNF " + data + " deleted"})

#@bottle.route(url_base + '/<tenant_id>/hosts/topology', method='GET')
#@bottle.route(url_base + '/<tenant_id>/physicalview/Madrid-Alcantara', method='GET') 
Example #5
Source File: test_ext_bottle.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_path_from_view(self, spec):
        @route("/hello")
        def hello():
            return "hi"

        spec.path(
            view=hello, operations={"get": {"parameters": [], "responses": {"200": {}}}}
        )
        paths = get_paths(spec)
        assert "/hello" in paths
        assert "get" in paths["/hello"]
        expected = {"parameters": [], "responses": {"200": {}}}
        assert paths["/hello"]["get"] == expected 
Example #6
Source File: test_ext_bottle.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_integration_with_docstring_introspection(self, spec):
        @route("/hello")
        def hello():
            """A greeting endpoint.

            ---
            x-extension: value
            get:
                description: get a greeting
                responses:
                    200:
                        description: a pet to be returned
                        schema:
                            $ref: #/definitions/Pet

            post:
                description: post a greeting
                responses:
                    200:
                        description: some data

            foo:
                description: not a valid operation
                responses:
                    200:
                        description:
                            more junk
            """
            return "hi"

        spec.path(view=hello)
        paths = get_paths(spec)
        get_op = paths["/hello"]["get"]
        post_op = paths["/hello"]["post"]
        extension = paths["/hello"]["x-extension"]
        assert get_op["description"] == "get a greeting"
        assert post_op["description"] == "post a greeting"
        assert "foo" not in paths["/hello"]
        assert extension == "value" 
Example #7
Source File: test_ext_bottle.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_path_is_translated_to_openapi_template(self, spec):
        @route("/pet/<pet_id>")
        def get_pet(pet_id):
            return f"representation of pet {pet_id}"

        spec.path(view=get_pet)
        assert "/pet/{pet_id}" in get_paths(spec) 
Example #8
Source File: test_ext_bottle.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_path_with_params(self, spec, path):
        @route(path, methods=["GET"])
        def handler():
            pass

        spec.path(view=handler)
        assert "/pet/{pet_id}/{shop_id}" in get_paths(spec) 
Example #9
Source File: weblcds.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def send():
    send_all(jdumps(request.json))

# route that establishes the websocket between the Artisan app and the clients 
Example #10
Source File: weblcds.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def status():
    return "1"
    
# route to serve the static page 
Example #11
Source File: proxy.py    From github-pages-basic-auth-proxy with MIT License 4 votes vote down vote up
def run_proxy(args):

    #
    # ERROR HANDLERS
    #
    @error(401)
    def error404(error):
        return template(error_tpl, headline='Error '+error.status, error=error.body)

    @error(500)
    def error500(error):
        return template(error_tpl, headline='Error '+error.status, error=error.body)

    #
    # SPECIAL ENDPOINTS
    #
    @route('/health')
    def hello():
        return template(healthcheck_tpl, headline='Healthcheck')

    @route('/install-success')
    def hello():
        remote_page_call_status_code = proxy_trough_helper('https://{0}.github.io/{1}/{2}/{3}'.format(args.owner, args.repository, args.obfuscator, '/')).status_code
        return template(install_success_tpl, headline='Installation Success', remote_page_call_status_code=remote_page_call_status_code)

    #
    # make args available in auth callback
    #
    global owner, auth_type
    owner = args.owner
    auth_type = args.authType

    @route('/<url:re:.+>')
    @auth_basic(check_pass)
    def proxy_trough(url):
        return proxy_trough_helper('https://{0}.github.io/{1}/{2}/{3}'.format(args.owner, args.repository, args.obfuscator, normalize_proxy_url(url)))

    @route('/')
    @auth_basic(check_pass)
    def proxy_trough_root_page():
        return proxy_trough_helper('https://{0}.github.io/{1}/{2}/{3}'.format(args.owner, args.repository, args.obfuscator, '/index.html'))

    #
    # RUN BY ENVIRONMENT
    #
    if args.environment == 'wsgi':
        run(host='localhost', port=args.port, debug=True)
    if args.environment == 'heroku':
        run(host="0.0.0.0", port=int(args.port))
    else:
        run(server='cgi') 
Example #12
Source File: __init__.py    From Eel with MIT License 4 votes vote down vote up
def start(*start_urls, **kwargs):
    _start_args.update(kwargs)

    if 'options' in kwargs:
        if _start_args['suppress_error']:
            _start_args.update(kwargs['options'])
        else:
            raise RuntimeError(api_error_message)

    if _start_args['port'] == 0:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('localhost', 0))
        _start_args['port'] = sock.getsockname()[1]
        sock.close()

    if _start_args['jinja_templates'] != None:
        from jinja2 import Environment, FileSystemLoader, select_autoescape
        templates_path = os.path.join(root_path, _start_args['jinja_templates'])
        _start_args['jinja_env'] = Environment(loader=FileSystemLoader(templates_path),
                                 autoescape=select_autoescape(['html', 'xml']))


    # Launch the browser to the starting URLs
    show(*start_urls)

    def run_lambda():
        if _start_args['all_interfaces'] == True:
            HOST = '0.0.0.0'
        else:
            HOST = _start_args['host']

        app = _start_args['app']  # type: btl.Bottle
        for route_path, route_params in BOTTLE_ROUTES.items():
            route_func, route_kwargs = route_params
            btl.route(path=route_path, callback=route_func, **route_kwargs)

        return btl.run(
            host=HOST,
            port=_start_args['port'],
            server=wbs.GeventWebSocketServer,
            quiet=True,
            app=app)

    # Start the webserver
    if _start_args['block']:
        run_lambda()
    else:
        spawn(run_lambda) 
Example #13
Source File: __init__.py    From NSC_BUILDER with MIT License 4 votes vote down vote up
def start(*start_urls, **kwargs):
	_start_args.update(kwargs)
	if 'options' in kwargs:
		if _start_args['suppress_error']:
			_start_args.update(kwargs['options'])
		else:
			raise RuntimeError(api_error_message)

	if _start_args['port'] == 0:
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.bind(('localhost', 0))
		_start_args['port'] = sock.getsockname()[1]
		sock.close()

	if _start_args['jinja_templates'] != None:
		from jinja2 import Environment, FileSystemLoader, select_autoescape
		templates_path = os.path.join(root_path, _start_args['jinja_templates'])
		_start_args['jinja_env'] = Environment(loader=FileSystemLoader(templates_path),
								 autoescape=select_autoescape(['html', 'xml']))


	# Launch the browser to the starting URLs
	show(*start_urls)

	def run_lambda():
		if _start_args['all_interfaces'] == True:
			HOST = '0.0.0.0'
		else:
			HOST = _start_args['host']

		app = _start_args['app']  # type: btl.Bottle
		for route_path, route_params in BOTTLE_ROUTES.items():
			route_func, route_kwargs = route_params
			btl.route(path=route_path, callback=route_func, **route_kwargs)
		if _start_args['ssl_cert']==False or _start_args['ssl_key']==False:	
			return btl.run(
				host=HOST,
				port=_start_args['port'],
				server=wbs.GeventWebSocketServer,
				quiet=True,
				app=app
				)
		else:
			ssldict = {'keyfile': _start_args['ssl_key'], 'certfile': _start_args['ssl_cert']}
			return btl.run(
				host=HOST,
				port=_start_args['port'],
				server=wbs.GeventWebSocketServer,
				quiet=True,
				app=app, 
				**ssldict)

	# Start the webserver
	if _start_args['block']:
		run_lambda()
	else:
		spawn(run_lambda)