twisted.web.error.Error

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

55 Examples 7

Page 1 Selected Page 2

Example 1

Project: filesync-server Source File: test_basic.py
    @defer.inlineCallbacks
    def test_status_not_found(self):
        """Test the OK status response."""
        status = self.site.resource.children['status']
        # override user_id with a non-existing user
        status.user_id = sys.maxint
        try:
            yield client.getPage(self.url + "/foo")
        except error.Error, e:
            self.assertEquals('404', e.status)
        else:
            self.fail('An error is expected.')

Example 2

Project: pyamf Source File: test_twisted.py
Function: test_bad_content
    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 3

Project: Piped Source File: test_processors.py
        @defer.inlineCallbacks
        def statustest_web_server_without_pb(self):
            """ If the pb server is stopped, the web server should return an error status. """

            # stop the perspective broker server for the duration of this test:
            self.pb_server.stopService()
            self.addCleanup(self.pb_server.startService)

            try:
                yield client.getPage('http://localhost:8080')
                self.fail('Expected an error to be raised.')
            except error.Error as e:
                self.assertEquals(e.status, '500')

                # since we've turned on debugging for localhost, we should get a traceback:
                self.assertIn('web.Server Traceback', e.response)

Example 4

Project: flumotion Source File: test_component_httpserver.py
    def testDirMountOnDemand(self):
        properties = {
            u'mount-point': '/ondemand',
            u'path': self.path,
            u'port': 0,
        }
        self.makeComponent(properties)

        d = client.getPage(self.getURL('/ondemand/A'))
        d.addCallback(lambda r: self.assertEquals(r, 'test file A'))
        d2 = client.getPage(self.getURL('/ondemand/B/C'))
        d2.addCallback(lambda r: self.assertEquals(r, 'test file C'))
        # getting a non-existing resource should give web.error.Error
        d3 = client.getPage(self.getURL('/A'))
        d3.addErrback(lambda f: f.trap(error.Error))
        d4 = client.getPage(self.getURL('/ondemand/B/D'))
        d4.addErrback(lambda f: f.trap(error.Error))

        return defer.DeferredList([d, d2, d3, d4], fireOnOneErrback=True)

Example 5

Project: scrapyrt Source File: test_resource_serviceresource.py
    def test_format_error_response(self):
        code = 400
        self.request.code = code
        exc = Error(str(code), 'blah')
        response = self.resource.format_error_response(exc, self.request)
        self.assertEqual(response['status'], 'error')
        self.assertEqual(response['message'], exc.message)
        self.assertEqual(response['code'], code)

Example 6

Project: idavoll Source File: test_gateway.py
    def test_subscribeNonExisting(self):
        def cb(err):
            self.assertEqual('403', err.status)

        d = self.client.subscribe('xmpp:%s?node=test' % component)
        self.assertFailure(d, error.Error)
        d.addCallback(cb)
        return d

Example 7

Project: pyamf Source File: test_twisted.py
Function: test_invalid_method
    def test_invalid_method(self):
        """
        A classic GET on the xml server should return a NOT_ALLOWED.
        """
        d = self.getPage(method='GET')
        d = self.assertFailure(d, error.Error)
        d.addCallback(
            lambda exc: self.assertEqual(int(exc.args[0]), http.NOT_ALLOWED))

        return d

Example 8

Project: idavoll Source File: test_gateway.py
    def test_unsubscribeNonExisting(self):
        def cb(err):
            self.assertEqual('403', err.status)

        d = self.client.unsubscribe('xmpp:%s?node=test' % component)
        self.assertFailure(d, error.Error)
        d.addCallback(cb)
        return d

Example 9

Project: Python-RTSP Source File: rtsp.py
Function: handle_status
    def handleStatus(self, version, status, message):
        """ Called when the status header is received """
        if status == '404':
            self.transport.loseConnection()
            self.factory.error(failure.Failure(error.Error(http.NOT_FOUND)))
            return
        length = len(version) + len(status) + len(message)
        if length > 50:
            self.transport.loseConnection()
            self.factory.error(
                failure.Failure(
                    RTSPStatusError(
                        'Length of status message was too long: %s' % length,
                        version)))
            return
        print('Status: %s %s %s' % (status,message,version))

Example 10

Project: airpnp Source File: test_device_builder.py
    def test_build_device_error_with_missing_service(self, pageMock):
        def fetch(*args, **kw):
            def fetch2(*args, **kw):
                # second time: 404 Not Found
                return defer.fail(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
            pageMock.side_effect = fetch2
            # first time: return docuement
            return defer.succeed(readall('ms.xml'))
        pageMock.side_effect = fetch
        builder = DeviceBuilder(Mock(), lambda x: (True, None))
        actual = builder.build('')
        err = [None]
        actual.addErrback(lambda x: err.__setitem__(0, x))

        self.assertEqual(err[0].type, error.Error)

Example 11

Project: flumotion Source File: test_component_httpserver.py
    def testDirMountEmpty(self):
        properties = {
            u'mount-point': '',
            u'path': self.path,
            u'port': 0,
        }
        self.makeComponent(properties)

        d = client.getPage(self.getURL('/A'))
        d.addCallback(lambda r: self.assertEquals(r, 'test file A'))

        d2 = client.getPage(self.getURL('/B/C'))
        d2.addCallback(lambda r: self.assertEquals(r, 'test file C'))

        # getting a non-existing resource should give web.error.Error
        d3 = client.getPage(self.getURL('/B/D'))
        d3.addErrback(lambda f: f.trap(error.Error))
        return defer.DeferredList([d, d2, d3], fireOnOneErrback=True)

Example 12

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 13

Project: airpnp Source File: test_device_builder.py
    def test_failure_from_builder_contains_url_when_service_fetching_fails(self, pageMock):
        def fetch(*args, **kw):
            def fetch2(*args, **kw):
                # second time: 404 Not Found
                return defer.fail(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
            pageMock.side_effect = fetch2
            # first time: return docuement
            return defer.succeed(readall('ms.xml'))
        pageMock.side_effect = fetch
        builder = DeviceBuilder(Mock(), lambda x: (True, None))
        actual = builder.build('http://www.dummy.com')

        err = [None]
        actual.addErrback(lambda x: err.__setitem__(0, x))

        self.assertEqual(err[0].url, 'http://www.dummy.com/cds.xml')

Example 14

Project: flumotion Source File: test_component_httpserver.py
    def testCortadoResourceNotFound(self):
        properties = {
            u'mount-point': '/m/c/',
            u'port': 0,
        }

        plugs = self._cortadoPlug()
        self._makeComponent(properties, plugs)

        def errorNotFound(failure):
            failure.trap(error.Error)

        d = client.getPage(self._getURL('/m/c/bar.html'))
        d.addErrback(errorNotFound)
        return d

Example 15

Project: filesync-server Source File: test_basic.py
Function: test_status_error
    @defer.inlineCallbacks
    def test_status_ERROR(self):
        """Test the OK status response."""
        status = self.site.resource.children['status']
        # override user_id with a non-existing user
        status.user_id = sys.maxint
        try:
            yield client.getPage(self.url)
        except error.Error, e:
            self.assertEquals('500', e.status)
        else:
            self.fail('An error is expected.')

Example 16

Project: Tickery Source File: create-twitter-namespaces-and-tags.py
def ignorePreexistingErrror(failure, msg):
    failure.trap(error.Error)
    if int(failure.value.status) == http.PRECONDITION_FAILED:
        print 'Ignoring precondition error (encountered in %r)' % (msg,)
    else:
        return failure

Example 17

Project: scrapyrt Source File: core.py
Function: crawl
    def crawl(self, *args, **kwargs):
        self.crawler_process = ScrapyrtCrawlerProcess(
            self.get_project_settings(), self)
        try:
            dfd = self.crawler_process.crawl(self.spider_name, *args, **kwargs)
        except KeyError as e:
            # Spider not found.
            raise Error('404', message=e.message)
        dfd.addCallback(self.return_items)
        return dfd

Example 18

Project: airpnp Source File: test_util.py
    def test_unrecognized_error_is_reraised(self, pageMock):
        # Setup mock
        f = failure.Failure(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
        pageMock.return_value = defer.fail(f)

        # Given
        msg = SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1', 'GetCurrentConnectionIDs')

        # When
        d = send_soap_message_deferred('http://www.dummy.com', msg)

        # Then
        f = d.result
        self.assertTrue(f.check(error.Error))

Example 19

Project: idavoll Source File: test_gateway.py
    def test_publishNonExisting(self):
        def cb(err):
            self.assertEqual('404', err.status)

        d = self.client.publish(TEST_ENTRY, 'xmpp:%s?node=test' % component)
        self.assertFailure(d, error.Error)
        d.addCallback(cb)
        return d

Example 20

Project: SubliminalCollaborator Source File: test_soap.py
Function: test_method_not_found
    def testMethodNotFound(self):
        """
        Check that a non existing method return error 500.
        """
        d = self.proxy().callRemote('doesntexist')
        self.assertFailure(d, error.Error)
        def cb(err):
            self.assertEqual(int(err.status), 500)
        d.addCallback(cb)
        return d

Example 21

Project: SubliminalCollaborator Source File: test_error.py
    def test_messageExists(self):
        """
        If a C{message} argument is passed to the L{Error} constructor, the
        C{message} isn't affected by the value of C{status}.
        """
        e = error.Error("200", "My own message")
        self.assertEqual(e.message, "My own message")

Example 22

Project: scrapyrt Source File: test_resource_serviceresource.py
    def test_error_403(self, log_msg_mock):
        exc = Error('403', 'blah_403')
        result = self.resource.handle_error(exc, self.request)
        self.assertEqual(self.request.code, 403)
        self.assertFalse(log_msg_mock.called)
        self.assertEqual(result['message'], exc.message)

Example 23

Project: SubliminalCollaborator Source File: test_error.py
    def test_noMessageInvalidStatus(self):
        """
        If no C{message} argument is passed to the L{Error} constructor and
        C{code} isn't a valid HTTP status code, C{message} stays C{None}.
        """
        e = error.Error("InvalidCode")
        self.assertEqual(e.message, None)

Example 24

Project: wolverine Source File: pubsub.py
@defer.inlineCallbacks
def publish(url):
    subscribers = subscriptions.get(url, None)
    if len(subscribers):
        print "Fetching %s for %s subscribers" % (url, len(subscribers))
        try:
            page = yield client.getPage(url, headers={'X-Hub-Subscribers': len(subscribers)})
            for subscriber in subscribers:
                post_and_retry(subscriber, page, content_type='application/atom+xml')
        except error.Error, e:
            print e

Example 25

Project: scrapyrt Source File: test_resource_serviceresource.py
    def test_error_400(self, log_msg_mock):
        exc = Error('400', 'blah_400')
        result = self.resource.handle_error(exc, self.request)
        self.assertEqual(self.request.code, 400)
        self.assertFalse(log_msg_mock.called)
        self.assertEqual(result['message'], exc.message)

Example 26

Project: airpnp Source File: device_discovery.py
    def _device_error(self, fail, udn):
        """Handle error that occurred when building a device."""
        if not fail.check(defer.CancelledError):
            del self._builders[udn]
            if fail.check(DeviceRejectedError):
                device = fail.value.device
                log.msg('Adding device %s to ignore list, because %s' %
                        (device, fail.getErrorMessage()), ll=2)
                self._ignored.append(udn)
            elif fail.check(error.Error):
                if hasattr(fail, 'url'):
                    msg = "%s when fetching %s" % (str(fail.value), fail.url)
                else:
                    msg = str(fail.value)
                log.msg('Adding UDN %s to ignore list, because %s' % (udn, msg), ll=2)
                self._ignored.append(udn)
            else:
                log.err(fail, "Failed to build Device with UDN %s" % (udn, ))

Example 27

Project: deblaze Source File: test_twisted.py
Function: test_invalid_method
    def test_invalid_method(self):
        """
        A classic GET on the xml server should return a NOT_ALLOWED.
        """
        d = client.getPage("http://127.0.0.1:%d/" % (self.port,))
        d = self.assertFailure(d, error.Error)
        d.addCallback(
            lambda exc: self.assertEquals(int(exc.args[0]), http.NOT_ALLOWED))

        return d

Example 28

Project: p2pool-n Source File: soap.py
Function: got_error
    def _got_error(self, res):
        """
        The HTTP POST command did not succeed, depending on the error type:
            - it's a SOAP error, we parse it and return a L{SoapError}.
            - it's another type of error (http, other), we raise it as is
        """
        logging.debug("SOAP Error:\n%s", res)
        
        if isinstance(res.value, error.Error):
            try:
                logging.debug("SOAP Error content:\n%s", res.value.response)
                raise SoapError(SOAPpy.parseSOAPRPC(res.value.response)["detail"])
            except:
                raise
        raise Exception(res.value)

Example 29

Project: flumotion Source File: test_component_httpserver.py
    def testDirMountRoot(self):
        properties = {
            u'mount-point': '/',
            u'path': self.path,
            u'port': 0,
        }
        self.makeComponent(properties)

        d = client.getPage(self.getURL('/A'))
        d.addCallback(lambda r: self.assertEquals(r, 'test file A'))

        d2 = client.getPage(self.getURL('/B/C'))
        d2.addCallback(lambda r: self.assertEquals(r, 'test file C'))

        # getting a non-existing resource should give web.error.Error
        d3 = client.getPage(self.getURL('/B/D'))
        d3.addErrback(lambda f: f.trap(error.Error))

        return defer.DeferredList([d, d2, d3], fireOnOneErrback=True)

Example 30

Project: airpnp Source File: test_util.py
    def test_soap_error_on_500_response(self, pageMock):
        # Setup mock
        f = failure.Failure(error.Error(http.INTERNAL_SERVER_ERROR, 'Internal Error', 
                                        SoapError(501, 'Action Failed').tostring()))
        pageMock.return_value = defer.fail(f)

        # Given
        msg = SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1', 'GetCurrentConnectionIDs')

        # When
        d = send_soap_message_deferred('http://www.dummy.com', msg)

        # Then
        response = d.result
        self.assertEqual(response.__class__, SoapError)
        self.assertEqual(response.code, '501')

Example 31

Project: flumotion Source File: test_component_httpserver.py
    def testFileMountOnDemand(self):
        properties = {
            u'mount-point': '/ondemand',
            u'path': os.path.join(self.path, 'A'),
            u'port': 0,
        }
        self.makeComponent(properties)

        d1 = client.getPage(self.getURL('/ondemand'))
        d1.addCallback(lambda r: self.assertEquals(r, 'test file A'))
        # getting a non-existing resource should give web.error.Error
        d2 = client.getPage(self.getURL('/A'))
        d2.addErrback(lambda f: f.trap(error.Error))
        d3 = client.getPage(self.getURL('/ondemand/B/D'))
        d3.addErrback(lambda f: f.trap(error.Error))
        return defer.DeferredList([d1, d2, d3], fireOnOneErrback=True)

Example 32

Project: SubliminalCollaborator Source File: test_error.py
Function: test_nomessagevalidstatus
    def test_noMessageValidStatus(self):
        """
        If no C{message} argument is passed to the L{Error} constructor and the
        C{code} argument is a valid HTTP status code, C{code} is mapped to a
        descriptive string to which C{message} is assigned.
        """
        e = error.Error("200")
        self.assertEqual(e.message, "OK")

Example 33

Project: SubliminalCollaborator Source File: test_xmlrpc.py
    def test_errorGet(self):
        """
        A classic GET on the xml server should return a NOT_ALLOWED.
        """
        d = client.getPage("http://127.0.0.1:%d/" % (self.port,))
        d = self.assertFailure(d, error.Error)
        d.addCallback(
            lambda exc: self.assertEqual(int(exc.args[0]), http.NOT_ALLOWED))
        return d

Example 34

Project: airpnp Source File: test_device_builder.py
    def test_failure_from_builder_contains_url(self, pageMock):
        pageMock.return_value = defer.fail(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
        builder = DeviceBuilder(Mock(), lambda x: (True, None))
        actual = builder.build('http://www.dummy.com')

        err = [None]
        actual.addErrback(lambda x: err.__setitem__(0, x))

        self.assertEqual(err[0].url, 'http://www.dummy.com')

Example 35

Project: deblaze Source File: test_twisted.py
Function: test_bad_content
    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: idavoll Source File: gateway.py
Function: render_post
    @_asyncResponse
    def render_POST(self, request):
        def trapNotFound(failure):
            err = failure.trap(*self.errorMap.keys())
            status, message = self.errorMap[err]
            raise Error(status, message)

        def toResponse(result):
            request.setResponseCode(http.NO_CONTENT)
            return b''

        def trapXMPPURIParseError(failure):
            failure.trap(XMPPURIParseError)
            raise Error(http.BAD_REQUEST,
                        "Malformed XMPP URI: %s" % failure.value)

        data = request.content.read()
        self.params = simplejson.loads(data)

        uri = self.params['uri']
        callback = self.params['callback']

        jid, nodeIdentifier = getServiceAndNode(uri)
        method = getattr(self.service, self.serviceMethod)
        d = method(jid, nodeIdentifier, callback)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        d.addErrback(trapXMPPURIParseError)
        return d

Example 37

Project: deblaze Source File: test_twisted.py
Function: test_encoding_error
    def test_encoding_error(self):
        encode = _twisted.remoting.encode

        def force_error(amf_request, context=None):
            raise pyamf.EncodeError

        def echo(request, data):
            return data

        self.gw.addService(echo)

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        d = client.getPage("http://127.0.0.1:%d/" % (self.port,),
                method="POST", postdata=remoting.encode(env).getvalue())

        _twisted.remoting.encode = force_error
        def switch(x):
            _twisted.remoting.encode = encode

        d = self.assertFailure(d, error.Error)

        def check(exc):
            self.assertEquals(int(exc.args[0]), http.INTERNAL_SERVER_ERROR)
            self.assertTrue(exc.args[1].startswith('500 Internal Server Error'))

        d.addCallback(check)

        return d.addBoth(switch)

Example 38

Project: idavoll Source File: gateway.py
Function: render_get
    @_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 39

Project: scrapyrt Source File: core.py
    def create_spider_request(self, kwargs):
        url = kwargs.pop('url')
        try:
            req = Request(url, **kwargs)
        except (TypeError, ValueError) as e:
            # Bad arguments for scrapy Request
            # we don't want to schedule spider if someone
            # passes meaingless arguments to Request.
            # We must raise this here so that this will be returned to client,
            # Otherwise if this is raised in spider_idle it goes to
            # spider logs where it does not really belong.
            # It is needed because in POST handler we can pass
            # all possible requests kwargs, so it is easy to make mistakes.
            message = "Error while creating Request, {}".format(e.message)
            raise Error('400', message=message)

        req.dont_filter = True
        msg = u"Created request for spider {} with url {} and kwargs {}"
        msg = msg.format(self.spider_name, url, repr(kwargs))
        log.msg(msg)
        return req

Example 40

Project: wolverine Source File: pubsub.py
@defer.inlineCallbacks
def post_and_retry(url, data, retry=0, content_type='application/x-www-form-urlencoded'):
    if type(data) is dict:
        print "Posting [%s] to %s with %s" % (retry, url, data)
        data = urllib.urlencode(data)
    else:
        print "Posting [%s] to %s with %s bytes of postdata" % (retry, url, len(data))
    headers = {
        'Content-Type': content_type,
        'Content-Length': str(len(data)),
    }
    try:    
        page = yield client.getPage(url, method='POST' if len(data) else 'GET', headers=headers, postdata=data if len(data) else None)
    except error.Error, e:
        if e.status in ['301', '302', '303']:
            return # Not really a fail
        print e
        if retry < RETRIES:
            retry += 1
            reactor.callLater(retry * DELAY_MULTIPLIER, post_and_retry, url, data, retry, content_type)

Example 41

Project: airpnp Source File: util.py
def send_soap_message_deferred(url, msg, mpost=False, deferred=None):
    """
    Send a SOAP message to the given URL.
    
    The HTTP headers mandated by the UPnP specification are added. Also, if
    posting fails with a 405 error, another attempt is made with slightly
    different headers and method set to M-POST.

    Return a Deferred, whose callback will be called with a SoapMessage or a
    SoapError, depending on the outcome.

    """
    def handle_error(fail):
        if fail.check(error.Error):
            err = fail.value
            status = int(err.status)
            if not mpost and status == http.NOT_ALLOWED:
                # new attempt
                # don't pass the deferred here, because we're already
                # within the callback/errback chain
                return send_soap_message_deferred(url, msg, mpost=True)
            elif status == http.INTERNAL_SERVER_ERROR:
                # return to the callback chain
                return SoapError.parse(err.response)
        log.err(fail, "Failed to send SOAP message to %s" % (url, ))
        fail.raiseException()

    # setup request headers
    headers = {}
    headers['Content-Type'] = 'text/xml; charset="utf-8"'
    if mpost:
        headers['Man'] = '"http://schemas.xmlsoap.org/soap/envelope/"; ns=01'
        headers['01-Soapaction'] = msg.get_header()
    else:
        headers['Soapaction'] = msg.get_header()

    # prepare the post data
    data = msg.tostring().encode("utf-8")

    # select method
    method = 'POST' if not mpost else 'M-POST'

    # initiate the request and add initial handlers
    if deferred:
        def tourl(value):
            return url
        # the deferred is an initiator, so we don't care about
        # its result
        d = deferred
        d.addCallback(tourl)
        d.addCallback(client.getPage, method=method, headers=headers,
                      postdata=data, agent='OS/1.0 UPnP/1.0 airpnp/1.0')
    else:
        d = client.getPage(url, method=method, headers=headers, postdata=data,
                           agent='OS/1.0 UPnP/1.0 airpnp/1.0')
    d.addCallback(StringIO)
    d.addCallback(SoapMessage.parse)
    d.addErrback(handle_error)
    return d

Example 42

Project: airpnp Source File: test_util.py
Function: test_fallback_to_mpost
    def test_fallback_to_mpost(self, pageMock):
        # Setup mock
        def side_effect(*args, **kwargs):
            def second_call(*args, **kwargs):
                return defer.succeed(SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1',
                                                 'GetCurrentConnectionIDsResponse').tostring())
            pageMock.side_effect = second_call
            f = failure.Failure(error.Error(http.NOT_ALLOWED, 'Method Not Allowed',
                                            'Method Not Allowed'))
            return defer.fail(f)
        pageMock.side_effect = side_effect

        # Given
        msg = SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1', 'GetCurrentConnectionIDs')

        # When
        send_soap_message_deferred('http://www.dummy.com', msg)

        # Then
        headers = pageMock.call_args[1]['headers']
        self.assertEqual(headers['Man'],
                         '"http://schemas.xmlsoap.org/soap/envelope/"; ns=01')
        self.assertEqual(headers['01-Soapaction'],
                         '"urn:schemas-upnp-org:service:ConnectionManager:1#GetCurrentConnectionIDs"')

Example 43

Project: scrapyrt Source File: resources.py
Function: render_post
    def render_POST(self, request, **kwargs):
        """
        :param request:
            body should contain JSON

        Required keys in JSON posted:

        :spider_name: string
            name of spider to be scheduled.

        :request: json object
            request to be scheduled with spider.
            Note: request must contain url for spider.
            It may contain kwargs to scrapy request.

        """
        request_body = request.content.getvalue()
        try:
            request_data = demjson.decode(request_body)
        except ValueError as e:
            message = "Invalid JSON in POST body. {}"
            message.format(e.pretty_description())
            raise Error('400', message=message)

        log.msg("{}".format(request_data))
        spider_data = self.get_required_argument(request_data, "request")
        error_msg = "Missing required key 'url' in 'request' object"
        self.get_required_argument(spider_data, "url", error_msg=error_msg)

        return self.prepare_crawl(request_data, spider_data, **kwargs)

Example 44

Project: idavoll Source File: gateway.py
def _asyncResponse(render):
    """
    """
    def wrapped(self, request):
        def eb(failure):
            if failure.check(Error):
                err = failure.value
            else:
                log.err(failure)
                err = Error(500)
            request.setResponseCode(err.status, err.message)
            return err.response

        def finish(result):
            if result is server.NOT_DONE_YET:
                return

            if result:
                request.write(result)
            request.finish()

        d = defer.maybeDeferred(render, self, request)
        d.addErrback(eb)
        d.addCallback(finish)

        return server.NOT_DONE_YET

    return wrapped

Example 45

Project: scrapyrt Source File: resources.py
    def get_required_argument(self, request_data, name, error_msg=None):
        """Get required API key from dict-like object.

        :param dict request_data:
            dictionary with names and values of parameters supplied to API.
        :param str name:
            required key that must be found in request_data
        :return: value of required param
        :raises Error: Bad Request response

        """
        if error_msg is None:
            error_msg = 'Missing required parameter: {}'.format(repr(name))
        try:
            value = request_data[name]
        except KeyError:
            raise Error('400', message=error_msg)
        if not value:
            raise Error('400', message=error_msg)
        return value

Example 46

Project: idavoll Source File: gateway.py
Function: render_post
    @_asyncResponse
    def render_POST(self, request):
        """
        Respond to a POST request to create a new node.
        """
        def toResponse(result):
            request.setResponseCode(http.NO_CONTENT)

        def trapNotFound(failure):
            failure.trap(error.NodeNotFound)
            raise Error(http.NOT_FOUND, "Node not found")

        if not request.args.get('uri'):
            raise Error(http.BAD_REQUEST, "No URI given")

        try:
            jid, nodeIdentifier = getServiceAndNode(request.args['uri'][0])
        except XMPPURIParseError, e:
            raise Error(http.BAD_REQUEST, "Malformed XMPP URI: %s" % e)


        data = request.content.read()
        if data:
            params = simplejson.loads(data)
            redirectURI = params.get('redirect_uri', None)
        else:
            redirectURI = None

        d = self.backend.deleteNode(nodeIdentifier, self.owner,
                                    redirectURI)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        return d

Example 47

Project: DrEval Source File: __init__.py
def Bigglesworth(*args, **kw_args):
    """
    This is basically the DrEval test framework/DSL
    """
    def wrap(f):
        @defer.inlineCallbacks
        def wrapped_f(self):
            yield doctoreval.start(*args, **kw_args)
            try:
                self.url = 'http://%s:%s' % (web.port.getHost().host, web.port.getHost().port)
                test = f(self)
                try:
                    resp = yield request(test)
                    self.assertEqual(resp, test.get('result'))
                except error.Error, e:
                    self.assertEqual(str(e), test['error'])
            finally:
                yield doctoreval.stop()
        return wrapped_f
    return wrap

Example 48

Project: quarry Source File: http.py
def request(url, timeout, err_type=Exception, expect_content=False, data=None):
    d0 = defer.Deferred()

    def _callback(data):
        d0.callback(json.loads(data.decode('ascii')))

    def _errback(err):
        if isinstance(err.value, error.Error):
            if err.value.status == b"204":
                if expect_content:
                    err = failure.Failure(err_type(
                        "No Content",
                        "No content was returned by the server"))
                else:
                    d0.callback(None)
                    return
            else:
                data = json.loads(err.value.response.decode('ascii'))
                err = failure.Failure(err_type(
                    data['error'],
                    data['errorMessage']))
        d0.errback(err)

    if data:
        d1 = client.getPage(
            url,
            headers = {b'Content-Type': b'application/json'},
            method = b'POST',
            postdata = json.dumps(data).encode('ascii'))
    else:
        d1 = client.getPage(url)
    d1.addCallbacks(_callback, _errback)

    return d0

Example 49

Project: downpour Source File: __init__.py
Function: init
    def __init__(self, reason):
        error.Error(self, reason)
        self.reason = reason

Example 50

Project: idavoll Source File: gateway.py
    @_asyncResponse
    def render_POST(self, request):
        """
        Respond to a POST request to create a new item.
        """

        def toResponse(nodeIdentifier):
            uri = getXMPPURI(self.serviceJID, nodeIdentifier)
            body = simplejson.dumps({'uri': uri})
            request.setHeader(b'Content-Type', MIME_JSON)
            return body

        def gotNode(nodeIdentifier, payload):
            item = Item(id='current', payload=payload)
            d = self.backend.publish(nodeIdentifier, [item], self.owner)
            d.addCallback(lambda _: nodeIdentifier)
            return d

        def getNode():
            if request.args.get('uri'):
                jid, nodeIdentifier = getServiceAndNode(request.args['uri'][0])
                return defer.succeed(nodeIdentifier)
            else:
                return self.backend.createNode(None, self.owner)

        def trapNotFound(failure):
            failure.trap(error.NodeNotFound)
            raise Error(http.NOT_FOUND, "Node not found")

        def trapXMPPURIParseError(failure):
            failure.trap(XMPPURIParseError)
            raise Error(http.BAD_REQUEST,
                        "Malformed XMPP URI: %s" % failure.value)

        self.checkMediaType(request)
        payload = parseXml(request.content.read())
        d = getNode()
        d.addCallback(gotNode, payload)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        d.addErrback(trapXMPPURIParseError)
        return d
See More Examples - Go to Next Page
Page 1 Selected Page 2