twisted.web.http.BAD_REQUEST

Here are the examples of the python api twisted.web.http.BAD_REQUEST taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

60 Examples 7

Page 1 Selected Page 2

Example 1

Project: petmail Source File: web.py
Function: render_post
    def render_POST(self, request):
        err = None
        try:
            results = self.handle(self.payload.get("args", {}))
            if isinstance(results, (str, unicode)):
                results = {"ok": results}
        except CommandError, e:
            # this is the only way to signal a "known" error
            err = unicode(e.msg)
        if err:
            request.setResponseCode(http.BAD_REQUEST, "command error")
            request.setHeader("content-type", "text/plain; charset=utf-8")
            return err.encode("utf-8")
        assert "ok" in results, (results, type(results))
        request.setResponseCode(http.OK, "OK")
        request.setHeader("content-type", "application/json; charset=utf-8")
        return json.dumps(results).encode("utf-8")

Example 2

Project: worker Source File: test_api.py
    @trigger("not-list-targets")
    @inlineCallbacks
    def testSendNotListTargets(self):
        response, body = yield self.request('PUT', 'trigger/{0}'.format(self.trigger.id),
                                            '{ "name":"111", \
        "targets":{"target":"DevOps.system.*.loadavg.load"}, \
        "expression":"WARN if t1 > 10 else OK", \
        "tags":"1111" }', http.BAD_REQUEST)
        self.flushLoggedErrors()
        self.assertEqual("Invalid trigger targets", body)

Example 3

Project: wolverine Source File: pubsub.py
Function: render_post
    def render_POST(self, request):
        mode = request.args.get('hub.mode', [None])[0]
        url = request.args.get('hub.url', [None])[0]
        
        if not mode or not url:
            request.setResponseCode(http.BAD_REQUEST)
            return "400 Bad request: Expected 'hub.mode' and 'hub.url'"
        
        if mode == 'publish':
            publish(url)
            request.setResponseCode(http.NO_CONTENT)
            return "204 Published"
        else:
            request.setResponseCode(http.BAD_REQUEST)
            return "400 Bad request: Unrecognized mode"

Example 4

Project: flud Source File: ServerDHTPrimitives.py
Function: render_get
    def render_GET(self, request):
        logger.debug("META get (findval)")
        if len(request.prepath) != 2:
            request.setResponseCode(http.BAD_REQUEST, "expected key")
            return "expected key, got %s" % '/'.join(request.prepath)
        key = request.prepath[1]
        self.setHeaders(request)
        return kFindVal(self.node, self.config, request, key).deferred

Example 5

Project: idavoll Source File: gateway.py
    def checkMediaType(self, request):
        ctype = request.getHeader(b'content-type')

        if not ctype:
            request.setResponseCode(http.BAD_REQUEST)

            raise Error(http.BAD_REQUEST, b"No specified Media Type")

        message = _parseContentType(ctype)
        if (message.maintype != b'application' or
            message.subtype != b'atom+xml' or
            message.getparam(b'type') != b'entry' or
            (message.getparam(b'charset') or b'utf-8') != b'utf-8'):
            raise Error(http.UNSUPPORTED_MEDIA_TYPE,
                              b"Unsupported Media Type: %s" % ctype)

Example 6

Project: vumi Source File: mxit.py
Function: handle_raw_inbound_message
    def handle_raw_inbound_message(self, msg_id, request):
        if not self.is_mxit_request(request):
            return self.finish_request(
                msg_id, data=http.RESPONSES[http.BAD_REQUEST],
                code=http.BAD_REQUEST)

        data = self.get_request_data(request)
        content = self.get_request_content(request)
        return self.publish_message(
            message_id=msg_id,
            content=content,
            to_addr=data['X-Mxit-Contact'],
            from_addr=data['X-Mxit-USERID-R'],
            provider='mxit',
            transport_type=self.transport_type,
            helper_metadata={
                'mxit_info': data,
            })

Example 7

Project: pyamf Source File: test_twisted.py
    def test_bad_content(self):
        d = self.getPage('spamandeggs')
        d = self.assertFailure(d, error.Error)

        d.addCallback(
            lambda exc: self.assertEqual(int(exc.args[0]), http.BAD_REQUEST))

        return d

Example 8

Project: worker Source File: tags.py
Function: render_delete
    @delayed
    @defer.inlineCallbacks
    def render_DELETE(self, request):
        triggers = yield self.db.getTagTriggers(self.tag)
        if triggers:
            request.setResponseCode(http.BAD_REQUEST)
            request.write(
                "This tag is assigned to %s triggers. Remove tag from triggers first" %
                len(triggers))
            request.finish()
        else:
            existing = yield self.db.getTag(self.tag)
            yield self.db.removeTag(self.tag, request=request, existing=existing)
            self.write_json(request, {"message": "tag deleted"})

Example 9

Project: worker Source File: test_api.py
    @trigger("without-warn-value")
    @inlineCallbacks
    def testSendWithoutWarnValue(self):
        response, body = yield self.request('PUT', 'trigger/{0}'.format(self.trigger.id),
                                            '{"name": "test trigger", "targets": ["sumSeries(*)"], "error_value": 50 }',
                                            http.BAD_REQUEST)
        self.flushLoggedErrors()
        self.assertEqual("warn_value is required", body)

Example 10

Project: vumi Source File: test_apposit.py
    @inlineCallbacks
    def test_outbound_requests_for_unknown_error_responses(self):
        code = '103000'
        self.set_fake_http_response(http.BAD_REQUEST, code)

        msg = yield self.tx_helper.make_dispatch_outbound("so many dynamos")

        [nack] = yield self.tx_helper.wait_for_dispatched_events(1)
        self.assert_nack(
            nack, msg, self.transport.UNKNOWN_RESPONSE_CODE_ERROR % code)

Example 11

Project: tahoe-lafs Source File: common.py
def parse_replace_arg(replace):
    if replace.lower() == "only-files":
        return replace
    try:
        return boolean_of_arg(replace)
    except WebError:
        raise WebError("invalid replace= argument: %r" % (replace,), http.BAD_REQUEST)

Example 12

Project: idavoll Source File: test_gateway.py
    def test_postMalformedXMPPURI(self):
        """
        If the XMPP URI is malformed, Bad Request is returned.
        """
        request = DummyRequest([b''])
        request.method = b'POST'

        def rendered(result):
            self.assertEqual(http.BAD_REQUEST, request.responseCode)

        uri = 'xmpp:@@@@'
        request.args[b'uri'] = [uri]
        request.content = StringIO(b'')

        d = _render(self.resource, request)
        d.addCallback(rendered)
        return d

Example 13

Project: vumi-go Source File: conversation_api.py
    @inlineCallbacks
    def handle_jsbox(self, request, command, conversation):
        if command == 'postcommit':
            conv_config = conversation.get_config()

            # update the config blocks
            jsbox_app_config = conv_config.get('jsbox_app_config', {})
            for key, config_section in jsbox_app_config.items():
                yield self.update_jsbox_config('value', config_section)

            # update the application code
            jsbox_md = conv_config.get('jsbox', {})
            yield self.update_jsbox_config('javascript', jsbox_md)

            conversation.set_config(conv_config)
            yield conversation.save()
        else:
            request.setResponseCode(http.BAD_REQUEST)

Example 14

Project: tahoe-lafs Source File: unlinked.py
def PUTUnlinkedCreateDirectory(req, client):
    # "PUT /uri?t=mkdir", to create an unlinked directory.
    file_format = get_format(req, None)
    if file_format == "CHK":
        raise WebError("format=CHK not accepted for PUT /uri?t=mkdir",
                       http.BAD_REQUEST)
    mt = None
    if file_format:
        mt = get_mutable_type(file_format)
    d = client.create_dirnode(version=mt)
    d.addCallback(lambda dirnode: dirnode.get_uri())
    # XXX add redirect_to_result
    return d

Example 15

Project: petmail Source File: web.py
    def render_GET(self, request):
        if "text/event-stream" not in (request.getHeader("accept") or ""):
            request.setResponseCode(http.BAD_REQUEST, "Must use EventSource")
            return "Must use EventSource (Content-Type: text/event-stream)"
        request.setHeader("content-type", "text/event-stream")
        self.events_protocol = EventsProtocol(request)
        request.notifyFinish().addErrback(self._shutdown)
        # tell the frontend it's safe to subscribe
        self.events_protocol.sendEvent(json.dumps({"type": "ready"}))
        return server.NOT_DONE_YET

Example 16

Project: flud Source File: ServerDHTPrimitives.py
Function: render_put
    def render_PUT(self, request):
        logger.debug("META put (storeval)")
        if len(request.prepath) != 3:
            request.setResponseCode(http.BAD_REQUEST, "expected key/val")
            return "expected key/val, got %s" % '/'.join(request.prepath)
        key = request.prepath[1]
        val = request.prepath[2]
        self.setHeaders(request)
        return kStoreVal(self.node, self.config, request, key, val).deferred

Example 17

Project: vumi-go Source File: test_vumi_app.py
    def assert_bad_request(self, response, reason):
        self.assertEqual(response.code, http.BAD_REQUEST)
        self.assertEqual(
            response.headers.getRawHeaders('content-type'),
            ['application/json; charset=utf-8'])
        data = json.loads(response.delivered_body)
        self.assertEqual(data, {
            "success": False,
            "reason": reason,
        })

Example 18

Project: worker Source File: test_api.py
    @trigger("delete-tag")
    @inlineCallbacks
    def testTagDeletion(self):
        response, body = yield self.request('PUT', 'trigger/{0}'.format(self.trigger.id),
                                            '{"name": "test trigger", "targets": ["sumSeries(*)"], \
                                             "warn_value": "1e-7", "error_value": 50, "tags": ["tag1", "tag2"] }',
                                            )
        response, body = yield self.request('GET', 'trigger/{0}'.format(self.trigger.id))
        response, body = yield self.request('DELETE', 'tag/tag1', state=http.BAD_REQUEST)
        response, body = yield self.request('DELETE', 'trigger/{0}'.format(self.trigger.id))
        response, body = yield self.request('DELETE', 'tag/tag1')

Example 19

Project: vumi Source File: wechat.py
Function: handle_error
    @inlineCallbacks
    def handle_error(self, failure, request):
        if not failure.trap(WeChatException):
            raise failure

        yield self.transport.add_status_bad_req()
        request.setResponseCode(http.BAD_REQUEST)
        request.write(failure.getErrorMessage())
        request.finish()

Example 20

Project: worker Source File: test_api.py
    @trigger("wrong-time-span")
    @inlineCallbacks
    def testSendWrongTimeSpan(self):
        response, body = yield self.request('PUT', 'trigger/{0}'.format(self.trigger.id),
                                            '{"name": "test trigger", "targets": ["movingAverage(*, \\"10g\\")"], \
                                             "warn_value": "1e-7", "error_value": 50}', http.BAD_REQUEST)
        self.flushLoggedErrors()
        self.assertEqual("Invalid graphite targets", body)

Example 21

Project: worker Source File: test_api.py
    @trigger("invalid-expression-trigger")
    @inlineCallbacks
    def testSendInvalidExpressionTrigger(self):
        response, body = yield self.request('PUT', 'trigger/{0}'.format(self.trigger.id),
                                            '{"name":"test trigger","targets":["metric"], \
                                             "warn_value":-0.1, "error_value":0.1,"ttl":600,"ttl_state":"NODATA", \
                                             "tags":["tag1"],"expression":"ERROR if"}', http.BAD_REQUEST)
        self.flushLoggedErrors()
        self.assertEqual("Invalid expression", body)

Example 22

Project: vumi Source File: test_netcore.py
    @inlineCallbacks
    def test_inbound_content_none_string_literal(self):
        transport = yield self.get_transport()
        resp = yield request(transport, 'POST', {
            'to_addr': '10010',
            'from_addr': '8800000000',
            'content': 'None',  # Python str(None) on netcore's side
            'source': 'sms',
            'circle': 'of life',
        })
        self.assertEqual(resp.code, http.BAD_REQUEST)
        self.assertEqual(resp.delivered_body, (
            '"None" string literal not allowed for content parameter.'))
        self.assertEqual(
            [], self.tx_helper.get_dispatched_inbound())

Example 23

Project: vumi Source File: test_apposit.py
    @inlineCallbacks
    def test_outbound_requests_for_known_error_responses(self):
        code = '102999'
        self.set_fake_http_response(http.BAD_REQUEST, code)

        msg = yield self.tx_helper.make_dispatch_outbound('racecar')

        [nack] = yield self.tx_helper.wait_for_dispatched_events(1)
        self.assert_nack(nack, msg, "(%s) %s" % (
            code, self.transport.KNOWN_ERROR_RESPONSE_CODES[code]))

Example 24

Project: vumi Source File: rapidsms_relay.py
    def fail_request(self, request, f):
        if f.check(BadRequestError):
            code = http.BAD_REQUEST
        else:
            code = http.INTERNAL_SERVER_ERROR
        log.err(f)
        request.setResponseCode(code)
        request.write(f.getErrorMessage())
        request.finish()

Example 25

Project: mamba-framework Source File: response.py
    def __init__(self, code, subject, headers):
        self.code = code
        self.subject = subject
        self.headers = headers

        if code in (http.BAD_REQUEST, http.NOT_FOUND):
            if type(self.subject) not in [unicode, str]:
                log.msg(brown(str(self.subject)), logLevel=logging.WARN)
            else:
                log.msg(brown(self.subject), logLevel=logging.WARN)

Example 26

Project: vumi Source File: test_wechat.py
    @inlineCallbacks
    def test_nack_push_text_message(self):
        yield self.get_transport_with_access_token('foo')
        msg_d = self.dispatch_push_message('foo', {})

        # fail the API request
        request = yield self.request_queue.get()
        request.setResponseCode(http.BAD_REQUEST)
        request.finish()

        msg = yield msg_d
        [nack] = yield self.tx_helper.wait_for_dispatched_events(1)
        self.assertEqual(
            nack['user_message_id'], msg['message_id'])
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['nack_reason'], 'Received status code: 400')

Example 27

Project: idavoll Source File: test_gateway.py
    def test_postURIMissing(self):
        """
        If no URI is passed, 400 Bad Request is returned.
        """
        request = DummyRequest([b''])
        request.method = b'POST'

        def rendered(result):
            self.assertEqual(http.BAD_REQUEST, request.responseCode)

        request.content = StringIO(b'')

        d = _render(self.resource, request)
        d.addCallback(rendered)
        return d

Example 28

Project: crossbar Source File: longpoll.py
Function: fail_request
    def _fail_request(self, request, msg):
        """
        Fails a request to the long-poll service.
        """
        self._set_standard_headers(request)
        request.setHeader(b'content-type', b'text/plain; charset=UTF-8')
        request.setResponseCode(http.BAD_REQUEST)
        return msg

Example 29

Project: tahoe-lafs Source File: common.py
Function: get_format
def get_format(req, default="CHK"):
    arg = get_arg(req, "format", None)
    if not arg:
        if boolean_of_arg(get_arg(req, "mutable", "false")):
            return "SDMF"
        return default
    if arg.upper() == "CHK":
        return "CHK"
    elif arg.upper() == "SDMF":
        return "SDMF"
    elif arg.upper() == "MDMF":
        return "MDMF"
    else:
        raise WebError("Unknown format: %s, I know CHK, SDMF, MDMF" % arg,
                       http.BAD_REQUEST)

Example 30

Project: vumi Source File: test_netcore.py
    @inlineCallbacks
    def test_inbound_sms_failure(self):
        transport = yield self.get_transport()
        resp = yield request(transport, 'POST', {
            'foo': 'bar'
        })
        self.assertEqual(resp.code, http.BAD_REQUEST)
        self.assertEqual(resp.delivered_body, (
            "Not all expected parameters received. Only allowing: "
            "['to_addr', 'from_addr', 'content', 'circle', 'source'], "
            "received: ['foo']"))
        self.assertEqual(
            [], self.tx_helper.get_dispatched_inbound())

Example 31

Project: tahoe-lafs Source File: root.py
    def render_PUT(self, ctx):
        req = IRequest(ctx)
        # either "PUT /uri" to create an unlinked file, or
        # "PUT /uri?t=mkdir" to create an unlinked directory
        t = get_arg(req, "t", "").strip()
        if t == "":
            file_format = get_format(req, "CHK")
            mutable_type = get_mutable_type(file_format)
            if mutable_type is not None:
                return unlinked.PUTUnlinkedSSK(req, self.client, mutable_type)
            else:
                return unlinked.PUTUnlinkedCHK(req, self.client)
        if t == "mkdir":
            return unlinked.PUTUnlinkedCreateDirectory(req, self.client)
        errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
                  "and POST?t=mkdir")
        raise WebError(errmsg, http.BAD_REQUEST)

Example 32

Project: worker Source File: test_api.py
    @trigger("not-json-trigger")
    @inlineCallbacks
    def testSendNotJsonTrigger(self):
        response, body = yield self.request('PUT', 'trigger/{0}'.format(self.trigger.id),
                                            "i am not json", http.BAD_REQUEST)
        self.flushLoggedErrors()
        self.assertEqual("Content is not json", body)

Example 33

Project: vumi Source File: test_netcore.py
    @inlineCallbacks
    def test_inbound_missing_values(self):
        transport = yield self.get_transport()
        resp = yield request(transport, 'POST', {
            'to_addr': '10010',
            'from_addr': '8800000000',
            'content': '',  # Intentionally empty!
            'source': 'sms',
            'circle': 'of life',
        })
        self.assertEqual(resp.code, http.BAD_REQUEST)
        self.assertEqual(resp.delivered_body, (
            "Not all parameters have values. "
            "Received: %r" % (sorted(
                ['', 'sms', 'of life', '10010', '8800000000']),)))
        self.assertEqual(
            [], self.tx_helper.get_dispatched_inbound())

Example 34

Project: vumi Source File: test_airtel.py
    @inlineCallbacks
    def test_cleanup_session_missing_params(self):
        response = yield self.mk_request(clean='clean-session')
        self.assertEqual(response.code, http.BAD_REQUEST)
        json_response = json.loads(response.delivered_body)
        self.assertEqual(set(json_response['missing_parameter']),
                         set(['msisdn', 'SessionID', 'error']))

Example 35

Project: deblaze Source File: test_twisted.py
    def test_bad_content(self):
        d = client.getPage("http://127.0.0.1:%d/" % (self.port,),
                method="POST", postdata="spamandeggs")
        d = self.assertFailure(d, error.Error)
        d.addCallback(
            lambda exc: self.assertEquals(int(exc.args[0]), http.BAD_REQUEST))

        return d

Example 36

Project: tahoe-lafs Source File: common.py
def boolean_of_arg(arg):
    # TODO: ""
    if arg.lower() not in ("true", "t", "1", "false", "f", "0", "on", "off"):
        raise WebError("invalid boolean argument: %r" % (arg,), http.BAD_REQUEST)
    return arg.lower() in ("true", "t", "1", "on")

Example 37

Project: vumi Source File: imimobile_ussd.py
    @inlineCallbacks
    def handle_raw_inbound_message(self, message_id, request):
        errors = {}

        to_addr, to_addr_errors = self.get_to_addr(request)
        errors.update(to_addr_errors)

        values, field_value_errors = self.get_field_values(request,
                                                        self.EXPECTED_FIELDS)
        errors.update(field_value_errors)

        if errors:
            log.msg('Unhappy incoming message: %s' % (errors,))
            yield self.finish_request(
                message_id, json.dumps(errors), code=http.BAD_REQUEST)
            return

        from_addr = values['msisdn']
        log.msg('ImiMobileTransport receiving inbound message from %s to %s.' %
                (from_addr, to_addr))

        content = values['msg']
        if self.user_has_terminated_session(content):
            yield self.session_manager.clear_session(from_addr)
            session_event = TransportUserMessage.SESSION_CLOSE

            # IMImobile use 0 for termination of a session
            self.finish_request(
                message_id,
                self.user_terminated_session_response,
                headers={'X-USSD-SESSION': ['0']})
        else:
            # We use the msisdn (from_addr) to make a guess about the
            # whether the session is new or not.
            session = yield self.session_manager.load_session(from_addr)
            if session:
                session_event = TransportUserMessage.SESSION_RESUME
                yield self.session_manager.save_session(from_addr, session)
            else:
                session_event = TransportUserMessage.SESSION_NEW
                yield self.session_manager.create_session(
                    from_addr, from_addr=from_addr, to_addr=to_addr)

        yield self.publish_message(
            message_id=message_id,
            content=content,
            to_addr=to_addr,
            from_addr=from_addr,
            provider='imimobile',
            session_event=session_event,
            transport_type=self.transport_type,
            transport_metadata={
                'imimobile_ussd': {
                    'tid': values['tid'],
                    'code': values['code'],
                    'dcs': values['dcs'],
                }
            })

Example 38

Project: vumi Source File: wechat.py
Function: render_get
    def render_GET(self, request):
        if is_verifiable(request) and verify(self.config.auth_token, request):
            return request.args['echostr'][0]
        request.setResponseCode(http.BAD_REQUEST)
        return ''

Example 39

Project: tahoe-lafs Source File: common.py
def humanize_failure(f):
    # return text, responsecode
    if f.check(EmptyPathnameComponentError):
        return ("The webapi does not allow empty pathname components, "
                "i.e. a double slash", http.BAD_REQUEST)
    if f.check(ExistingChildError):
        return ("There was already a child by that name, and you asked me "
                "to not replace it.", http.CONFLICT)
    if f.check(NoSuchChildError):
        quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
        return ("No such child: %s" % quoted_name, http.NOT_FOUND)
    if f.check(NotEnoughSharesError):
        t = ("NotEnoughSharesError: This indicates that some "
             "servers were unavailable, or that shares have been "
             "lost to server departure, hard drive failure, or disk "
             "corruption. You should perform a filecheck on "
             "this object to learn more.\n\nThe full error message is:\n"
             "%s") % str(f.value)
        return (t, http.GONE)
    if f.check(NoSharesError):
        t = ("NoSharesError: no shares could be found. "
             "Zero shares usually indicates a corrupt URI, or that "
             "no servers were connected, but it might also indicate "
             "severe corruption. You should perform a filecheck on "
             "this object to learn more.\n\nThe full error message is:\n"
             "%s") % str(f.value)
        return (t, http.GONE)
    if f.check(UnrecoverableFileError):
        t = ("UnrecoverableFileError: the directory (or mutable file) could "
             "not be retrieved, because there were insufficient good shares. "
             "This might indicate that no servers were connected, "
             "insufficient servers were connected, the URI was corrupt, or "
             "that shares have been lost due to server departure, hard drive "
             "failure, or disk corruption. You should perform a filecheck on "
             "this object to learn more.")
        return (t, http.GONE)
    if f.check(MustNotBeUnknownRWError):
        quoted_name = quote_output(f.value.args[1], encoding="utf-8")
        immutable = f.value.args[2]
        if immutable:
            t = ("MustNotBeUnknownRWError: an operation to add a child named "
                 "%s to a directory was given an unknown cap in a write slot.\n"
                 "If the cap is actually an immutable readcap, then using a "
                 "webapi server that supports a later version of Tahoe may help.\n\n"
                 "If you are using the webapi directly, then specifying an immutable "
                 "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
                 "omitting the write slot (rw_uri), would also work in this "
                 "case.") % quoted_name
        else:
            t = ("MustNotBeUnknownRWError: an operation to add a child named "
                 "%s to a directory was given an unknown cap in a write slot.\n"
                 "Using a webapi server that supports a later version of Tahoe "
                 "may help.\n\n"
                 "If you are using the webapi directly, specifying a readcap in "
                 "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
                 "writecap in the write slot if desired, would also work in this "
                 "case.") % quoted_name
        return (t, http.BAD_REQUEST)
    if f.check(MustBeDeepImmutableError):
        quoted_name = quote_output(f.value.args[1], encoding="utf-8")
        t = ("MustBeDeepImmutableError: a cap passed to this operation for "
             "the child named %s, needed to be immutable but was not. Either "
             "the cap is being added to an immutable directory, or it was "
             "originally retrieved from an immutable directory as an unknown "
             "cap.") % quoted_name
        return (t, http.BAD_REQUEST)
    if f.check(MustBeReadonlyError):
        quoted_name = quote_output(f.value.args[1], encoding="utf-8")
        t = ("MustBeReadonlyError: a cap passed to this operation for "
             "the child named '%s', needed to be read-only but was not. "
             "The cap is being passed in a read slot (ro_uri), or was retrieved "
             "from a read slot as an unknown cap.") % quoted_name
        return (t, http.BAD_REQUEST)
    if f.check(blacklist.FileProhibited):
        t = "Access Prohibited: %s" % quote_output(f.value.reason, encoding="utf-8", quotemarks=False)
        return (t, http.FORBIDDEN)
    if f.check(WebError):
        return (f.value.text, f.value.code)
    if f.check(FileTooLargeError):
        return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
    return (str(f), None)

Example 40

Project: vumi Source File: apposit.py
    @inlineCallbacks
    def handle_raw_inbound_message(self, message_id, request):
        values, errors = self.get_field_values(request, self.EXPECTED_FIELDS)

        channel = values.get('channel')
        if channel is not None and channel not in self.CHANNEL_LOOKUP.values():
            errors['unsupported_channel'] = channel

        if errors:
            log.msg('Unhappy incoming message: %s' % (errors,))
            yield self.finish_request(message_id, json.dumps(errors),
                                      code=http.BAD_REQUEST)
            return

        self.emit("AppositTransport receiving inbound message from "
                  "%(from)s to %(to)s" % values)

        yield self.publish_message(
            transport_name=self.transport_name,
            message_id=message_id,
            content=values['content'],
            from_addr=values['from'],
            to_addr=values['to'],
            provider='apposit',
            transport_type=self.TRANSPORT_TYPE_LOOKUP[channel],
            transport_metadata={'apposit': {'isTest': values['isTest']}})

        yield self.finish_request(
            message_id, json.dumps({'message_id': message_id}))

Example 41

Project: vumi-go Source File: conversation_api.py
Function: fallback_handler
    def fallback_handler(self, request, command, conversation):
        request.setResponseCode(http.BAD_REQUEST)
        succeed(None)

Example 42

Project: vumi Source File: airtel.py
    def handle_bad_request(self, message_id, request, errors):
        log.msg('Unhappy incoming message: %s' % (errors,))
        return self.finish_request(message_id, json.dumps(errors),
                                   code=http.BAD_REQUEST)

Example 43

Project: vumi Source File: netcore.py
Function: render_post
    def render_POST(self, request):
        expected_keys = [
            'to_addr',
            'from_addr',
            'content',
            'circle',
            'source',
        ]

        received = set(request.args.keys())
        expected = set(expected_keys)
        if received != expected:
            request.setResponseCode(http.BAD_REQUEST)
            return ('Not all expected parameters received. '
                    'Only allowing: %r, received: %r' % (
                        expected_keys, request.args.keys()))
        param_values = [param[0] for param in request.args.values()]
        if not all(param_values):
            request.setResponseCode(http.BAD_REQUEST)
            return ('Not all parameters have values. '
                    'Received: %r' % (sorted(param_values),))

        content = request.args['content'][0]
        if self.config.reject_none and content == "None":
            request.setResponseCode(http.BAD_REQUEST)
            return ('"None" string literal not allowed for content parameter.')

        self.handle_request(request)
        return NOT_DONE_YET

Example 44

Project: wolverine Source File: pubsub.py
Function: render_post
    def render_POST(self, request):
        mode        = request.args.get('hub.mode', [None])[0]
        callback    = request.args.get('hub.callback', [None])[0]
        topic       = request.args.get('hub.topic', [None])[0]
        verify      = request.args.get('hub.verify', [None])
        verify_token = request.args.get('hub.verify_token', [None])[0]
        
        if not mode or not callback or not topic or not verify:
            request.setResponseCode(http.BAD_REQUEST)
            return "400 Bad request: Expected 'hub.mode', 'hub.callback', 'hub.topic', and 'hub.verify'"
        
        if not mode in ['subscribe', 'unsubscribe']:
            request.setResponseCode(http.BAD_REQUEST)
            return "400 Bad request: Unrecognized mode"
        
        verify = verify[0] # For now, only using the first preference of verify mode
        if not verify in ['sync', 'async']:
            request.setResponseCode(http.BAD_REQUEST)
            return "400 Bad request: Unsupported verification mode"
            
        to_verify = {'mode': mode, 'callback': callback, 'topic': topic, 'verify_token': verify_token}
        if verify == 'sync':
            def finish_success(request):
                request.setResponseCode(http.NO_CONTENT)
                request.write("204 Subscription created")
                request.finish()
            def finish_failed(request):
                request.setResponseCode(http.CONFLICT)
                request.write("409 Subscription verification failed")
                request.finish()
            subscribe(to_verify).addCallbacks(lambda x: finish_success(request), lambda x: finish_failed(request))
            return NOT_DONE_YET
            
        elif verify == 'async':
            subscribe(to_verify)
            request.setResponseCode(http.ACCEPTED)
            return "202 Scheduled for verification"

Example 45

Project: mamba-framework Source File: test_response.py
    def test_response_bad_request_code_is_400(self):
        result = response.BadRequest()
        self.assertEqual(result.code, http.BAD_REQUEST)

Example 46

Project: mamba-framework Source File: response.py
Function: init
    def __init__(self, subject='', headers={}):
        super(BadRequest, self).__init__(http.BAD_REQUEST, subject, headers)

Example 47

Project: vumi Source File: opera.py
Function: render_post
    def render_POST(self, request):
        try:
            content = get_receipts_xml(request.content.read())
            sms = utils.parse_post_event_xml(content)
            for field in [
                    'Local', 'Remote', 'Text', 'MessageID', 'MobileNetwork']:
                if field not in sms:
                    raise BadRequestError("Missing field: %s" % (field,))
        except BadRequestError as err:
            request.setResponseCode(http.BAD_REQUEST)
            request.setHeader('Content-Type', 'text/plain; charset=utf8')
            return err.args[0]
        self.callback(
            to_addr=normalize_msisdn(sms['Local'], country_code='27'),
            from_addr=normalize_msisdn(sms['Remote'], country_code='27'),
            content=sms['Text'], transport_type='sms',
            message_id=sms['MessageID'], transport_metadata={
                'provider': sms['MobileNetwork']
            })
        request.setResponseCode(http.OK)
        request.setHeader('Content-Type', 'text/xml; charset=utf8')
        return content

Example 48

Project: idavoll Source File: gateway.py
    @_asyncResponse
    def render_GET(self, request):
        try:
            maxItems = int(request.args.get('max_items', [0])[0]) or None
        except ValueError:
            raise Error(http.BAD_REQUEST,
                        "The argument max_items has an invalid value.")

        try:
            uri = request.args['uri'][0]
        except KeyError:
            raise Error(http.BAD_REQUEST,
                        "No URI for the remote node provided.")

        try:
            jid, nodeIdentifier = getServiceAndNode(uri)
        except XMPPURIParseError:
            raise Error(http.BAD_REQUEST,
                        "Malformed XMPP URI: %s" % uri)

        def toResponse(items):
            """
            Create a feed out the retrieved items.
            """
            atomEntries = extractAtomEntries(items)
            feed = constructFeed(jid, nodeIdentifier, atomEntries,
                                    "Retrieved item collection")
            body = feed.toXml().encode('utf-8')
            request.setHeader(b'Content-Type', MIME_ATOM_FEED)
            return body

        def trapNotFound(failure):
            failure.trap(StanzaError)
            if not failure.value.condition == 'item-not-found':
                raise failure
            raise Error(http.NOT_FOUND, "Node not found")

        d = self.service.items(jid, nodeIdentifier, maxItems)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        return d

Example 49

Project: vumi Source File: dmark_ussd.py
    @inlineCallbacks
    def handle_raw_inbound_message(self, request_id, request):
        try:
            values, errors = self.get_field_values(
                request, self.EXPECTED_FIELDS)
        except UnicodeDecodeError:
            self.log.msg('Bad request encoding: %r' % request)
            request_dict = {
                'uri': request.uri,
                'method': request.method,
                'path': request.path,
                'content': request.content.read(),
                'headers': dict(request.requestHeaders.getAllRawHeaders()),
            }
            self.finish_request(
                request_id, json.dumps({'invalid_request': request_dict}),
                code=http.BAD_REQUEST)
            yield self.add_status(
                component='request',
                status='down',
                type='invalid_encoding',
                message='Invalid encoding',
                details={
                    'request': request_dict,
                })
            return

        if errors:
            self.log.msg('Unhappy incoming message: %r' % (errors,))
            self.finish_request(
                request_id, json.dumps(errors), code=http.BAD_REQUEST)
            yield self.add_status(
                component='request',
                status='down',
                type='invalid_inbound_fields',
                message='Invalid inbound fields',
                details=errors)
            return

        yield self.add_status(
            component='request',
            status='ok',
            type='request_parsed',
            message='Request parsed',)

        to_addr = values["ussdServiceCode"]
        from_addr = values["msisdn"]
        content = values["ussdRequestString"]
        session_event = yield self.session_event_for_transaction(
            values["transactionId"])
        if session_event == TransportUserMessage.SESSION_NEW:
            content = None

        yield self.publish_message(
            message_id=request_id,
            content=content,
            to_addr=to_addr,
            from_addr=from_addr,
            provider='dmark',
            session_event=session_event,
            transport_type=self.transport_type,
            transport_metadata={
                'dmark_ussd': {
                    'transaction_id': values['transactionId'],
                    'transaction_time': values['transactionTime'],
                    'creation_time': values['creationTime'],
                }
            })

Example 50

Project: vumi Source File: test_wechat.py
    @inlineCallbacks
    def test_unsupported_message_type(self):
        transport = yield self.get_transport_with_access_token('foo')

        response = yield request(
            transport, 'POST', data="""
            <xml>
            <ToUserName><![CDATA[toUser]]></ToUserName>
            <FromUserName><![CDATA[fromUser]]></FromUserName>
            <CreateTime>1348831860</CreateTime>
            <MsgType><![CDATA[THIS_IS_UNSUPPORTED]]></MsgType>
            <Content><![CDATA[this is a test]]></Content>
            <MsgId>1234567890123456</MsgId>
            </xml>
            """.strip())

        self.assertEqual(
            response.code, http.BAD_REQUEST)
        self.assertEqual(
            response.delivered_body,
            "Unsupported MsgType: THIS_IS_UNSUPPORTED")
        self.assertEqual(
            [],
            self.tx_helper.get_dispatched_inbound())
See More Examples - Go to Next Page
Page 1 Selected Page 2