Python twisted.web.server.NOT_DONE_YET Examples

The following are 30 code examples of twisted.web.server.NOT_DONE_YET(). 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 twisted.web.server , or try the search function .
Example #1
Source File: distrib.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET 
Example #2
Source File: test_web.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def render(self, resource):
        """
        Render the given resource as a response to this request.

        This implementation only handles a few of the most common behaviors of
        resources.  It can handle a render method that returns a string or
        C{NOT_DONE_YET}.  It doesn't know anything about the semantics of
        request methods (eg HEAD) nor how to set any particular headers.
        Basically, it's largely broken, but sufficient for some tests at least.
        It should B{not} be expanded to do all the same stuff L{Request} does.
        Instead, L{DummyRequest} should be phased out and L{Request} (or some
        other real code factored in a different way) used.
        """
        result = resource.render(self)
        if result is server.NOT_DONE_YET:
            return
        self.write(result)
        self.finish() 
Example #3
Source File: distrib.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET 
Example #4
Source File: restapi.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def check_for_payment(self, request):
        if not self.protocol.blockchain.connected:
            request.write(json.dumps({"success": False, "reason": "libbitcoin server offline"}, indent=4))
            request.finish()
            return server.NOT_DONE_YET
        try:
            check_order_for_payment(request.args["order_id"][0], self.db,
                                    self.protocol.blockchain,
                                    self.mserver.protocol.get_notification_listener(),
                                    self.protocol.testnet)
            request.write(json.dumps({"success": True}, indent=4))
            request.finish()
            return server.NOT_DONE_YET
        except Exception, e:
            request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
            request.finish()
            return server.NOT_DONE_YET 
Example #5
Source File: restapi.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def migrate(self, request):
        try:
            path = migratev2(self.db)
            request.setHeader('content-disposition', 'filename="listings.csv"')
            request.setHeader('content-type', "text/csv")
            f = open(path)
            while 1:
                d = f.read(2048)
                if not d:
                    break
                request.write(d)
            f.close()
            request.finish()
            return server.NOT_DONE_YET
        except Exception, e:
            request.write(json.dumps({"success": False, "reason": e.message}))
            request.finish()
            return server.NOT_DONE_YET 
Example #6
Source File: test_api_twisted.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_render_POST_queue_messages(self):
        status_worker = Mock()
        status_worker.queueMessage = Mock()
        status_worker.queueMessage.return_value = succeed(None)
        resource = StatusHandlerResource(status_worker)
        message = {
            "event_type": (
                factory.make_name("type") + "/" + factory.make_name("sub_type")
            ),
            "origin": factory.make_name("origin"),
            "name": factory.make_name("name"),
            "description": factory.make_name("description"),
        }
        token = factory.make_name("token")
        request = self.make_request(
            content=json.dumps(message).encode("ascii"), token=token
        )
        output = resource.render_POST(request)
        self.assertEquals(NOT_DONE_YET, output)
        self.assertEquals(204, request.responseCode)
        self.assertThat(
            status_worker.queueMessage, MockCalledOnceWith(token, message)
        ) 
Example #7
Source File: restapi.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def add_social_account(self, request):
        try:
            p = Profile(self.db)
            if "account_type" in request.args and "username" in request.args:
                p.add_social_account(request.args["account_type"][0],
                                     request.args["username"][0],
                                     request.args["proof"][0] if
                                     "proof" in request.args else None)
            else:
                raise Exception("Missing required fields")
            request.write(json.dumps({"success": True}))
            request.finish()
            return server.NOT_DONE_YET
        except Exception, e:
            request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
            request.finish()
            return server.NOT_DONE_YET 
Example #8
Source File: restapi.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def authenticated(func):
        def _authenticate(self, request):
            session = request.getSession()
            if session not in self.authenticated_sessions and "localhost" not in self.authenticated_sessions:
                session.expire()
                request.setResponseCode(401)
                request.write('<html><body><div><span style="color:red">Authorization Error</span></div>'
                              '<h2>Permission Denied</h2></body></html>')
                request.finish()
                return server.NOT_DONE_YET
            else:
                if request.getHeader("Content-Type") == "application/json":
                    request.args = json.loads(request.content.read())
                func(self, request)
                return server.NOT_DONE_YET
        return wraps(func)(_authenticate) 
Example #9
Source File: webservice.py    From scrapy-do with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, request):
        try:
            data = super(JsonResource, self).render(request)
            if data == NOT_DONE_YET:
                return data
            data = {
                **{'status': 'ok'},
                **data
            }
            return self.render_json(request, data)
        except Exception as e:
            request.setResponseCode(400)
            data = {
                'status': 'error',
                'msg': str(e)
            }
            return self.render_json(request, data)


#------------------------------------------------------------------------------- 
Example #10
Source File: test_template.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_simpleRender(self):
        """
        L{renderElement} returns NOT_DONE_YET and eventually
        writes the rendered L{Element} to the request before finishing the
        request.
        """
        element = TestElement()

        d = self.request.notifyFinish()

        def check(_):
            self.assertEqual(
                b"".join(self.request.written),
                b"<!DOCTYPE html>\n"
                b"<p>Hello, world.</p>")
            self.assertTrue(self.request.finished)

        d.addCallback(check)

        self.assertIdentical(NOT_DONE_YET, renderElement(self.request, element))

        return d 
Example #11
Source File: requesthelper.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def render(self, resource):
        """
        Render the given resource as a response to this request.

        This implementation only handles a few of the most common behaviors of
        resources.  It can handle a render method that returns a string or
        C{NOT_DONE_YET}.  It doesn't know anything about the semantics of
        request methods (eg HEAD) nor how to set any particular headers.
        Basically, it's largely broken, but sufficient for some tests at least.
        It should B{not} be expanded to do all the same stuff L{Request} does.
        Instead, L{DummyRequest} should be phased out and L{Request} (or some
        other real code factored in a different way) used.
        """
        result = resource.render(self)
        if result is NOT_DONE_YET:
            return
        self.write(result)
        self.finish() 
Example #12
Source File: test_protocol.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processMessages_calls_loseConnection_if_missing_type_field(self):
        protocol, factory = self.make_protocol()
        protocol.user = maas_factory.make_User()
        mock_loseConnection = self.patch_autospec(protocol, "loseConnection")
        self.patch_autospec(
            protocol, "handleRequest"
        ).return_value = NOT_DONE_YET
        messages = [
            {"request_id": 1},
            {"type": MSG_TYPE.REQUEST, "request_id": 2},
        ]
        protocol.messages = deque(messages)
        self.expectThat([messages[0]], Equals(protocol.processMessages()))
        self.expectThat(
            mock_loseConnection,
            MockCalledOnceWith(
                STATUSES.PROTOCOL_ERROR,
                "Missing type field in the received message.",
            ),
        ) 
Example #13
Source File: distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET 
Example #14
Source File: requesthelper.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def render(self, resource):
        """
        Render the given resource as a response to this request.

        This implementation only handles a few of the most common behaviors of
        resources.  It can handle a render method that returns a string or
        C{NOT_DONE_YET}.  It doesn't know anything about the semantics of
        request methods (eg HEAD) nor how to set any particular headers.
        Basically, it's largely broken, but sufficient for some tests at least.
        It should B{not} be expanded to do all the same stuff L{Request} does.
        Instead, L{DummyRequest} should be phased out and L{Request} (or some
        other real code factored in a different way) used.
        """
        result = resource.render(self)
        if result is NOT_DONE_YET:
            return
        self.write(result)
        self.finish() 
Example #15
Source File: test_template.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_simpleRender(self):
        """
        L{renderElement} returns NOT_DONE_YET and eventually
        writes the rendered L{Element} to the request before finishing the
        request.
        """
        element = TestElement()

        d = self.request.notifyFinish()

        def check(_):
            self.assertEqual(
                b"".join(self.request.written),
                b"<!DOCTYPE html>\n"
                b"<p>Hello, world.</p>")
            self.assertTrue(self.request.finished)

        d.addCallback(check)

        self.assertIdentical(NOT_DONE_YET, renderElement(self.request, element))

        return d 
Example #16
Source File: webservice.py    From scrapy-do with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_POST(self, request):
        @inlineCallbacks
        def do_async():
            try:
                job_id = request.args[b'id'][0].decode('utf-8')
            except KeyError as e:
                result = {
                    'status': 'error',
                    'msg': 'Missing argument: ' + str(e)
                }
                request.setResponseCode(400)
                request.write(self.render_json(request, result))
                request.finish()
                return

            try:
                controller = self.parent.controller

                yield controller.cancel_job(job_id)
                result = {'status': 'ok'}
            except Exception as e:
                request.setResponseCode(400)
                result = {'status': 'error', 'msg': str(e)}

            request.write(self.render_json(request, result))
            request.finish()
        do_async()
        return NOT_DONE_YET


#------------------------------------------------------------------------------- 
Example #17
Source File: TTwisted.py    From thrift with GNU Lesser General Public License v3.0 5 votes vote down vote up
def render_POST(self, request):
        request.content.seek(0, 0)
        data = request.content.read()
        tmi = TTransport.TMemoryBuffer(data)
        tmo = TTransport.TMemoryBuffer()
        iprot = self.inputProtocolFactory.getProtocol(tmi)
        oprot = self.outputProtocolFactory.getProtocol(tmo)
        d = self.processor.process(iprot, oprot)
        d.addCallback(self._cbProcess, request, tmo)
        return server.NOT_DONE_YET

# CEK KONEKSI INI SBENRNYA DISINU 
Example #18
Source File: test_protocol.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dataReceived_calls_processMessages(self):
        protocol, factory = self.make_protocol()
        mock_processMessages = self.patch_autospec(protocol, "processMessages")
        message = {"type": MSG_TYPE.REQUEST}
        self.expectThat(
            protocol.dataReceived(json.dumps(message).encode("ascii")),
            Is(NOT_DONE_YET),
        )
        self.expectThat(mock_processMessages, MockCalledOnceWith()) 
Example #19
Source File: test_protocol.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dataReceived_adds_message_to_queue(self):
        protocol, factory = self.make_protocol()
        self.patch_autospec(protocol, "processMessages")
        message = {"type": MSG_TYPE.REQUEST}
        self.expectThat(
            protocol.dataReceived(json.dumps(message).encode("ascii")),
            Is(NOT_DONE_YET),
        )
        self.expectThat(protocol.messages, Equals(deque([message]))) 
Example #20
Source File: test_websockets.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_renderIProtocol(self):
        """
        If the protocol returned by C{lookupProtocol} isn't a
        C{WebSocketsProtocol}, L{WebSocketsResource} wraps it automatically
        with L{WebSocketsProtocolWrapper}.
        """

        def lookupProtocol(names, otherRequest):
            return AccumulatingProtocol(), None

        self.resource = WebSocketsResource(lookupProtocol)

        request = DummyRequest(b"/")
        request.requestHeaders = Headers(
            {b"user-agent": [b"user-agent"], b"host": [b"host"]}
        )
        transport = StringTransportWithDisconnection()
        transport.protocol = Protocol()
        request.transport = transport
        self.update_headers(
            request,
            headers={
                b"upgrade": b"Websocket",
                b"connection": b"Upgrade",
                b"sec-websocket-key": b"secure",
                b"sec-websocket-version": b"13",
            },
        )
        result = self.resource.render(request)
        self.assertEqual(NOT_DONE_YET, result)
        self.assertIsInstance(transport.protocol, WebSocketsProtocolWrapper)
        self.assertIsInstance(
            transport.protocol.wrappedProtocol, AccumulatingProtocol
        ) 
Example #21
Source File: test_protocol.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_processMessages_process_all_messages_in_the_queue(self):
        protocol, factory = self.make_protocol()
        protocol.user = maas_factory.make_User()
        self.patch_autospec(
            protocol, "handleRequest"
        ).return_value = NOT_DONE_YET
        messages = [
            {"type": MSG_TYPE.REQUEST, "request_id": 1},
            {"type": MSG_TYPE.REQUEST, "request_id": 2},
        ]
        protocol.messages = deque(messages)
        self.assertEqual(messages, protocol.processMessages()) 
Example #22
Source File: monast.py    From monast with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_GET(self, request):
		session = request.getSession()
		session.touch()
		log.debug("HTTP Request from %s:%s (%s) to %s", request.client.host, request.client.port, session.uid, request.uri)

		if not self.sessions.has_key(session.uid):
			log.info("New Client Session: %s" % session.uid)
			session._expireCall.cancel()
			session.sessionTimeout = HTTP_SESSION_TIMEOUT
			session.startCheckingExpiration()
			session.notifyOnExpire(self._expireSession)
			session.updates            = []
			session.isAuthenticated    = not self.monast.authRequired
			session.username           = None
			self.sessions[session.uid] = session
		
		if not session.isAuthenticated and request.path != "/doAuthentication":
			return "ERROR :: Authentication Required"
		
		handler = self.handlers.get(request.path)
		if handler:
			d = task.deferLater(reactor, 0.1, lambda: request)
			d.addCallback(handler)
			d.addErrback(self._onRequestFailure, request)
			return TWebServer.NOT_DONE_YET
		
		return "ERROR :: Request Not Found" 
Example #23
Source File: distrib.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def remote_request(self, request):
        """
        Look up the resource for the given request and render it.
        """
        res = self.site.getResourceFor(request)
        log.msg( request )
        result = res.render(request)
        if result is not server.NOT_DONE_YET:
            request.write(result)
            request.finish()
        return server.NOT_DONE_YET 
Example #24
Source File: distrib.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def finished(self, result):
        if result != server.NOT_DONE_YET:
            assert isinstance(result, types.StringType),\
                   "return value not a string"
            self.request.write(result)
            self.request.finish() 
Example #25
Source File: soap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def render(self, request):
        """Handle a SOAP command."""
        data = request.content.read()

        p, header, body, attrs = SOAPpy.parseSOAPRPC(data, 1, 1, 1)

        methodName, args, kwargs, ns = p._name, p._aslist, p._asdict, p._ns

        # deal with changes in SOAPpy 0.11
        if callable(args):
            args = args()
        if callable(kwargs):
            kwargs = kwargs()

        function = self.lookupFunction(methodName)

        if not function:
            self._methodNotFound(request, methodName)
            return server.NOT_DONE_YET
        else:
            if hasattr(function, "useKeywords"):
                keywords = {}
                for k, v in kwargs.items():
                    keywords[str(k)] = v
                d = defer.maybeDeferred(function, **keywords)
            else:
                d = defer.maybeDeferred(function, *args)

        d.addCallback(self._gotResult, request, methodName)
        d.addErrback(self._gotError, request, methodName)
        return server.NOT_DONE_YET 
Example #26
Source File: wsgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def render(self, request):
        """
        Turn the request into the appropriate C{environ} C{dict} suitable to be
        passed to the WSGI application object and then pass it on.

        The WSGI application object is given almost complete control of the
        rendering process.  C{NOT_DONE_YET} will always be returned in order
        and response completion will be dictated by the application object, as
        will the status, headers, and the response body.
        """
        response = _WSGIResponse(
            self._reactor, self._threadpool, self._application, request)
        response.start()
        return NOT_DONE_YET 
Example #27
Source File: util.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _cbChild(self, child, request):
        result = resource.getChildForRequest(child, request).render(request)
        from twisted.web.server import NOT_DONE_YET
        if result == NOT_DONE_YET:
            return
        else:
            request.write(result)
            request.finish() 
Example #28
Source File: webservice.py    From scrapy-do with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_POST(self, request):
        @inlineCallbacks
        def do_async():
            try:
                data = request.args[b'archive'][0]
            except KeyError as e:
                result = {
                    'status': 'error',
                    'msg': 'Missing argument: ' + str(e)
                }
                request.setResponseCode(400)
                request.write(self.render_json(request, result))
                request.finish()
                return

            try:
                controller = self.parent.controller

                project = yield controller.push_project(data)
                result = {
                    'status': 'ok',
                    'name': project.name,
                    'spiders': project.spiders
                }
            except Exception as e:
                request.setResponseCode(400)
                result = {'status': 'error', 'msg': str(e)}

            request.write(self.render_json(request, result))
            request.finish()
        do_async()
        return NOT_DONE_YET


#------------------------------------------------------------------------------- 
Example #29
Source File: TTwisted.py    From SOLO with GNU General Public License v3.0 5 votes vote down vote up
def render_POST(self, request):
        request.content.seek(0, 0)
        data = request.content.read()
        tmi = TTransport.TMemoryBuffer(data)
        tmo = TTransport.TMemoryBuffer()
        iprot = self.inputProtocolFactory.getProtocol(tmi)
        oprot = self.outputProtocolFactory.getProtocol(tmo)
        d = self.processor.process(iprot, oprot)
        d.addCallback(self._cbProcess, request, tmo)
        return server.NOT_DONE_YET

# CEK KONEKSI INI SBENRNYA DISINU 
Example #30
Source File: http.py    From sygnal with Apache License 2.0 5 votes vote down vote up
def render_POST(self, request):
        response = self._handle_request(request)
        if response != NOT_DONE_YET:
            PUSHGATEWAY_HTTP_RESPONSES_COUNTER.labels(code=request.code).inc()
        return response