You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rewrite.py 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. #
  4. from twisted.web import resource
  5. class RewriterResource(resource.Resource):
  6. def __init__(self, orig, *rewriteRules):
  7. resource.Resource.__init__(self)
  8. self.resource = orig
  9. self.rewriteRules = list(rewriteRules)
  10. def _rewrite(self, request):
  11. for rewriteRule in self.rewriteRules:
  12. rewriteRule(request)
  13. def getChild(self, path, request):
  14. request.postpath.insert(0, path)
  15. request.prepath.pop()
  16. self._rewrite(request)
  17. path = request.postpath.pop(0)
  18. request.prepath.append(path)
  19. return self.resource.getChildWithDefault(path, request)
  20. def render(self, request):
  21. self._rewrite(request)
  22. return self.resource.render(request)
  23. def tildeToUsers(request):
  24. if request.postpath and request.postpath[0][:1]=='~':
  25. request.postpath[:1] = ['users', request.postpath[0][1:]]
  26. request.path = '/'+'/'.join(request.prepath+request.postpath)
  27. def alias(aliasPath, sourcePath):
  28. """
  29. I am not a very good aliaser. But I'm the best I can be. If I'm
  30. aliasing to a Resource that generates links, and it uses any parts
  31. of request.prepath to do so, the links will not be relative to the
  32. aliased path, but rather to the aliased-to path. That I can't
  33. alias static.File directory listings that nicely. However, I can
  34. still be useful, as many resources will play nice.
  35. """
  36. sourcePath = sourcePath.split('/')
  37. aliasPath = aliasPath.split('/')
  38. def rewriter(request):
  39. if request.postpath[:len(aliasPath)] == aliasPath:
  40. after = request.postpath[len(aliasPath):]
  41. request.postpath = sourcePath + after
  42. request.path = '/'+'/'.join(request.prepath+request.postpath)
  43. return rewriter