Writing excellent Twisted web Resources

十年热恋 提交于 2019-12-10 10:56:15

问题


I wrote my very first Twisted 10.1.0 web Resource and I am seeking for feedback, because I feel this isn't exactly following the best practice and may contain newbies bugs.

The resource responds to /?url=http://www.foo.baz/abc123 and relies on a service that returns a dict. If anything goes wrong (e.g., invalid or non-existing url, then a 400 is returned).

Any comment? Anything to fix, to improve

class ProcessedUrl(resource.Resource):
    isLeaf = True

    def __init__(self, service):
        resource.Resource.__init__(self)
        self.service = service

    def _cancel(self, err, deferred):
        deferred.cancel()

    def _write(self, value, request):
        request.setResponseCode(http.OK)
        request.write(json.dumps(value))
        request.finish()

    def _cleanUrl(self, url):
        return cleanUrl(url)

    def _checkUrl(self, url):
        if url is not None:
            if isValidUrl(url):
                return True
        return False

    def render_GET(self, request):
        request.setResponseCode(http.BAD_REQUEST)
        url = request.args.get('url', [None])[0]

        if self._checkUrl(url):
            url = self._cleanUrl(url)
            d = self.service.processUrl(url)
            request.notifyFinish().addErrback(self._cancel, d)
            d.addCallback(_write)
            d.addErrback(log.err)
        else:
            return 'Invalid or no URL.'
        return server.NOT_DONE_YET

    def getChild(self, name, request):
        return self

回答1:


I think you wouldn't need to explicitly override getChild() if you set isLeaf=True



来源:https://stackoverflow.com/questions/4287310/writing-excellent-twisted-web-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!