Writing excellent Twisted web Resources

2019-05-27 02:55发布

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条回答
Animai°情兽
2楼-- · 2019-05-27 03:03

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

查看更多
登录 后发表回答