Python twisted.web.http.datetimeToString() Examples

The following are 20 code examples of twisted.web.http.datetimeToString(). 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.http , or try the search function .
Example #1
Source File: server.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def process(self):
        """
        Process a request.
        """

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader(b'server', version)
        self.setHeader(b'date', http.datetimeToString())

        # Resource Identification
        self.prepath = []
        self.postpath = list(map(unquote, self.path[1:].split(b'/')))

        try:
            resrc = self.site.getResourceFor(self)
            if resource._IEncodingResource.providedBy(resrc):
                encoder = resrc.getEncoder(self)
                if encoder is not None:
                    self._encoder = encoder
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure()) 
Example #2
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_unmodified(self):
        """
        If a request is made with an I{If-Modified-Since} header value with a
        timestamp indicating a time after the last modification of the request
        resource, a 304 response is returned along with an empty response body
        and no Content-Type header if the application does not set one.
        """
        for line in [b"GET / HTTP/1.1",
                     b"If-Modified-Since: " + http.datetimeToString(100), b""]:
            self.channel.dataReceived(line + b'\r\n')
        result = self.transport.getvalue()
        self.assertEqual(httpCode(result), http.NOT_MODIFIED)
        self.assertEqual(httpBody(result), b"")
        # Since there SHOULD NOT (RFC 2616, section 10.3.5) be any
        # entity-headers, the Content-Type is not set if the application does
        # not explicitly set it.
        self.assertEqual(httpHeader(result, b"Content-Type"), None) 
Example #3
Source File: server.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def process(self):
        "Process a request."

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader('server', version)
        self.setHeader('date', http.datetimeToString())
        self.setHeader('content-type', "text/html")

        # Resource Identification
        self.prepath = []
        self.postpath = map(unquote, string.split(self.path[1:], '/'))
        try:
            resrc = self.site.getResourceFor(self)
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure()) 
Example #4
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_unmodified(self):
        """
        If a request is made with an I{If-Modified-Since} header value with a
        timestamp indicating a time after the last modification of the request
        resource, a 304 response is returned along with an empty response body
        and no Content-Type header if the application does not set one.
        """
        for line in [b"GET / HTTP/1.1",
                     b"If-Modified-Since: " + http.datetimeToString(100), b""]:
            self.channel.dataReceived(line + b'\r\n')
        result = self.transport.getvalue()
        self.assertEqual(httpCode(result), http.NOT_MODIFIED)
        self.assertEqual(httpBody(result), b"")
        # Since there SHOULD NOT (RFC 2616, section 10.3.5) be any
        # entity-headers, the Content-Type is not set if the application does
        # not explicitly set it.
        self.assertEqual(httpHeader(result, b"Content-Type"), None) 
Example #5
Source File: server.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def process(self):
        "Process a request."

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader('server', version)
        self.setHeader('date', http.datetimeToString())
        self.setHeader('content-type', "text/html")

        # Resource Identification
        self.prepath = []
        self.postpath = map(unquote, string.split(self.path[1:], '/'))
        try:
            resrc = self.site.getResourceFor(self)
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure()) 
Example #6
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_modified(self):
        """
        If a request is made with an I{If-Modified-Since} header value with
        a timestamp indicating a time before the last modification of the
        requested resource, a 200 response is returned along with a response
        body containing the resource.
        """
        self._modifiedTest(modifiedSince=http.datetimeToString(1)) 
Example #7
Source File: test_http.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testRoundtrip(self):
        for i in range(10000):
            time = random.randint(0, 2000000000)
            timestr = http.datetimeToString(time)
            time2 = http.stringToDatetime(timestr)
            self.assertEquals(time, time2) 
Example #8
Source File: test_web.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def test_unmodified(self):
        """If-Modified-Since cache validator (negative)"""
        self.channel.lineReceived("If-Modified-Since: %s"
                                  % http.datetimeToString(100))
        self.channel.lineReceived('')
        result = self.transport.getvalue()
        self.failUnlessEqual(httpCode(result), http.NOT_MODIFIED)
        self.failUnlessEqual(httpBody(result), "") 
Example #9
Source File: test_web.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def test_modified(self):
        """If-Modified-Since cache validator (positive)"""
        self.channel.lineReceived("If-Modified-Since: %s"
                                  % http.datetimeToString(1))
        self.channel.lineReceived('')
        result = self.transport.getvalue()
        self.failUnlessEqual(httpCode(result), http.OK)
        self.failUnlessEqual(httpBody(result), "correct") 
Example #10
Source File: test_http.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testRoundtrip(self):
        for i in range(10000):
            time = random.randint(0, 2000000000)
            timestr = http.datetimeToString(time)
            time2 = http.stringToDatetime(timestr)
            self.assertEquals(time, time2) 
Example #11
Source File: test_web.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_unmodified(self):
        """
        If a request is made with an I{If-Modified-Since} header value with
        a timestamp indicating a time after the last modification of the
        request resource, a 304 response is returned along with an empty
        response body.
        """
        self.channel.lineReceived("If-Modified-Since: %s"
                                  % http.datetimeToString(100))
        self.channel.lineReceived('')
        result = self.transport.getvalue()
        self.failUnlessEqual(httpCode(result), http.NOT_MODIFIED)
        self.failUnlessEqual(httpBody(result), "") 
Example #12
Source File: test_web.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_modified(self):
        """
        If a request is made with an I{If-Modified-Since} header value with
        a timestamp indicating a time before the last modification of the
        requested resource, a 200 response is returned along with a response
        body containing the resource.
        """
        self._modifiedTest(http.datetimeToString(1)) 
Example #13
Source File: test_http.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testRoundtrip(self):
        for i in range(10000):
            time = random.randint(0, 2000000000)
            timestr = http.datetimeToString(time)
            time2 = http.stringToDatetime(timestr)
            self.assertEqual(time, time2) 
Example #14
Source File: test_web.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_deprecatedAttributeDateTimeString(self):
        """
        twisted.web.server.date_time_string should not be used; instead use
        twisted.web.http.datetimeToString directly
        """
        server.date_time_string
        warnings = self.flushWarnings(
            offendingFunctions=[self.test_deprecatedAttributeDateTimeString])

        self.assertEqual(len(warnings), 1)
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            ("twisted.web.server.date_time_string was deprecated in Twisted "
             "12.1.0: Please use twisted.web.http.datetimeToString instead")) 
Example #15
Source File: test_web.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_modified(self):
        """
        If a request is made with an I{If-Modified-Since} header value with
        a timestamp indicating a time before the last modification of the
        requested resource, a 200 response is returned along with a response
        body containing the resource.
        """
        self._modifiedTest(modifiedSince=http.datetimeToString(1)) 
Example #16
Source File: server.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def process(self):
        """
        Process a request.

        Find the addressed resource in this request's L{Site},
        and call L{self.render()<Request.render()>} with it.

        @see: L{Site.getResourceFor()}
        """

        # get site from channel
        self.site = self.channel.site

        # set various default headers
        self.setHeader(b'server', version)
        self.setHeader(b'date', http.datetimeToString())

        # Resource Identification
        self.prepath = []
        self.postpath = list(map(unquote, self.path[1:].split(b'/')))

        # Short-circuit for requests whose path is '*'.
        if self.path == b'*':
            self._handleStar()
            return

        try:
            resrc = self.site.getResourceFor(self)
            if resource._IEncodingResource.providedBy(resrc):
                encoder = resrc.getEncoder(self)
                if encoder is not None:
                    self._encoder = encoder
            self.render(resrc)
        except:
            self.processingFailed(failure.Failure()) 
Example #17
Source File: test_http.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testRoundtrip(self):
        for i in range(10000):
            time = random.randint(0, 2000000000)
            timestr = http.datetimeToString(time)
            time2 = http.stringToDatetime(timestr)
            self.assertEqual(time, time2) 
Example #18
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_deprecatedAttributeDateTimeString(self):
        """
        twisted.web.server.date_time_string should not be used; instead use
        twisted.web.http.datetimeToString directly
        """
        server.date_time_string
        warnings = self.flushWarnings(
            offendingFunctions=[self.test_deprecatedAttributeDateTimeString])

        self.assertEqual(len(warnings), 1)
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            ("twisted.web.server.date_time_string was deprecated in Twisted "
             "12.1.0: Please use twisted.web.http.datetimeToString instead")) 
Example #19
Source File: service_discovery_ssdp.py    From calvin-base with Apache License 2.0 4 votes vote down vote up
def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("ServerBase::Received %s, %s from %r" % (cmd, headers, address, ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                _log.debug("Ignore list %s ignore %s" % (self.ignore_list, address not in self.ignore_list))
                # Only reply to our requests
                if SERVICE_UUID in headers['st'] and address not in self.ignore_list:
                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[0] != "127.0.0.1":
                                continue

                            response = MS_RESP[SERVICE_UUID] % ('%s:%d' % addr, str(time.time()),
                                                                k, self._control_uri + "/node/" + self._node_id, datetimeToString())
                            if "cert" in self._msearches_resp[SERVICE_UUID].keys():
                                response += "CERTIFICATE: {}\r\n\r\n".format(self._msearches_resp[SERVICE_UUID]["cert"])
                            _log.debug("ServerBase::Sending response: %s" % repr(response))
                            delay = random.randint(0, min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it,
                                                  response, address)
                elif CA_SERVICE_UUID in headers['st'] and address not in self.ignore_list\
                    and self._msearches_resp[CA_SERVICE_UUID]["sign"]:
                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[0] != "127.0.0.1":
                                continue
                            try:
                                response = MS_RESP[CA_SERVICE_UUID] % (str(addr),
                                                                    str(time.time()),
                                                                    self._control_uri + "/node/" + self._node_id,
                                                                    datetimeToString())
                            except Exception as err:
                                _log.error("Failed to create response, err={}".format(err))
                                raise
                            _log.debug("ServerBase::Sending response: %s" % repr(response))
                            delay = random.randint(0, min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it,
                                                  response, address)

        except:
            _log.exception("Error datagram received") 
Example #20
Source File: service_discovery_ssdp.py    From calvin-base with Apache License 2.0 4 votes vote down vote up
def datagramReceived(self, datagram, address):
        # Broadcast
        try:
            cmd, headers = parse_http_response(datagram)
            _log.debug("ServerBase::Received %s, %s from %r" % (cmd, headers, address, ))

            if cmd[0] == 'M-SEARCH' and cmd[1] == '*':

                _log.debug("Ignore list %s ignore %s" % (self.ignore_list, address not in self.ignore_list))
                # Only reply to our requests
                if SERVICE_UUID in headers['st'] and address not in self.ignore_list:

                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[0] != "127.0.0.1":
                                continue
                            response = MS_RESP[SERVICE_UUID] % ('%s:%d' % addr, str(time.time()),
                                                                k, self._control_uri + "/node/" + self._node_id, datetimeToString())
                            if "cert" in self._msearches_resp[SERVICE_UUID].keys():
                                response += "CERTIFICATE: {}\r\n\r\n".format(self._msearches_resp[SERVICE_UUID]["cert"])
                            _log.debug("ServerBase::Sending response: %s" % repr(response))
                            delay = random.randint(0, min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it,
                                                  response, address)
                elif CA_SERVICE_UUID in headers['st'] and address not in self.ignore_list\
                    and self._msearches_resp[CA_SERVICE_UUID]["sign"]:
                    for k, addrs in self._services.items():
                        for addr in addrs:
                            # Only tell local about local
                            if addr[0] == "127.0.0.1" and address[0] != "127.0.0.1":
                                continue
                            try:
                                response = MS_RESP[CA_SERVICE_UUID] % (str(addr),
                                                                    str(time.time()),
                                                                    self._control_uri + "/node/" + self._node_id,
                                                                    datetimeToString())
                            except Exception as err:
                                _log.error("Failed to create response, err={}".format(err))
                                raise
                            _log.debug("ServerBase::Sending response: %s" % repr(response))
                            delay = random.randint(0, min(5, int(headers['mx'])))
                            reactor.callLater(delay, self.send_it,
                                                  response, address)
        except Exception as err:
            _log.exception("SSDP search received, but failed handling, err={}".format(err))