Python twisted.web.http.NOT_FOUND Examples

The following are 30 code examples of twisted.web.http.NOT_FOUND(). 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: target.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def response_no_results(self, bucket):
        """
        Send "404 Not Found" response body in text/plain
        format describing HTTP API query interface.
        """
        # FIXME: Some words about "now-10d" being the default for "from", see influx.py.
        # FIXME: Maybe refactor "now-10d" to transformation machinery to make it accessible from here.
        error_message = u'# 404 Not Found\n#\n'\
                        u'# No data for query expression "{expression}"\n'\
                        u'# Please recognize absolute datetimes are expected to be in ISO 8601 format. '\
                        u'Default is UTC, optionally specify an appropriate timezone offset.\n'.format(expression=bucket.tdata.expression)
        error_message += u'#\n# Examples:\n#\n'\
                         u'#   ?from=2016-06-25T22:00:00.000Z\n'\
                         u'#   ?from=2016-06-26T00:00:00.000%2B02:00    (%2B is "+" urlencoded)\n'\
                         u'#   ?from=now-4h&to=now-2h\n'\
                         u'#   ?from=now-8d5h3m&to=now-6d'
        bucket.request.setResponseCode(http.NOT_FOUND)
        bucket.request.setHeader('Content-Type', 'text/plain; charset=utf-8')
        return error_message.encode('utf-8') 
Example #2
Source File: script.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
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("x-powered-by","Twisted/%s" % copyright.version)
        namespace = {'request': request,
                     '__file__': self.filename,
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError, e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(error.NoResource("File not found.").render(request)) 
Example #3
Source File: test_cgi.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_notFoundChild(self):
        """
        L{twcgi.CGIDirectory.getChild} returns a resource which renders an
        response with the HTTP I{NOT FOUND} status code if the indicated child
        does not exist as an entry in the directory used to initialized the
        L{twcgi.CGIDirectory}.
        """
        path = self.mktemp()
        os.makedirs(path)
        resource = twcgi.CGIDirectory(path)
        request = DummyRequest(['foo'])
        child = resource.getChild("foo", request)
        d = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #4
Source File: test_script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_notFoundChild(self):
        """
        L{ResourceScriptDirectory.getChild} returns a resource which renders an
        response with the HTTP I{NOT FOUND} status code if the indicated child
        does not exist as an entry in the directory used to initialized the
        L{ResourceScriptDirectory}.
        """
        path = self.mktemp()
        os.makedirs(path)
        resource = ResourceScriptDirectory(path)
        request = DummyRequest([b'foo'])
        child = resource.getChild("foo", request)
        d = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #5
Source File: test_cgi.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_notFoundChild(self):
        """
        L{twcgi.CGIDirectory.getChild} returns a resource which renders an
        response with the HTTP I{NOT FOUND} status code if the indicated child
        does not exist as an entry in the directory used to initialized the
        L{twcgi.CGIDirectory}.
        """
        path = self.mktemp()
        os.makedirs(path)
        resource = twcgi.CGIDirectory(path)
        request = DummyRequest(['foo'])
        child = resource.getChild("foo", request)
        d = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #6
Source File: launcher.py    From wslink with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_GET(self, request):
        id = extractSessionId(request)

        if not id:
           message = "id not provided in GET request"
           logging.error(message)
           request.setResponseCode(http.BAD_REQUEST)
           return jsonResponse({"error":message})

        logging.info("GET request received for id: %s" % id)

        session = self.session_manager.getSession(id)
        if not session:
           message = "No session with id: %s" % id
           logging.error(message)
           request.setResponseCode(http.NOT_FOUND)
           return jsonResponse({"error":message})

        # Return session meta-data
        request.setResponseCode(http.OK)
        return jsonResponse(filterResponse(session, self.field_filter))

    # =========================================================================
    # Handle DELETE request
    # ========================================================================= 
Example #7
Source File: test_cgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_notFoundChild(self):
        """
        L{twcgi.CGIDirectory.getChild} returns a resource which renders an
        response with the HTTP I{NOT FOUND} status code if the indicated child
        does not exist as an entry in the directory used to initialized the
        L{twcgi.CGIDirectory}.
        """
        path = self.mktemp()
        os.makedirs(path)
        resource = twcgi.CGIDirectory(path)
        request = DummyRequest(['foo'])
        child = resource.getChild("foo", request)
        d = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #8
Source File: test_script.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_notFoundChild(self):
        """
        L{ResourceScriptDirectory.getChild} returns a resource which renders an
        response with the HTTP I{NOT FOUND} status code if the indicated child
        does not exist as an entry in the directory used to initialized the
        L{ResourceScriptDirectory}.
        """
        path = self.mktemp()
        os.makedirs(path)
        resource = ResourceScriptDirectory(path)
        request = DummyRequest([b'foo'])
        child = resource.getChild("foo", request)
        d = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #9
Source File: script.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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("x-powered-by","Twisted/%s" % copyright.version)
        namespace = {'request': request,
                     '__file__': self.filename,
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError, e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(resource.NoResource("File not found.").render(request)) 
Example #10
Source File: test_script.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_notFoundRender(self):
        """
        If the source file a L{PythonScript} is initialized with doesn't exist,
        L{PythonScript.render} sets the HTTP response code to I{NOT FOUND}.
        """
        resource = PythonScript(self.mktemp(), None)
        request = DummyRequest([''])
        d = _render(resource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #11
Source File: benchlib.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def deleteResource(self, path):
        url = self._makeURL(path)
        d = self.agent.request('DELETE', url)

        def deleted(response):
            if response.code not in (NO_CONTENT, NOT_FOUND):
                raise Exception(
                    "Unexpected response to DELETE %s: %d" % (
                        url, response.code))
        d.addCallback(deleted)
        return d 
Example #12
Source File: launcher.py    From wslink with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_DELETE(self, request):
        id = extractSessionId(request)

        if not id:
           message = "id not provided in DELETE request"
           logging.error(message)
           request.setResponseCode(http.BAD_REQUEST)
           return jsonResponse({"error":message})

        logging.info("DELETE request received for id: %s" % id)

        session = self.session_manager.getSession(id)
        if not session:
           message = "No session with id: %s" % id
           logging.error(message)
           request.setResponseCode(http.NOT_FOUND)
           return jsonResponse({"error":message})

        # Remove session
        self.session_manager.deleteSession(id)
        self.process_manager.stopProcess(id)

        message = "Deleted session with id: %s" % id
        logging.info(message)

        request.setResponseCode(http.OK)
        return session

# =============================================================================
# Start the web server
# ============================================================================= 
Example #13
Source File: t43_http_formhandler.py    From python_web_Crawler_DA_ML_DL with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process(self):  # 重载方法,查找并匹配路径
        self.setHeader(b'Content-Type', b'text/html')
        if self.path.decode() in self.pageHandlers:
            handler = self.pageHandlers[self.path.decode()]
            handler(self) # 调用相应的自定义事件处理器
        else:
            self.setResponseCode(http.NOT_FOUND)
            self.write(b'<h1>Not Found</h1>Sorry, no such page.')
            self.finish() 
Example #14
Source File: t42_http_request.py    From python_web_Crawler_DA_ML_DL with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process(self):
        # print(self.path) # 可以打印尝试并和浏览器发送的地址做对比, self.path是bytes型哦,注意有些地方解码哦
        if self.path.decode() in self.pages: # 判断请求路径并发送相应的信息
            self.write(self.pages[self.path.decode()].encode())
        else: # 不存在的返回404并输出不存在信息
            self.setResponseCode(http.NOT_FOUND)  # 设置响应状态码
            self.write('<h1>Not Found</h1>Sorry, no such page.'.encode())
        self.finish() # 告知响应已完成 
Example #15
Source File: error.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, code, message=None, response=None):
        """
        Initializes a basic exception.

        @type code: C{str}
        @param code: Refers to an HTTP status code, for example
            L{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to a
            descriptive string that is used instead.

        @type message: C{str}
        @param message: A short error message, for example "NOT FOUND".

        @type response: C{str}
        @param response: A complete HTML document for an error page.
        """
        if not message:
            try:
                message = http.responses.get(int(code))
            except ValueError:
                # If code wasn't a stringified int, can't map the
                # status code to a descriptive string so keep message
                # unchanged.
                pass

        Exception.__init__(self, code, message, response)
        self.status = code
        self.message = message
        self.response = response 
Example #16
Source File: error.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, code, message=None, response=None, location=None):
        """
        Initializes a page redirect exception.

        @type code: C{str}
        @param code: Refers to an HTTP status code, for example
            L{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to a
            descriptive string that is used instead.

        @type message: C{str}
        @param message: A short error message, for example "NOT FOUND".

        @type response: C{str}
        @param response: A complete HTML document for an error page.

        @type location: C{str}
        @param location: The location response-header field value. It is an
            absolute URI used to redirect the receiver to a location other than
            the Request-URI so the request can be completed.
        """
        if not message:
            try:
                message = http.responses.get(int(code))
            except ValueError:
                # If code wasn't a stringified int, can't map the
                # status code to a descriptive string so keep message
                # unchanged.
                pass

        if location and message:
            message = "%s to %s" % (message, location)

        Error.__init__(self, code, message, response)
        self.location = location 
Example #17
Source File: error.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, code, message=None, response=None, location=None):
        """
        Initializes an infinite redirection exception.

        @type code: C{str}
        @param code: Refers to an HTTP status code, for example
            L{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to a
            descriptive string that is used instead.

        @type message: C{str}
        @param message: A short error message, for example "NOT FOUND".

        @type response: C{str}
        @param response: A complete HTML document for an error page.

        @type location: C{str}
        @param location: The location response-header field value. It is an
            absolute URI used to redirect the receiver to a location other than
            the Request-URI so the request can be completed.
        """
        if not message:
            try:
                message = http.responses.get(int(code))
            except ValueError:
                # If code wasn't a stringified int, can't map the
                # status code to a descriptive string so keep message
                # unchanged.
                pass

        if location and message:
            message = "%s to %s" % (message, location)

        Error.__init__(self, code, message, response)
        self.location = location 
Example #18
Source File: test_script.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_render(self):
        """
        L{ResourceScriptDirectory.render} sets the HTTP response code to I{NOT
        FOUND}.
        """
        resource = ResourceScriptDirectory(self.mktemp())
        request = DummyRequest([''])
        d = _render(resource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #19
Source File: test_cgi.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_render(self):
        """
        L{twcgi.CGIDirectory.render} sets the HTTP response code to I{NOT
        FOUND}.
        """
        resource = twcgi.CGIDirectory(self.mktemp())
        request = DummyRequest([''])
        d = _render(resource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #20
Source File: test_resource.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_noResourceRendering(self):
        """
        L{NoResource} sets the HTTP I{NOT FOUND} code.
        """
        detail = "long message"
        page = self.noResource(detail)
        self._pageRenderingTest(page, NOT_FOUND, "No Such Resource", detail) 
Example #21
Source File: test_static.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_childrenNotFound(self):
        """
        Any child resource of L{static.DirectoryLister} renders an HTTP
        I{NOT FOUND} response code.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        lister = static.DirectoryLister(path.path)
        request = self._request('')
        child = resource.getChildForRequest(lister, request)
        result = _render(child, request)
        def cbRendered(ignored):
            self.assertEquals(request.responseCode, http.NOT_FOUND)
        result.addCallback(cbRendered)
        return result 
Example #22
Source File: test_vhost.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_renderWithoutHostNoDefault(self):
        """
        L{NameVirtualHost.render} returns a response with a status of I{NOT
        FOUND} if the instance's C{default} is C{None} and there is no I{Host}
        header in the request.
        """
        virtualHostResource = NameVirtualHost()
        request = DummyRequest([''])
        d = _render(virtualHostResource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #23
Source File: test_vhost.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_renderWithUnknownHostNoDefault(self):
        """
        L{NameVirtualHost.render} returns a response with a status of I{NOT
        FOUND} if the instance's C{default} is C{None} and there is no host
        matching the value of the I{Host} header in the request.
        """
        virtualHostResource = NameVirtualHost()
        request = DummyRequest([''])
        request.headers['host'] = 'example.com'
        d = _render(virtualHostResource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #24
Source File: resource.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, message="Sorry. No luck finding that resource."):
        ErrorPage.__init__(self, http.NOT_FOUND,
                           "No Such Resource",
                           message) 
Example #25
Source File: error.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, message="Sorry. No luck finding that resource."):
        ErrorPage.__init__(self, http.NOT_FOUND,
                           "No Such Resource",
                           message) 
Example #26
Source File: test_api.py    From worker with GNU General Public License v3.0 5 votes vote down vote up
def testTriggerNotFound(self):
        response, body = yield self.request('GET', 'trigger/{0}'.format(self.trigger.id), state=http.NOT_FOUND) 
Example #27
Source File: trigger.py    From worker with GNU General Public License v3.0 5 votes vote down vote up
def render_GET(self, request):
        json, trigger = yield self.db.getTrigger(self.trigger_id)
        if json is None:
            request.setResponseCode(http.NOT_FOUND)
            request.finish()
        else:
            throttling = yield self.db.getTriggerThrottling(self.trigger_id)
            trigger["throttling"] = throttling
            self.write_json(request, trigger) 
Example #28
Source File: script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #29
Source File: test_script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_renderNotFound(self):
        """
        L{ResourceScriptDirectory.render} sets the HTTP response code to I{NOT
        FOUND}.
        """
        resource = ResourceScriptDirectory(self.mktemp())
        request = DummyRequest([b''])
        d = _render(resource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d 
Example #30
Source File: test_script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_notFoundRender(self):
        """
        If the source file a L{PythonScript} is initialized with doesn't exist,
        L{PythonScript.render} sets the HTTP response code to I{NOT FOUND}.
        """
        resource = PythonScript(self.mktemp(), None)
        request = DummyRequest([b''])
        d = _render(resource, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, NOT_FOUND)
        d.addCallback(cbRendered)
        return d