Python bottle.request() Examples

The following are 30 code examples of bottle.request(). 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: web-power.py    From pi-power with GNU General Public License v3.0 6 votes vote down vote up
def switchoff():
    socket = int(request.query.socket)
    # If single socket requested
    if (socket > 0 and socket <= 4) :
        #print 'Switching off {}'.format(socket)
        sockets[socket].off()
        return 'Requested switch off {}'.format(socket)
    # If all sockets requested
    elif (socket == 0) :
        for i in range (1, 5):
            sockets[i].off()
        return 'Requested switch off ALL'
    else:
        return 'Invalid request'
        

# Serve up the default index.html page 
Example #2
Source File: photobackup.py    From server-bottle with GNU General Public License v2.0 6 votes vote down vote up
def test():
    """ Tests the server capabilities to handle POST requests. """
    answer = validate_password(request, True)
    if answer:
        return answer

    if not os.path.exists(config['MediaRoot']):
        return end(500, "'MediaRoot' directory does not exist!")

    testfile = os.path.join(config['MediaRoot'], '.test_file_to_write')
    try:
        with open(testfile, 'w') as tf:
            tf.write('')
        log.info("Test succeeded \o/")
        return {'uploaded_files': get_files() }
    except EnvironmentError:
        return end(500, "Can't write to 'MediaRoot' directory!")
    finally:
        os.remove(testfile)


# variables 
Example #3
Source File: photobackup.py    From server-bottle with GNU General Public License v2.0 6 votes vote down vote up
def save_image():
    """ Saves the given image to the parameterized directory. """
    answer = validate_password(request)
    if answer:
        return answer

    upfile = request.files.get('upfile')
    if not upfile:
        return end(401, "no file in the request!")

    filesize = -1
    try:
        filesize = int(request.forms.get('filesize'))
        return save_file(upfile, filesize)
    except TypeError:
        return end(400, "Missing file size in the request!") 
Example #4
Source File: photobackup.py    From server-bottle with GNU General Public License v2.0 6 votes vote down vote up
def validate_password(request, isTest=False):
    """ Validates the password given in the request
        against the stored Bcrypted one. """
    password = None
    try:
        password = request.forms.get('password').encode('utf-8')
    except AttributeError:
        return end(403, "No password in request")

    if 'PasswordBcrypt' in config:
        passcrypt = config['PasswordBcrypt'].encode('utf-8')
        if bcrypt.hashpw(password, passcrypt) != passcrypt:
            return end(403, "wrong password!")
    elif 'Password' in config and config['Password'] != password:
        return end(403, "wrong password!")
    elif isTest:
        return end(401, "There's no password in server configuration!") 
Example #5
Source File: simpleRefundBalance.py    From PaperCutExamples with MIT License 6 votes vote down vote up
def topUp(user):
    if request.GET.get('cancel','').strip():
        return "Refund cancelled by {}".format(user)

    refundAmount = float(request.GET.get('amount','').strip())

    userCredit = proxy.api.getUserAccountBalance(auth, user)

    if userCredit != refundAmount:
        return "Error: User Credit Balance and Refund Requested do not match for user: {}".format(user)

    proxy.api.adjustUserAccountBalance(auth, user, -1 * refundAmount, "Money refunded by the Simple Refund Page")

    return "<p>Updated balance is now {}</p><p>Please close this tab/window and return to PaperCut</p><p>We would email you at {}, but email it not currently configured</p>".format(
            "{0:.2f}".format(proxy.api.getUserAccountBalance(auth, user)),proxy.api.getUserProperty(auth, user, "email"))

    # now transfer the value to the external student system 
Example #6
Source File: api.py    From dwarf with Apache License 2.0 6 votes vote down vote up
def _route_flavors_id(flavor_id):
    """
    Route:  /compute/v2.0/flavors/<flavor_id>
    Method: GET, DELETE
    """
    utils.show_request(bottle.request)

    # nova flavor-delete <flavor_id>
    if bottle.request.method == 'DELETE':
        FLAVORS.delete(flavor_id)
        return

    # nova flavor-list
    if flavor_id == 'detail':
        return api_response.list_flavors(FLAVORS.list(), details=True)

    # nova flavor-show <flavor_id>
    return api_response.show_flavor(FLAVORS.show(flavor_id)) 
Example #7
Source File: api.py    From dwarf with Apache License 2.0 6 votes vote down vote up
def _route_flavors():
    """
    Route:  /compute/v2.0/flavors
    Method: GET, POST
    """
    utils.show_request(bottle.request)

    # nova flavor-create
    if bottle.request.method == 'POST':
        body = json.load(bottle.request.body)
        return api_response.create_flavor(FLAVORS.create(body['flavor']))

    # nova flavor-list (no details)
    return api_response.list_flavors(FLAVORS.list(), details=False)


# -----------------------------------------------------------------------------
# Bottle Keypair API routes 
Example #8
Source File: api.py    From dwarf with Apache License 2.0 6 votes vote down vote up
def _route_servers_id(server_id):
    """
    Route:  /compute/v2.0/servers/<server_id>
    Method: GET, DELETE
    """
    utils.show_request(bottle.request)

    # nova delete <server_id>
    if bottle.request.method == 'DELETE':
        SERVERS.delete(server_id)
        return

    # nova list
    if server_id == 'detail':
        return api_response.list_servers(SERVERS.list(), details=True)

    # nova show <server_id>
    return api_response.show_server(SERVERS.show(server_id)) 
Example #9
Source File: app.py    From glim with MIT License 6 votes vote down vote up
def register_routes(self):
        """
        Function creates instances of controllers, adds into bottle routes
        """
        routes = self.flatten_urls(self.urls)
        self.controllers = {}
        controller_names = set()

        for route in routes:
            cname = route['endpoint'].split('.')[0]
            controller_names.add(cname)

        for cname in controller_names:
            attr = getattr(self.mcontrollers, cname)
            instance = attr(request, response)
            self.controllers[cname] = instance

        for route in routes:
            cname, aname = route['endpoint'].split('.')
            action = getattr(self.controllers[cname], aname)
            self.wsgi.route(route['url'], route['methods'], action) 
Example #10
Source File: conftest.py    From bottle-jwt with GNU General Public License v3.0 6 votes vote down vote up
def bottle_app(backend):
    """pytest fixture for `bottle.Bottle` instance.
    """

    app = bottle.Bottle()

    jwt_plugin = JWTProviderPlugin(
        keyword='jwt',
        auth_endpoint='/auth',
        backend=backend,
        fields=('username', 'password'),
        secret='my_secret',
        ttl=3
    )

    app.install(jwt_plugin)

    @app.get('/')
    @jwt_auth_required
    def private_resource():
        return {'user': bottle.request.get_user()}

    return webtest.TestApp(app) 
Example #11
Source File: conftest.py    From bottle-jwt with GNU General Public License v3.0 6 votes vote down vote up
def request():
    """Fixture for `bottle.request` instance.
    """

    class MockRequest(object):

        content_type = 'x-www-form-urlencoded'

        def __init__(self, data):
            self.forms = data
            self.query = data
            self.__get_header = {}

        def get_header(self, header, default=None):
            return self.__get_header.get(header) or default

        def set_header(self, header, value):
            self.__get_header[header] = value

    return MockRequest 
Example #12
Source File: api.py    From dwarf with Apache License 2.0 6 votes vote down vote up
def _route_images():
    """
    Route:  /image/v2/images
    Method: GET, POST
    """
    utils.show_request(bottle.request)

    # glance image-create
    if bottle.request.method == 'POST':
        bottle.response.status = 201
        image_md = json.load(bottle.request.body)
        return api_response.create_image(IMAGES.create(image_md))

    # glance image-list
    if (bottle.request.query.get('marker', None) is not None):
        # When the client wants more, tell it we're done
        return api_response.list_images([])
    else:
        # We don't 'do' marker, so return it all on the first call
        return api_response.list_images(IMAGES.list()) 
Example #13
Source File: auth.py    From bottle-jwt with GNU General Public License v3.0 6 votes vote down vote up
def authorize(self, request):
        """Checks if incoming request is authenticated.

        Args:
            request (instance): bottle.request instance.

        Returns:
            Request JWT decrypted payload, if request is authenticated else
            False.

        Raises:
            JWTProvider, if no auth header if present or invalid/expired
            token is provided.
        """
        user_token = request.get_header("Authorization", '')
        return self.validate_token(user_token) or False 
Example #14
Source File: server.py    From nematus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def translate(self):
        """
        Processes a translation request.
        """
        translation_request = request_provider(self._style, request)
        logging.debug("REQUEST - " + repr(translation_request))

        translations = self._translator.translate(
            translation_request.segments,
            translation_request.settings
        )
        response_data = {
            'status': TranslationResponse.STATUS_OK,
            'segments': [translation.target_words for translation in translations],
        }
        translation_response = response_provider(self._style, **response_data)
        logging.debug("RESPONSE - " + repr(translation_response))

        response.content_type = translation_response.get_content_type()
        return repr(translation_response) 
Example #15
Source File: test_bottle.py    From aws-xray-sdk-python with Apache License 2.0 6 votes vote down vote up
def test_custom_client_error():
    path = '/client_error'
    try:
        app.get(path)
    except Exception:
        pass
    segment = recorder.emitter.pop()
    assert not segment.in_progress
    assert segment.error

    response = segment.http['response']
    assert response['status'] == 400
    exception = segment.cause['exceptions'][0]
    assert exception.type == 'CustomError'

    request = segment.http['request']
    assert request['method'] == 'GET'
    assert request['url'] == BASE_URL.format(path) 
Example #16
Source File: test_bottle.py    From aws-xray-sdk-python with Apache License 2.0 6 votes vote down vote up
def test_error():
    path = '/error'
    try:
        app.get(path, extra_environ={'HTTP_X_FORWARDED_FOR': '192.168.0.0'})
    except Exception:
        pass
    segment = recorder.emitter.pop()
    assert not segment.in_progress
    assert segment.error

    request = segment.http['request']
    response = segment.http['response']
    assert request['method'] == 'GET'
    assert request['url'] == BASE_URL.format(path)
    assert request['client_ip'] == '192.168.0.0'
    assert response['status'] == 404 
Example #17
Source File: apiserver.py    From demobuilder with GNU General Public License v3.0 6 votes vote down vote up
def static(path):
    def copy(src, dst, n):
        while n > 0:
            d = src.read(min(n, 4096))
            if d == "":
                raise Exception()

            dst.write(d)
            n -= len(d)

    length = int(bottle.request.headers.get("Content-Length", "0"))
    if length <= 0 or bottle.request.headers.get("Content-Type", "") != "application/octet-stream":
        bottle.abort(400)

    path = "./" + path.strip("/")
    if os.path.dirname(path) and not os.path.isdir(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))

    with tempfile.NamedTemporaryFile(dir=os.path.dirname(path)) as f:
        copy(bottle.request["wsgi.input"], f, length)
        os.rename(f.name, path)
        f.delete = False

    return bottle.HTTPResponse(status=201, headers={"Location": path[2:]}) 
Example #18
Source File: oauth2.py    From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_userinfo_response(self):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib"

                uri, http_method, body, headers = extract_params(bottle.request)

                try:
                    resp_headers, resp_body, resp_status = self._oauthlib.create_userinfo_response(
                        uri, http_method=http_method, body=body, headers=headers
                    )
                except OAuth2Error as e:
                    resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code

                set_response(bottle.request, bottle.response, resp_status, resp_headers,
                             resp_body, force_json=True)

                func_response = f(*args, **kwargs)
                if func_response:
                    return func_response
                return bottle.response
            return wrapper
        return decorator 
Example #19
Source File: oauth2.py    From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_revocation_response(self):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib"

                uri, http_method, body, headers = extract_params(bottle.request)

                try:
                    resp_headers, resp_body, resp_status = self._oauthlib.create_revocation_response(
                        uri, http_method=http_method, body=body, headers=headers
                    )
                except OAuth2Error as e:
                    resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code

                set_response(bottle.request, bottle.response, resp_status, resp_headers, resp_body)

                func_response = f(*args, **kwargs)
                if func_response:
                    return func_response
                return bottle.response
            return wrapper
        return decorator 
Example #20
Source File: allinone.py    From NearlyPurePythonWebAppDemo with MIT License 6 votes vote down vote up
def getJSON(url, f):
        """
        JS version of jQuery.getJSON
        see http://youmightnotneedjquery.com/#get_json
        url must return a JSON string
        f(data) handles an object parsed from the return JSON string

        Uses JS: XMLHttpRequest, JSON.parse
        """
        request = __new__ (XMLHttpRequest())
        request.open('GET', url, True)
        def onload():
            if 200 <= request.status < 400:
                data = JSON.parse(request.responseText)
                f(data) ## call handler with object created from JSON string
            else:
                _ = "Server returned {} for getJSON request on {}".format(request.status, url)
                console.log(_)
        def onerror():
            _ = "Connection error for getJSON request on {}".format(url)
            console.log(_)
        request.onload = onload
        request.onerror = onerror
        request.send() 
Example #21
Source File: allinone.py    From NearlyPurePythonWebAppDemo with MIT License 6 votes vote down vote up
def handle_stepchange(event):
        """
        Check that the request for a new step size is a number between 0 and 10
        before allowing the submit action to proceed.

        Uses JS: .getElementById, alert, parseFloat, isNaN
        """
        fail_msg = "Step size must be a number between 0 and 10"
        v = document.getElementById('stepinput').value
        # Transcrypt float() is buggy, so use some inline JS.
        # See https://github.com/QQuick/Transcrypt/issues/314
        #__pragma__('js','{}','var vj = parseFloat(v); var isfloat = !isNaN(vj);')
        if isfloat and (0.0 <= vj <= 10.0):
            ## It's valid. Send it.
            post('/setstepsize', { 'stepsize': v })
            return False
        else:
            alert(fail_msg)
            return False 
Example #22
Source File: oauth2.py    From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_metadata_response(self):
        def decorator(f):
            @functools.wraps(f)
            def wrapper():
                assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib"

                uri, http_method, body, headers = extract_params(bottle.request)

                try:
                    resp_headers, resp_body, resp_status = self._oauthlib.create_metadata_response(
                        uri, http_method, body, headers
                    )
                except OAuth2Error as e:
                    resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code
                set_response(bottle.request, bottle.response, resp_status,
                             resp_headers, resp_body, force_json=True)

                func_response = f()
                if func_response:
                    return func_response
                return bottle.response
            return wrapper
        return decorator 
Example #23
Source File: api.py    From dwarf with Apache License 2.0 6 votes vote down vote up
def _route_images_id(image_id):
    """
    Route:  /image/v2/images/<image_id>
    Method: GET, DELETE, PATCH
    """
    utils.show_request(bottle.request)

    # glance image-delete
    if bottle.request.method == 'DELETE':
        bottle.response.status = 204
        IMAGES.delete(image_id)
        return

    # glance image-update
    if bottle.request.method == 'PATCH':
        image_ops = json.load(bottle.request.body)
        return api_response.update_image(IMAGES.update(image_id, image_ops))

    # glance image-show
    return api_response.show_image(IMAGES.show(image_id)) 
Example #24
Source File: bson_bottle_test.py    From bii-server with MIT License 5 votes vote down vote up
def __set_bson_content(self, data):
        bottle.request.environ['wsgi.input'] = str(BSON.encode(data))
        bottle.request.environ["CONTENT_LENGTH"] = len(bottle.request.environ['wsgi.input'])
        bottle.request.body = Mock
        bottle.request.body.read = Mock(return_value=bottle.request.environ['wsgi.input']) 
Example #25
Source File: tests.py    From boddle with GNU Lesser General Public License v2.1 5 votes vote down vote up
def testExtraStuff(self):
    with boddle(extra='woot'):
      self.assertEqual(bottle.request.extra, 'woot')
      with boddle(extra='woot2'):
        self.assertEqual(bottle.request.extra, 'woot2')
    self.assertFalse(hasattr(bottle.request,'extra')) 
Example #26
Source File: importer.py    From conifer with Apache License 2.0 5 votes vote down vote up
def do_upload(self, upload_key, filename, stream, user, coll, rec, offset, length):
        """Send PUT request to upload recording.

        :param str upload_key: upload Redis key
        :param str filename: WARC archive filename
        :param stream: file object
        :param User user: user
        :param str coll: collection ID
        :param str rec: record ID
        :param int offset: offset to start of stream
        :param int length: length of recording
        """
        stream.seek(offset)

        logger.debug('do_upload(): {0} offset: {1}: len: {2}'.format(rec, offset, length))

        stream = LimitReader(stream, length)
        headers = {'Content-Length': str(length)}

        upload_url = self.upload_path.format(record_host=self.record_host,
                                             user=user,
                                             coll=coll,
                                             rec=rec,
                                             upid=upload_key)

        r = requests.put(upload_url,
                         headers=headers,
                         data=stream) 
Example #27
Source File: tests.py    From boddle with GNU Lesser General Public License v2.1 5 votes vote down vote up
def testJSON(self):
    with boddle(json={'name':'derek'}):
      self.assertEqual(bottle.request.json['name'], 'derek') 
Example #28
Source File: web-power.py    From pi-power with GNU General Public License v3.0 5 votes vote down vote up
def switchon():
    socket = int(request.query.socket)
    # If single socket requested
    if (socket > 0 and socket <= 4) :
        #print 'Switching on {}'.format(socket)
        sockets[socket].on()
        return 'Requested switch on {}'.format(socket)
    # If all sockets requested
    elif (socket == 0) : 
        for i in range (1, 5):
            sockets[i].on()
        return 'Requested switch on ALL'
    else :
        return 'Invalid request' 
Example #29
Source File: app.py    From script.tubecast with MIT License 5 votes vote down vote up
def _register_listener(self):
        self.has_client = True
        pairing_code = request.forms.get("pairingCode")
        self._pair(pairing_code)
        response.status = 201
        return "" 
Example #30
Source File: app.py    From script.tubecast with MIT License 5 votes vote down vote up
def __post_bind(self, sc, postdata):  # type: (str, dict) -> None
        self.ofs += 1
        post_data = {"count": "1", "ofs": str(self.ofs), "req0__sc": sc}
        for key in list(postdata.keys()):
            post_data["req0_" + key] = postdata[key]

        if get_setting_as_bool("debug-http"):
            logger.debug("POST %s:\n%r", sc, post_data)

        bind_vals = self.bind_vals
        bind_vals["RID"] = "1337"
        url = "{}/api/lounge/bc/bind?{}".format(self.base_url, urlencode(bind_vals))
        verify_ssl = get_setting_as_bool("verify-ssl")

        last_exc = None
        for i in range(MAX_SEND_RETRIES):
            try:
                self.session.post(url, data=post_data, verify=verify_ssl)
            except requests.ConnectionError as e:
                logger.info("failed to send data on attempt %s/%s", i + 1, MAX_SEND_RETRIES)
                last_exc = e
                continue
            except Exception:
                logger.exception("error sending %s", sc)
                break
            else:
                # request successful
                break
        else:
            # MAX_SEND_RETRIES exceeded
            logger.exception("failed to send data to client", exc_info=last_exc)