twisted.web.server.NOT_DONE_YET

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

50 Examples 7

3 Source : TTwisted.py
with GNU General Public License v3.0
from AbiPutrallg

    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

3 Source : distrib.py
with MIT License
from autofelix

    def finished(self, result):
        if result is not server.NOT_DONE_YET:
            assert isinstance(result, str), "return value not a string"
            self.request.write(result)
            self.request.finish()

    def failed(self, failure):

3 Source : distrib.py
with MIT License
from autofelix

    def remote_request(self, request):
        """
        Look up the resource for the given request and render it.
        """
        res = self.site.getResourceFor(request)
        self._log.info(request)
        result = res.render(request)
        if result is not server.NOT_DONE_YET:
            request.write(result)
            request.finish()
        return server.NOT_DONE_YET



class UserDirectory(resource.Resource):

3 Source : test_distrib.py
with MIT License
from autofelix

    def test_largeWrite(self):
        """
        If a string longer than the Banana size limit is passed to the
        L{distrib.Request} passed to the remote resource, it is broken into
        smaller strings to be transported over the PB connection.
        """
        class LargeWrite(resource.Resource):
            def render(self, request):
                request.write(b'x' * SIZE_LIMIT + b'y')
                request.finish()
                return server.NOT_DONE_YET

        request = self._requestTest(LargeWrite())
        request.addCallback(self.assertEqual, b'x' * SIZE_LIMIT + b'y')
        return request


    def test_largeReturn(self):

3 Source : test_web.py
with MIT License
from autofelix

    def render(self, request):
        """
        Leave the request open for future writes.
        """
        self.request = request
        if request.method not in self.allowedMethods:
            raise error.UnsupportedMethod(self.allowedMethods)
        self.request.write(b"some data")
        return server.NOT_DONE_YET



class NewRenderTests(unittest.TestCase):

3 Source : test_webclient.py
with MIT License
from autofelix

    def render(self, request):
        if self._write:
            request.write(b'some bytes')
        return server.NOT_DONE_YET


class ForeverTakingNoReadingResource(resource.Resource):

3 Source : test_webclient.py
with MIT License
from autofelix

    def render(self, request):
        # Stop the producing.
        request.transport.pauseProducing()
        return server.NOT_DONE_YET


class CookieMirrorResource(resource.Resource):

3 Source : test_webclient.py
with MIT License
from autofelix

    def render(self, request):
        def response():
            request.write(b'some bytes')
            request.finish()
        reactor.callLater(self.seconds, response)
        return server.NOT_DONE_YET


class BrokenDownloadResource(resource.Resource):

3 Source : _util.py
with MIT License
from autofelix

def _render(resource, request):
    result = resource.render(request)
    if isinstance(result, bytes):
        request.write(result)
        request.finish()
        return succeed(None)
    elif result is server.NOT_DONE_YET:
        if request.finished:
            return succeed(None)
        else:
            return request.notifyFinish()
    else:
        raise ValueError("Unexpected return value: %r" % (result,))



class FlattenTestCase(TestCase):

3 Source : deferred_resource.py
with GNU General Public License v3.0
from AXErunners

    def render(self, request):
        def finish(x):
            if request.channel is None: # disconnected
                return
            if x is not None:
                request.write(x)
            request.finish()
        
        def finish_error(fail):
            if request.channel is None: # disconnected
                return
            request.setResponseCode(500) # won't do anything if already written to
            request.write('---ERROR---')
            request.finish()
            log.err(fail, "Error in DeferredResource handler:")
        
        defer.maybeDeferred(resource.Resource.render, self, request).addCallbacks(finish, finish_error)
        return server.NOT_DONE_YET

3 Source : snippet.py
with Apache License 2.0
from dockerizeme

    def render_GET(self, request):
        request.write('  <  b>%s < /b> < br>' % (time.ctime(),))
        self.presence.append(request)
        return server.NOT_DONE_YET

    def __print_time(self):

3 Source : distrib.py
with The Unlicense
from dspray95

    def finished(self, result):
        if result != server.NOT_DONE_YET:
            assert isinstance(result, str), "return value not a string"
            self.request.write(result)
            self.request.finish()

    def failed(self, failure):

3 Source : TTwisted.py
with GNU General Public License v3.0
from Dzulkiflibot

    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

3 Source : resource.py
with MIT License
from fbla-competitive-events

    def render_GET(self, request):
        request.redirect(self._redirect_url)
        request.finish()
        return server.NOT_DONE_YET


class StaticResource(File):

3 Source : distrib.py
with MIT License
from fbla-competitive-events

    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



class UserDirectory(resource.Resource):

3 Source : test_distrib.py
with MIT License
from fbla-competitive-events

    def test_largeWrite(self):
        """
        If a string longer than the Banana size limit is passed to the
        L{distrib.Request} passed to the remote resource, it is broken into
        smaller strings to be transported over the PB connection.
        """
        class LargeWrite(resource.Resource):
            def render(self, request):
                request.write('x' * SIZE_LIMIT + 'y')
                request.finish()
                return server.NOT_DONE_YET

        request = self._requestTest(LargeWrite())
        request.addCallback(self.assertEqual, 'x' * SIZE_LIMIT + 'y')
        return request


    def test_largeReturn(self):

3 Source : txipc.py
with Apache License 2.0
from gethue

  def render_POST(self, request):
    # Unfortunately, Twisted.web doesn't support incoming
    # streamed input yet, the whole payload must be kept in-memory
    request.content.seek(0, 0)
    call_request_reader = ipc.FramedReader(request.content)
    call_request = call_request_reader.read_framed_message()
    d = maybeDeferred(self.responder.respond, call_request)
    d.addCallback(self.cb_render_POST, request)
    return server.NOT_DONE_YET

3 Source : api_util.py
with Apache License 2.0
from HathorNetwork

def render_options(request: Request, verbs: str = 'GET, POST, OPTIONS') -> int:
    """Function to return OPTIONS request.

    Most of the APIs only need it for GET, POST and OPTIONS, but verbs can be passed as parameter.

    :param verbs: verbs to reply on render options
    :type verbs: str
    """
    from twisted.web import server
    set_cors(request, verbs)
    request.setHeader(b'content-type', b'application/json; charset=utf-8')
    request.write(b'')
    request.finish()
    return server.NOT_DONE_YET


def get_missing_params_msg(param_name):

3 Source : base_resource.py
with Apache License 2.0
from HathorNetwork

    def _resolveResult(self, request, result):
        if isinstance(result, bytes):
            request.write(result)
            request.finish()
            return succeed(request)
        elif result is server.NOT_DONE_YET:
            if request.finished:
                return succeed(request)
            else:
                deferred = request.notifyFinish().addCallback(lambda _: request)
                deferred.request = request
                return deferred
        else:
            raise ValueError('Unexpected return value: %r' % (result,))

3 Source : distrib.py
with Apache License 2.0
from lynings

    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



class UserDirectory(resource.Resource):

3 Source : test_storage.py
with MIT License
from opacam

    def render(self, request):
        print('ExternalProcessPipeline render')
        if self.mimetype:
            request.setHeader('content-type', self.mimetype)

        ExternalProcessProducer(self.uri, request)
        return server.NOT_DONE_YET


class ExternalProcessProducer(log.LogAble):

3 Source : transcoder.py
with MIT License
from opacam

    def render_GET(self, request):
        self.info(f'render GET {request}')
        request.setResponseCode(200)
        if self.contentType is not None:
            request.setHeader(b'Content-Type', self.contentType)
        request.write(b'')

        headers = request.getAllHeaders()
        if 'connection' in headers and headers['connection'] == 'close':
            pass

        self.start(request)
        return server.NOT_DONE_YET

    def render_HEAD(self, request):

3 Source : transcoder.py
with MIT License
from opacam

    def render(self, request):
        print('ExternalProcessPipeline render')
        if self.pipeline_description is None:
            raise NotImplementedError(
                'Warning: operation cancelled. You must set a value for '
                + 'ExternalProcessPipeline.pipeline_description'
            )
        if self.contentType is not None:
            request.setHeader(b'Content-Type', self.contentType)

        ExternalProcessProducer(self.pipeline_description % self.uri, request)
        return server.NOT_DONE_YET


def transcoder_class_wrapper(klass, content_type, pipeline):

3 Source : ui.py
with MIT License
from opacam

    def render_GET(self, request):
        d = flatten(request, self.index, request.write)

        def done_index(ignored):
            request.finish()

        d.addBoth(done_index)
        return server.NOT_DONE_YET

    def getChild(self, name, request):

3 Source : web_utils.py
with MIT License
from opacam

    def _resolveResult(self, request, result):
        if isinstance(result, str):
            request.write(result)
            request.finish()
            return succeed(request)
        elif result is server.NOT_DONE_YET:
            if request.finished:
                return succeed(request)
            else:
                return request.notifyFinish().addCallback(lambda _: request)
        else:
            raise ValueError("Unexpected return value: %r" % (result,))

3 Source : auth.py
with MIT License
from zenomt

def asyncResponse(f):
	def wrapper(*s, **kw):
		f(*s, **kw)
		return server.NOT_DONE_YET
	return wrapper

def delay(interval):

0 Source : distrib.py
with MIT License
from autofelix

    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



class ResourcePublisher(pb.Root, styles.Versioned):

0 Source : script.py
with MIT License
from autofelix

    def render(self, request):
        """
        Render me to a web client.

        Load my file, execute it in a special namespace (with 'request' and
        '__file__' global vars) and finish the request.  Output to the web-page
        will NOT be handled with print - standard output goes to the log - but
        with request.write.
        """
        request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version))
        namespace = {'request': request,
                     '__file__': _coerceToFilesystemEncoding("", self.filename),
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError as e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(resource.NoResource("File not found.").render(request))
        except:
            io = NativeStringIO()
            traceback.print_exc(file=io)
            output = util._PRE(io.getvalue())
            if _PY3:
                output = output.encode("utf8")
            request.write(output)
        request.finish()
        return server.NOT_DONE_YET

0 Source : static.py
with MIT License
from autofelix

    def render_GET(self, request):
        """
        Begin sending the contents of this L{File} (or a subset of the
        contents, based on the 'range' header) to the given request.
        """
        self.restat(False)

        if self.type is None:
            self.type, self.encoding = getTypeAndEncoding(self.basename(),
                                                          self.contentTypes,
                                                          self.contentEncodings,
                                                          self.defaultType)

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        request.setHeader(b'accept-ranges', b'bytes')

        try:
            fileForReading = self.openForReading()
        except IOError as e:
            if e.errno == errno.EACCES:
                return self.forbidden.render(request)
            else:
                raise

        if request.setLastModified(self.getModificationTime()) is http.CACHED:
            # `setLastModified` also sets the response code for us, so if the
            # request is cached, we close the file now that we've made sure that
            # the request would otherwise succeed and return an empty body.
            fileForReading.close()
            return b''

        if request.method == b'HEAD':
            # Set the content headers here, rather than making a producer.
            self._setContentHeaders(request)
            # We've opened the file to make sure it's accessible, so close it
            # now that we don't need it.
            fileForReading.close()
            return b''

        producer = self.makeProducer(request, fileForReading)
        producer.start()

        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET
    render_HEAD = render_GET

0 Source : xmlrpc.py
with MIT License
from autofelix

    def render_POST(self, request):
        request.content.seek(0, 0)
        request.setHeader(b"content-type", b"text/xml; charset=utf-8")
        try:
            args, functionPath = xmlrpclib.loads(request.content.read(),
                use_datetime=self.useDateTime)
        except Exception as e:
            f = Fault(self.FAILURE, "Can't deserialize input: %s" % (e,))
            self._cbRender(f, request)
        else:
            try:
                function = self.lookupProcedure(functionPath)
            except Fault as f:
                self._cbRender(f, request)
            else:
                # Use this list to track whether the response has failed or not.
                # This will be used later on to decide if the result of the
                # Deferred should be written out and Request.finish called.
                responseFailed = []
                request.notifyFinish().addErrback(responseFailed.append)
                if getattr(function, 'withRequest', False):
                    d = defer.maybeDeferred(function, request, *args)
                else:
                    d = defer.maybeDeferred(function, *args)
                d.addErrback(self._ebRender)
                d.addCallback(self._cbRender, request, responseFailed)
        return server.NOT_DONE_YET


    def _cbRender(self, result, request, responseFailed=None):

0 Source : common.py
with MIT License
from fbla-competitive-events

    def _render_request(self, request):
        """
        Receives an HTTP/POST|PUT request, and then calls the Publisher/Caller
        processor.
        """
        # read HTTP/POST|PUT body
        body = request.content.read()

        args = {native_string(x): y[0] for x, y in request.args.items()}
        headers = request.requestHeaders

        # check content type + charset encoding
        #
        content_type_header = headers.getRawHeaders(b"content-type", [])

        if len(content_type_header) > 0:
            content_type_elements = [
                x.strip().lower()
                for x in content_type_header[0].split(b";")
            ]
        else:
            content_type_elements = []

        if self.decode_as_json:
            # if the client sent a content type, it MUST be one of _ALLOWED_CONTENT_TYPES
            # (but we allow missing content type .. will catch later during JSON
            # parsing anyway)
            if len(content_type_elements) > 0 and \
               content_type_elements[0] not in _ALLOWED_CONTENT_TYPES:
                return self._deny_request(
                    request, 400,
                    accepted=list(_ALLOWED_CONTENT_TYPES),
                    given=content_type_elements[0],
                    log_category="AR452"
                )

        encoding_parts = {}

        if len(content_type_elements) > 1:
            try:
                for item in content_type_elements:
                    if b"=" not in item:
                        # Don't bother looking at things "like application/json"
                        continue

                    # Parsing things like:
                    # charset=utf-8
                    _ = native_string(item).split("=")
                    assert len(_) == 2

                    # We don't want duplicates
                    key = _[0].strip().lower()
                    assert key not in encoding_parts
                    encoding_parts[key] = _[1].strip().lower()
            except:
                return self._deny_request(request, 400, log_category="AR450")

        charset_encoding = encoding_parts.get("charset", "utf-8")

        if charset_encoding not in ["utf-8", 'utf8']:
            return self._deny_request(
                request, 400,
                log_category="AR450")

        # enforce "post_body_limit"
        #
        body_length = len(body)
        content_length_header = headers.getRawHeaders(b"content-length", [])

        if len(content_length_header) == 1:
            content_length = int(content_length_header[0])
        elif len(content_length_header) > 1:
            return self._deny_request(
                request, 400,
                log_category="AR463")
        else:
            content_length = body_length

        if body_length != content_length:
            # Prevent the body length from being different to the given
            # Content-Length. This is so that clients can't lie and bypass
            # length restrictions by giving an incorrect header with a large
            # body.
            return self._deny_request(request, 400, bodylen=body_length,
                                      conlen=content_length,
                                      log_category="AR465")

        if self._post_body_limit and content_length > self._post_body_limit:
            return self._deny_request(
                request, 413,
                length=content_length,
                accepted=self._post_body_limit
            )

        #
        # parse/check HTTP/POST|PUT query parameters
        #

        # key
        #
        if 'key' in args:
            key_str = args["key"]
        else:
            if self._secret:
                return self._deny_request(
                    request, 400,
                    reason=u"'key' field missing",
                    log_category="AR461")

        # timestamp
        #
        if 'timestamp' in args:
            timestamp_str = args["timestamp"]
            try:
                ts = datetime.datetime.strptime(native_string(timestamp_str), "%Y-%m-%dT%H:%M:%S.%fZ")
                delta = abs((ts - datetime.datetime.utcnow()).total_seconds())
                if self._timestamp_delta_limit and delta > self._timestamp_delta_limit:
                    return self._deny_request(
                        request, 400,
                        log_category="AR464")
            except ValueError as e:
                return self._deny_request(
                    request, 400,
                    reason=u"invalid timestamp '{0}' (must be UTC/ISO-8601, e.g. '2011-10-14T16:59:51.123Z')".format(native_string(timestamp_str)),
                    log_category="AR462")
        else:
            if self._secret:
                return self._deny_request(
                    request, 400, reason=u"signed request required, but mandatory 'timestamp' field missing",
                    log_category="AR461")

        # seq
        #
        if 'seq' in args:
            seq_str = args["seq"]
            try:
                # FIXME: check sequence
                seq = int(seq_str)  # noqa
            except:
                return self._deny_request(
                    request, 400,
                    reason=u"invalid sequence number '{0}' (must be an integer)".format(native_string(seq_str)),
                    log_category="AR462")
        else:
            if self._secret:
                return self._deny_request(
                    request, 400,
                    reason=u"'seq' field missing",
                    log_category="AR461")

        # nonce
        #
        if 'nonce' in args:
            nonce_str = args["nonce"]
            try:
                # FIXME: check nonce
                nonce = int(nonce_str)  # noqa
            except:
                return self._deny_request(
                    request, 400,
                    reason=u"invalid nonce '{0}' (must be an integer)".format(native_string(nonce_str)),
                    log_category="AR462")
        else:
            if self._secret:
                return self._deny_request(
                    request, 400,
                    reason=u"'nonce' field missing",
                    log_category="AR461")

        # signature
        #
        if 'signature' in args:
            signature_str = args["signature"]
        else:
            if self._secret:
                return self._deny_request(
                    request, 400,
                    reason=u"'signature' field missing",
                    log_category="AR461")

        # do more checks if signed requests are required
        #
        if self._secret:

            if key_str != self._key:
                return self._deny_request(
                    request, 401,
                    reason=u"unknown key '{0}' in signed request".format(native_string(key_str)),
                    log_category="AR460")

            # Compute signature: HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature
            hm = hmac.new(self._secret, None, hashlib.sha256)
            hm.update(key_str)
            hm.update(timestamp_str)
            hm.update(seq_str)
            hm.update(nonce_str)
            hm.update(body)
            signature_recomputed = base64.urlsafe_b64encode(hm.digest())

            if signature_str != signature_recomputed:
                return self._deny_request(request, 401,
                                          log_category="AR459")
            else:
                self.log.debug("REST request signature valid.",
                               log_category="AR203")

        # user_agent = headers.get("user-agent", "unknown")
        client_ip = request.getClientIP()
        is_secure = request.isSecure()

        # enforce client IP address
        #
        if self._require_ip:
            ip = IPAddress(native_string(client_ip))
            allowed = False
            for net in self._require_ip:
                if ip in net:
                    allowed = True
                    break
            if not allowed:
                return self._deny_request(request, 400, log_category="AR466")

        # enforce TLS
        #
        if self._require_tls:
            if not is_secure:
                return self._deny_request(request, 400,
                                          reason=u"request denied because not using TLS")

        # FIXME: authorize request
        authorized = True

        if not authorized:
            return self._deny_request(request, 401, reason=u"not authorized")

        _validator.reset()
        validation_result = _validator.validate(body)

        # validate() returns a 4-tuple, of which item 0 is whether it
        # is valid
        if not validation_result[0]:
            return self._deny_request(
                request, 400,
                log_category="AR451")

        event = body.decode('utf8')

        if self.decode_as_json:
            try:
                event = json.loads(event)
            except Exception as e:
                return self._deny_request(
                    request, 400,
                    exc=e, log_category="AR453")

            if not isinstance(event, dict):
                return self._deny_request(
                    request, 400,
                    log_category="AR454")

        d = self._process(request, event)

        if isinstance(d, bytes):
            # If it's bytes, return it directly
            return d
        else:
            # If it's a Deferred, let it run.
            d.addCallback(lambda _: request.finish())

        return server.NOT_DONE_YET

    def _process(self, request, event):

0 Source : soap.py
with MIT License
from fbla-competitive-events

    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 = p._name, p._aslist, p._asdict

        # 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

    def _methodNotFound(self, request, methodName):

0 Source : words.py
with GNU General Public License v2.0
from flathub

    def render_POST(self, request):
        try:
            d = self.parent.process_webhook(request)
        except Exception:
            d = defer.fail()

        def ok(_):
            request.setResponseCode(202)
            request.finish()

        def err(error):
            try:
                self.parent.log_err(error, "processing telegram request", self.__class__.__name__)
            except AttributeError:
                log.err(error, "processing telegram request")
            request.setResponseCode(500)
            request.finish()

        d.addCallbacks(ok, err)

        return server.NOT_DONE_YET

0 Source : web.py
with GNU General Public License v2.0
from flathub

    def test_render(self, resource):
        for arg in self.args:
            if not isinstance(arg, bytes):
                raise ValueError("self.args: {!r},  contains "
                    "values which are not bytes".format(self.args))

        if self.uri and not isinstance(self.uri, bytes):
            raise ValueError("self.uri: {!r} is {}, not bytes".format(
                self.uri, type(self.uri)))

        if self.method and not isinstance(self.method, bytes):
            raise ValueError("self.method: {!r} is {}, not bytes".format(
                self.method, type(self.method)))

        result = resource.render(self)
        if isinstance(result, bytes):
            self.write(result)
            self.finish()
            return self.deferred
        elif isinstance(result, str):
            raise ValueError("{!r} should return bytes, not {}: {!r}".format(
                resource.render, type(result), result))
        elif result is server.NOT_DONE_YET:
            return self.deferred
        else:
            raise ValueError("Unexpected return value: {!r}".format(result))

0 Source : www.py
with GNU General Public License v2.0
from flathub

    def render_resource(self, rsrc, path=b'/', accept=None, method=b'GET',
                        origin=None, access_control_request_method=None,
                        extraHeaders=None, request=None):
        if not request:
            request = self.make_request(path, method=method)
            if accept:
                request.input_headers[b'accept'] = accept
            if origin:
                request.input_headers[b'origin'] = origin
            if access_control_request_method:
                request.input_headers[b'access-control-request-method'] = \
                    access_control_request_method
            if extraHeaders is not None:
                request.input_headers.update(extraHeaders)

        rv = rsrc.render(request)
        if rv != server.NOT_DONE_YET:
            if rv is not None:
                request.write(rv)
            request.finish()
        return request.deferred

    @defer.inlineCallbacks

0 Source : www.py
with GNU General Public License v2.0
from flathub

    def render_control_resource(self, rsrc, path=b'/', params=None,
                                requestJson=None, action="notfound", id=None,
                                content_type=b'application/json'):
        # pass *either* a request or postpath
        if params is None:
            params = {}
        id = id or self.UUID
        request = self.make_request(path)
        request.method = b"POST"
        request.content = StringIO(requestJson or json.dumps(
            {"jsonrpc": "2.0", "method": action, "params": params, "id": id}))
        request.input_headers = {b'content-type': content_type}
        rv = rsrc.render(request)
        if rv == server.NOT_DONE_YET:
            rv = yield request.deferred

        res = json.loads(bytes2unicode(rv))
        self.assertIn("jsonrpc", res)
        self.assertEqual(res["jsonrpc"], "2.0")
        if not requestJson:
            # requestJson is used for invalid requests, so don't expect ID
            self.assertIn("id", res)
            self.assertEqual(res["id"], id)

    def assertRequest(self, content=None, contentJson=None, contentType=None,

0 Source : change_hook.py
with GNU General Public License v2.0
from flathub

    def render_POST(self, request):
        """
        Responds to events and starts the build process
          different implementations can decide on what methods they will accept

        :arguments:
            request
                the http request object
        """
        try:
            d = self.getAndSubmitChanges(request)
        except Exception:
            d = defer.fail()

        def ok(_):
            request.setResponseCode(202)
            request.finish()

        def err(why):
            code = 500
            if why.check(ValueError):
                code = 400
                msg = unicode2bytes(why.getErrorMessage())
            else:
                log.err(why, "adding changes from web hook")
                msg = b'Error processing changes.'
            request.setResponseCode(code, msg)
            request.write(msg)
            request.finish()

        d.addCallbacks(ok, err)

        return server.NOT_DONE_YET

    @defer.inlineCallbacks

0 Source : resource.py
with GNU General Public License v2.0
from flathub

    def asyncRenderHelper(self, request, _callable, writeError=None):
        def writeErrorDefault(msg, errcode=400):
            request.setResponseCode(errcode)
            request.setHeader(b'content-type', b'text/plain; charset=utf-8')
            request.write(msg)
            request.finish()
        if writeError is None:
            writeError = writeErrorDefault
        try:
            d = _callable(request)
        except Exception as e:
            d = defer.fail(e)

        @d.addCallback
        def finish(s):
            try:
                if s is not None:
                    request.write(s)
                request.finish()
            except RuntimeError:  # pragma: no cover
                # this occurs when the client has already disconnected; ignore
                # it (see #2027)
                log.msg("http client disconnected before results were sent")

        @d.addErrback
        def failHttpRedirect(f):
            f.trap(Redirect)
            request.redirect(f.value.url)
            request.finish()
            return None

        @d.addErrback
        def failHttpError(f):
            f.trap(Error)
            e = f.value
            message = unicode2bytes(e.message)
            writeError(message, errcode=int(e.status))

        @d.addErrback
        def fail(f):
            log.err(f, 'While rendering resource:')
            try:
                writeError(b'internal error - see logs', errcode=500)
            except Exception:
                try:
                    request.finish()
                except Exception:
                    pass

        return server.NOT_DONE_YET


class RedirectResource(Resource):

0 Source : sse.py
with GNU General Public License v2.0
from flathub

    def render(self, request):
        command = b"listen"
        path = request.postpath
        if path and path[-1] == b'':
            path = path[:-1]

        if path and path[0] in (b"listen", b"add", b"remove"):
            command = path[0]
            path = path[1:]

        if command == b"listen":
            cid = unicode2bytes(str(uuid.uuid4()))
            consumer = Consumer(request)

        elif command in (b"add", b"remove"):
            if path:
                cid = path[0]
                path = path[1:]
                if cid not in self.consumers:
                    return self.finish(request, 400, b"unknown uuid")
                consumer = self.consumers[cid]
            else:
                return self.finish(request, 400, b"need uuid")

        pathref = b"/".join(path)
        path = self.decodePath(path)

        if command == b"add" or (command == b"listen" and path):
            options = request.args
            for k in options:
                if len(options[k]) == 1:
                    options[k] = options[k][1]

            try:
                d = self.master.mq.startConsuming(
                    consumer.onMessage,
                    tuple([bytes2unicode(p) for p in path]))

                @d.addCallback
                def register(qref):
                    consumer.registerQref(pathref, qref)
                d.addErrback(log.err, "while calling startConsuming")
            except NotImplementedError:
                return self.finish(request, 404, b"not implemented")
            except InvalidPathError:
                return self.finish(request, 404, b"not implemented")
        elif command == b"remove":
            try:
                consumer.stopConsuming(pathref)
            except KeyError:
                return self.finish(request, 404, b"consumer is not listening to this event")

        if command == b"listen":
            self.consumers[cid] = consumer
            request.setHeader(b"content-type", b"text/event-stream")
            request.write(b"")
            request.write(b"event: handshake\n")
            request.write(b"data: " + cid + b"\n")
            request.write(b"\n")
            d = request.notifyFinish()

            @d.addBoth
            def onEndRequest(_):
                consumer.stopConsuming()
                del self.consumers[cid]

            return server.NOT_DONE_YET

        self.finish(request, 200, b"ok")
        return None

0 Source : xmlrpc.py
with Apache License 2.0
from google

    def render_POST(self, request):
        request.content.seek(0, 0)
        request.setHeader("content-type", "text/xml")
        try:
            if self.useDateTime:
                args, functionPath = xmlrpc.client.loads(request.content.read(),
                    use_datetime=True)
            else:
                # Maintain backwards compatibility with Python   <   2.5
                args, functionPath = xmlrpc.client.loads(request.content.read())
        except Exception as e:
            f = Fault(self.FAILURE, "Can't deserialize input: %s" % (e,))
            self._cbRender(f, request)
        else:
            try:
                function = self.lookupProcedure(functionPath)
            except Fault as f:
                self._cbRender(f, request)
            else:
                # Use this list to track whether the response has failed or not.
                # This will be used later on to decide if the result of the
                # Deferred should be written out and Request.finish called.
                responseFailed = []
                request.notifyFinish().addErrback(responseFailed.append)
                if getattr(function, 'withRequest', False):
                    d = defer.maybeDeferred(function, request, *args)
                else:
                    d = defer.maybeDeferred(function, *args)
                d.addErrback(self._ebRender)
                d.addCallback(self._cbRender, request, responseFailed)
        return server.NOT_DONE_YET


    def _cbRender(self, result, request, responseFailed=None):

0 Source : iradio_storage.py
with MIT License
from opacam

    def render(self, request):

        if self.uri is None:

            def got_playlist(result):
                if result is None:
                    # print(
                    #     'Error to retrieve playlist - nothing retrieved')
                    return self.requestFinished(result)
                result = result[0].split(b'\n')
                for line in result:
                    if line.startswith(b'File1='):
                        self.uri = line[6:]
                        break
                if self.uri is None:
                    # print(
                    #     'Error to retrieve playlist - '
                    #     'inconsistent playlist file')
                    return self.requestFinished(result)
                request.uri = self.uri
                return self.render(request)

            def got_error(error):
                print(
                    f'Error to retrieve playlist - '
                    + f'unable to retrieve data [ERROR: {error}]'
                )
                return None

            playlist_url = self.uri
            d = utils.getPage(playlist_url, timeout=20)
            d.addCallbacks(got_playlist, got_error)
            return server.NOT_DONE_YET

        if request.clientproto == 'HTTP/1.1':
            self.connection = request.getHeader(b'connection')
            if self.connection:
                tokens = list(map(str.lower, self.connection.split(b' ')))
                if b'close' in tokens:
                    d = request.notifyFinish()
                    d.addBoth(self.requestFinished)
        else:
            d = request.notifyFinish()
            d.addBoth(self.requestFinished)
        return super(PlaylistStreamProxy, self).render(request)


class IRadioItem(BackendAudioItem):

0 Source : itv_storage.py
with MIT License
from opacam

    def render(self, request):

        if self.stream_url is None:

            def got_playlist(result):
                if result is None:
                    self.warning(
                        'Error to retrieve playlist - nothing retrieved'
                    )
                    return self.requestFinished(result)
                result = result[0].split('\n')
                for line in result:
                    if line.startswith('File1='):
                        self.stream_url = line[6:].split(';')[0]
                        break
                # print('stream URL:', self.stream_url)
                if self.stream_url is None:
                    self.warning(
                        'Error to retrieve playlist - '
                        'inconsistent playlist file'
                    )
                    return self.requestFinished(result)
                # self.resetUri(self.stream_url)
                request.uri = self.stream_url
                return self.render(request)

            def got_error(error):
                self.warning(error)
                return None

            playlist_url = self.uri
            # print('playlist URL:', playlist_url)
            d = utils.getPage(playlist_url, timeout=20)
            d.addCallbacks(got_playlist, got_error)
            return server.NOT_DONE_YET

        if request.clientproto == 'HTTP/1.1':
            self.connection = request.getHeader('connection')
            if self.connection:
                tokens = list(map(str.lower, self.connection.split(' ')))
                if 'close' in tokens:
                    d = request.notifyFinish()
                    d.addBoth(self.requestFinished)
        else:
            d = request.notifyFinish()
            d.addBoth(self.requestFinished)
        return utils.ReverseProxyUriResource.render(self, request)


class Container(BackendItem):

0 Source : twitch_storage.py
with MIT License
from opacam

    def render_GET(self, request):
        self.debug(
            f'serving {request.method} request from '
            f'{request.getClientIP()} for {request.uri}'
        )

        def stream_opened(fd):
            producer = NoRangeStaticProducer(request, fd)
            producer.start()

        def got_streams(streams):
            if self.stream_id not in streams:
                self.warning(
                    f'stream not found for ' f'{self.url}@{self.stream_id}'
                )
                request.setResponseCode(http.NOT_FOUND)
                request.write(b'')
                return

            request.setHeader(
                b'Content-Type', self.content_type.encode('ascii')
            )
            request.setResponseCode(http.OK)

            if request.method == b'HEAD':
                request.write(b'')
                return

            d_open_stream = threads.deferToThread(streams[self.stream_id].open)
            d_open_stream.addCallback(stream_opened)

        d_get_streams = threads.deferToThread(livestreamer.streams, self.url)
        d_get_streams.addCallback(got_streams)

        return server.NOT_DONE_YET


class TwitchLazyContainer(LazyContainer):

0 Source : youtube_storage.py
with MIT License
from opacam

    def render(self, request):

        self.info(
            f'VideoProxy render {request} {self.stream_url} {self.video_url}'
        )
        self.info(f'VideoProxy headers: {request.getAllHeaders()}')
        self.info(f'VideoProxy id: {self.id}')

        d = request.notifyFinish()
        d.addBoth(self.requestFinished)

        if self.stream_url is None:

            web_url = f'http://{self.host}{self.path}'
            self.info(f'Web_url: {web_url}')

            def got_real_urls(real_urls):
                if len(real_urls) == 0:
                    self.warning('Unable to retrieve any URL for video stream')
                    return self.requestFinished(None)
                else:
                    got_real_url(real_urls[0])

            def got_real_url(real_url):
                self.info(f'Real URL is {real_url}')
                self.stream_url = real_url
                if self.stream_url is None:
                    self.warning(
                        'Unable to retrieve URL - inconsistent web page'
                    )
                    return self.requestFinished(None)  # FIXME
                self.stream_url = self.stream_url.encode('ascii', 'strict')
                self.resetUri(self.stream_url)
                self.info(f'Video URL: {self.stream_url}')
                self.video_url = self.stream_url[:]
                d = self.followRedirects(request)
                d.addCallback(self.proxyURL)
                d.addErrback(self.requestFinished)

            if self.url_extractor_fct is not None:
                d = self.url_extractor_fct(
                    web_url, **self.url_extractor_params
                )
                d.addCallback(got_real_urls)
            else:
                got_real_url(web_url)
            return server.NOT_DONE_YET

        reactor.callLater(0.05, self.proxyURL, request)
        return server.NOT_DONE_YET

    def followRedirects(self, request):

0 Source : youtube_storage.py
with MIT License
from opacam

    def proxyURL(self, request):
        self.info(f'proxy_mode: {self.proxy_mode}, request {request.method}')

        if self.proxy_mode == 'redirect':
            # send stream url to client for redirection
            request.redirect(self.stream_url)
            request.finish()
        elif self.proxy_mode in ('proxy',):
            res = ReverseProxyResource.render(self, request)
            if isinstance(res, int):
                return res
            request.write(res)
            return
        elif self.proxy_mode in ('buffer', 'buffered'):
            # download stream to cache,
            # and send it to the client in // after X bytes
            filepath = os.path.join(self.cache_directory, self.id)

            file_is_already_available = False
            if (
                os.path.exists(filepath)
                and os.path.getsize(filepath) == self.filesize
            ):
                res = self.renderFile(request, filepath)
                if isinstance(res, int):
                    return res
                request.write(res)
                request.finish()
            else:
                if request.method != 'HEAD':
                    self.downloadFile(request, filepath, None)
                    range = request.getHeader('range')
                    if range is not None:
                        bytesrange = range.split('=')
                        assert (
                            bytesrange[0] == 'bytes'
                        ), 'Syntactically invalid http range header!'
                        start, end = bytesrange[1].split('-', 1)
                        # print('%r %r' %(start,end))
                        if start:
                            start = int(start)
                            if end:
                                end = int(end)
                            else:
                                end = self.filesize - 1
                            # Are we requesting something
                            # beyond the current size of the file?
                            try:
                                size = os.path.getsize(filepath)
                            except OSError:
                                size = 0
                            if (
                                start >= size
                                and end + 10 > self.filesize
                                and end - start   <   200000
                            ):
                                # print 'let's hand that through,
                                # it is probably a mp4 index request'
                                res = ReverseProxyResource.render(
                                    self, request
                                )
                                if isinstance(res, int):
                                    return res
                                request.write(res)
                                return

                res = self.renderBufferFile(
                    request, filepath, self.buffer_size
                )
                if res == '' and request.method != 'HEAD':
                    return server.NOT_DONE_YET
                if not isinstance(res, int):
                    request.write(res)
                if request.method == 'HEAD':
                    request.finish()

        else:
            self.warning(f'Unsupported Proxy Mode: {self.proxy_mode}')
            return self.requestFinished(None)

    def getMimetype(self):

0 Source : transcoder.py
with MIT License
from opacam

    def render_GET(self, request):
        self.info(f'render GET {request}')
        request.setResponseCode(200)
        if hasattr(self, 'contentType'):
            request.setHeader(b'Content-Type', self.contentType)
        request.write(b'')

        headers = request.getAllHeaders()
        if 'connection' in headers and headers['connection'] == 'close':
            pass
        if self.requests:
            if self.streamheader:
                self.debug('writing streamheader')
                for h in self.streamheader:
                    request.write(h.data)
            self.requests.append(request)
        else:
            self.parse_pipeline()
            self.start(request)
        return server.NOT_DONE_YET

    def render_HEAD(self, request):

0 Source : soap_service.py
with MIT License
from opacam

    def render(self, request):
        '''Handle a SOAP command.'''
        data = request.content.read()
        headers = request.getAllHeaders()
        self.info(f'soap_request: {headers}')

        # allow external check of data
        self.dispatch_event('control_client_command_received', headers, data)

        def print_c(e):
            for c in e.getchildren():
                print(c, c.tag)
                print_c(c)

        if data == b'':
            return b'  <  p>No content to show < /p>'
        try:
            tree = etree.fromstring(data)
        except Exception:
            self.warning(
                'UPnPPublisher.render: error on parsing soap result, probably'
                + ' has encoding declaration, trying with another method...'
            )
            tree = parse_with_lxml(data, encoding='utf-8')

        body = tree.find('{http://schemas.xmlsoap.org/soap/envelope/}Body')
        method = body.getchildren()[0]
        methodName = method.tag
        ns = None

        if methodName.startswith('{') and methodName.rfind('}') > 1:
            ns, methodName = methodName[1:].split('}')

        args = []
        kwargs = {}
        for child in method.getchildren():
            kwargs[child.tag] = self.decode_result(child)
            args.append(kwargs[child.tag])

        # p, header, body, attrs = SOAPpy.parseSOAPRPC(data, 1, 1, 1)
        # methodName, args, kwargs, ns = p._name, p._aslist, p._asdict, p._ns

        try:
            headers[b'content-type'].index(b'text/xml')
        except (KeyError, ValueError):
            self._gotError(
                failure.Failure(errorCode(415)), request, methodName, ns
            )
            return server.NOT_DONE_YET

        self.debug(f'headers: {headers}')

        l_function, use_keywords = self.lookupFunction(methodName)
        # print('function', function, 'keywords', useKeywords,
        #       'args', args, 'kwargs', kwargs)

        if not l_function:
            self._methodNotFound(request, methodName)
            return server.NOT_DONE_YET
        else:
            keywords = {'soap_methodName': methodName}
            if (
                b'user-agent' in headers
                and headers[b'user-agent'].find(b'Xbox/') == 0
            ):
                keywords['X_UPnPClient'] = 'XBox'
            # if headers.has_key(b'user-agent') and \
            #         headers[b'user-agent'].startswith(
            #             b'''Mozilla/4.0 (compatible; UPnP/1.0; Windows'''):
            #     keywords['X_UPnPClient'] = 'XBox'
            if (
                b'x-av-client-info' in headers
                and headers[b'x-av-client-info'].find(b'"PLAYSTATION3') > 0
            ):
                keywords['X_UPnPClient'] = 'PLAYSTATION3'
            if (
                b'user-agent' in headers
                and headers[b'user-agent'].find(
                    b'Philips-Software-WebClient/4.32'
                )
                == 0
            ):
                keywords['X_UPnPClient'] = 'Philips-TV'
            for k, v in list(kwargs.items()):
                keywords[str(k)] = v
            self.info(f'call {methodName} {keywords}')
            if hasattr(l_function, 'useKeywords'):
                d = defer.maybeDeferred(l_function, **keywords)
            else:
                d = defer.maybeDeferred(l_function, *args, **keywords)

        d.addCallback(self._gotResult, request, methodName, ns)
        d.addErrback(self._gotError, request, methodName, ns)
        return server.NOT_DONE_YET

    def decode_result(self, element):

0 Source : utils.py
with MIT License
from opacam

    def render(self, request):
        '''
        Render a request by forwarding it to the proxied server.
        '''
        # RFC 2616 tells us that we can omit the port if it's the default port,
        # but we have to provide it otherwise
        if self.port == 80:
            host = self.host
        else:
            host = self.host + b':' + to_bytes(self.port)
        request.requestHeaders.setRawHeaders(b'host', [host])
        request.content.seek(0, 0)
        qs = urlparse(request.uri)[4]
        if qs == b'':
            qs = self.qs
        if qs:
            rest = self.path + b'?' + qs
        else:
            rest = self.path
        clientFactory = self.proxyClientFactoryClass(
            request.method,
            rest,
            request.clientproto,
            request.getAllHeaders(),
            request.content.read(),
            request,
        )
        self.reactor.connectTCP(self.host, self.port, clientFactory)
        return server.NOT_DONE_YET

    def resetTarget(self, host, port, path, qs=''):

0 Source : utils.py
with MIT License
from opacam

    def render(self, request):
        # print ''
        # print 'BufferFile', request

        # FIXME detect when request is REALLY finished
        if request is None or request.finished:
            logger.info('No request to render!')
            return ''

        '''You know what you doing.'''
        self.restat()

        if self.type is None:
            self.type, self.encoding = static.getTypeAndEncoding(
                self.basename(),
                self.contentTypes,
                self.contentEncodings,
                self.defaultType,
            )

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        # for content-length
        if self.target_size > 0:
            fsize = size = int(self.target_size)
        else:
            fsize = size = int(self.getFileSize())

        # print fsize

        if size == int(self.getFileSize()):
            request.setHeader(b'accept-ranges', b'bytes')

        if self.type:
            request.setHeader(b'content-type', to_bytes(self.type))
        if self.encoding:
            request.setHeader(b'content-encoding', to_bytes(self.encoding))

        try:
            f = self.openForReading()
        except IOError as e:
            import errno

            if e.errno == errno.EACCES:
                return resource.ForbiddenResource().render(request)
            else:
                raise
        if request.setLastModified(self.getmtime()) is http.CACHED:
            return ''
        trans = True

        range = request.getHeader('range')
        # print 'StaticFile', range

        tsize = size
        if range is not None:
            # This is a request for partial data...
            bytesrange = range.split('=')
            assert (
                bytesrange[0] == 'bytes'
            ), 'Syntactically invalid http range header!'
            start, end = bytesrange[1].split('-', 1)
            if start:
                start = int(start)
                # Are we requesting something
                # beyond the current size of the file?
                if start >= self.getFileSize():
                    # Retry later!
                    logger.info(bytesrange)
                    logger.info(
                        'Requesting data beyond current scope -> '
                        'postpone rendering!'
                    )
                    self.upnp_retry = reactor.callLater(
                        1.0, self.render, request
                    )
                    return server.NOT_DONE_YET

                f.seek(start)
                if end:
                    # print(f':{end}')
                    end = int(end)
                else:
                    end = size - 1
            else:
                lastbytes = int(end)
                if size   <   lastbytes:
                    lastbytes = size
                start = size - lastbytes
                f.seek(start)
                fsize = lastbytes
                end = size - 1
            size = end + 1
            fsize = end - int(start) + 1
            # start is the byte offset to begin, and end is the byte offset
            # to end..  fsize is size to send, tsize is the real size of
            # the file, and size is the byte position to stop sending.
            if fsize  < = 0:
                request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
                fsize = tsize
                trans = False
            else:
                request.setResponseCode(http.PARTIAL_CONTENT)
                request.setHeader(
                    b'content-range',
                    f'bytes {str(start)}-{str(end)}/{str(tsize)} '.encode(
                        'ascii'
                    ),
                )
                # print 'StaticFile', start, end, tsize

        request.setHeader('content-length', str(fsize))

        if request.method == b'HEAD' or trans is False:
            # pretend we're a HEAD request, so content-length
            # won't be overwritten.
            request.method = b'HEAD'
            return ''
        # print 'StaticFile out', request.headers, request.code

        # return data
        # size is the byte position to stop sending, not how many bytes to send

        BufferFileTransfer(f, size - f.tell(), request)
        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET


class BufferFileTransfer(object):

0 Source : websso_daemon.py
with GNU General Public License v3.0
from SURFscz

    def render_POST(self, request):
        session = request.getSession()
        s = ISession(session)
        nonce = s.nonce
        args = request.args
        client = self.client.clients.get(nonce)
        if client:
            pin = client['pin'][0]
        else:
            return "  <  html> < body>Unknown Error < /body> < /html>"
        if args.get('action'):
            if 'login' in args.get('action'):
                req = self._prepare_from_twisted_request(request)
                auth = OneLogin_Saml2_Auth(req, old_settings=self.settings)
                redirect = auth.login()
                request.redirect(redirect)
                request.finish()
                return server.NOT_DONE_YET
            else:
                self.client.handleCommand(nonce, " FAIL")
                return " < html> < body>PIN failed! < /body> < /html>"

        req = self._prepare_from_twisted_request(request)
        auth = OneLogin_Saml2_Auth(req, old_settings=self.settings)
        auth.process_response()
        errors = auth.get_errors()
        msg = { 'uid': '', 'result': 'FAIL' }
        if auth.is_authenticated():
            attributes = auth.get_attributes()
            print("attributes: {}".format(attributes))
            uid_attr = attributes.get(self.settings.get('user_attribute'))
            if uid_attr:
                msg['uid'] = uid_attr[0]
                msg['result'] = 'SUCCESS'
        self.client.handleCommand(nonce, json.dumps(msg))

        #print("Destroy %s" % nonce)
        #self.client.clients.pop(nonce)
        request.setHeader(b"content-type", b"text/html")
        content =  u" < html>\n < body>\n"
        content += u"{}/{} successfully authenticated < br />\n".format(nonce, msg['uid'])
        content += u"PIN: {} < br />\n".format(pin)
        content += u"This window may be closed\n"
        content += u" < /body>\n < /html>\n"
        return content.encode("ascii")

class Server: