编写优秀的 Twisted 网络资源
我编写了第一个 Twisted 10.1.0 Web Resource
,并且正在寻求反馈,因为我觉得这并不完全遵循最佳实践,并且可能包含新手错误。
该资源响应 /?url=http://www.foo.baz/abc123
并依赖于返回 dict
的服务。如果出现任何问题(例如,url
无效或不存在,则返回 400
)。
有什么意见吗?任何需要修复、改进的地方
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果设置
isLeaf=True
,则不需要显式重写getChild()
I think you wouldn't need to explicitly override
getChild()
if you setisLeaf=True