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
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