编写出色的Twisted Web资源 [英] Writing excellent Twisted web Resources

查看:122
本文介绍了编写出色的Twisted Web资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了第一篇Twisted 10.1.0网页资源,我正在寻求反馈,因为我觉得这并不完全符合最佳做法,可能包含新手错误。

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.

资源响应 /?url=http://www.foo.baz/abc123 和依赖于返回 dict 的服务。如果出现任何问题(例如,无效或不存在 url ,则返回 400 )。

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


推荐答案

你不会如果设置 isLeaf = True

这篇关于编写出色的Twisted Web资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆