script.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # -*- test-case-name: twisted.web.test.test_script -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. I contain PythonScript, which is a very simple python script resource.
  6. """
  7. import os
  8. import traceback
  9. from io import StringIO
  10. from twisted import copyright
  11. from twisted.python.compat import execfile, networkString
  12. from twisted.python.filepath import _coerceToFilesystemEncoding
  13. from twisted.web import http, resource, server, static, util
  14. rpyNoResource = """<p>You forgot to assign to the variable "resource" in your script. For example:</p>
  15. <pre>
  16. # MyCoolWebApp.rpy
  17. import mygreatresource
  18. resource = mygreatresource.MyGreatResource()
  19. </pre>
  20. """
  21. class AlreadyCached(Exception):
  22. """
  23. This exception is raised when a path has already been cached.
  24. """
  25. class CacheScanner:
  26. def __init__(self, path, registry):
  27. self.path = path
  28. self.registry = registry
  29. self.doCache = 0
  30. def cache(self):
  31. c = self.registry.getCachedPath(self.path)
  32. if c is not None:
  33. raise AlreadyCached(c)
  34. self.recache()
  35. def recache(self):
  36. self.doCache = 1
  37. noRsrc = resource._UnsafeErrorPage(500, "Whoops! Internal Error", rpyNoResource)
  38. def ResourceScript(path, registry):
  39. """
  40. I am a normal py file which must define a 'resource' global, which should
  41. be an instance of (a subclass of) web.resource.Resource; it will be
  42. renderred.
  43. """
  44. cs = CacheScanner(path, registry)
  45. glob = {
  46. "__file__": _coerceToFilesystemEncoding("", path),
  47. "resource": noRsrc,
  48. "registry": registry,
  49. "cache": cs.cache,
  50. "recache": cs.recache,
  51. }
  52. try:
  53. execfile(path, glob, glob)
  54. except AlreadyCached as ac:
  55. return ac.args[0]
  56. rsrc = glob["resource"]
  57. if cs.doCache and rsrc is not noRsrc:
  58. registry.cachePath(path, rsrc)
  59. return rsrc
  60. def ResourceTemplate(path, registry):
  61. from quixote import ptl_compile
  62. glob = {
  63. "__file__": _coerceToFilesystemEncoding("", path),
  64. "resource": resource._UnsafeErrorPage(
  65. 500, "Whoops! Internal Error", rpyNoResource
  66. ),
  67. "registry": registry,
  68. }
  69. with open(path) as f: # Not closed by quixote as of 2.9.1
  70. e = ptl_compile.compile_template(f, path)
  71. code = compile(e, "<source>", "exec")
  72. eval(code, glob, glob)
  73. return glob["resource"]
  74. class ResourceScriptWrapper(resource.Resource):
  75. def __init__(self, path, registry=None):
  76. resource.Resource.__init__(self)
  77. self.path = path
  78. self.registry = registry or static.Registry()
  79. def render(self, request):
  80. res = ResourceScript(self.path, self.registry)
  81. return res.render(request)
  82. def getChildWithDefault(self, path, request):
  83. res = ResourceScript(self.path, self.registry)
  84. return res.getChildWithDefault(path, request)
  85. class ResourceScriptDirectory(resource.Resource):
  86. """
  87. L{ResourceScriptDirectory} is a resource which serves scripts from a
  88. filesystem directory. File children of a L{ResourceScriptDirectory} will
  89. be served using L{ResourceScript}. Directory children will be served using
  90. another L{ResourceScriptDirectory}.
  91. @ivar path: A C{str} giving the filesystem path in which children will be
  92. looked up.
  93. @ivar registry: A L{static.Registry} instance which will be used to decide
  94. how to interpret scripts found as children of this resource.
  95. """
  96. def __init__(self, pathname, registry=None):
  97. resource.Resource.__init__(self)
  98. self.path = pathname
  99. self.registry = registry or static.Registry()
  100. def getChild(self, path, request):
  101. fn = os.path.join(self.path, path)
  102. if os.path.isdir(fn):
  103. return ResourceScriptDirectory(fn, self.registry)
  104. if os.path.exists(fn):
  105. return ResourceScript(fn, self.registry)
  106. return resource._UnsafeNoResource()
  107. def render(self, request):
  108. return resource._UnsafeNoResource().render(request)
  109. class PythonScript(resource.Resource):
  110. """
  111. I am an extremely simple dynamic resource; an embedded python script.
  112. This will execute a file (usually of the extension '.epy') as Python code,
  113. internal to the webserver.
  114. """
  115. isLeaf = True
  116. def __init__(self, filename, registry):
  117. """
  118. Initialize me with a script name.
  119. """
  120. self.filename = filename
  121. self.registry = registry
  122. def render(self, request):
  123. """
  124. Render me to a web client.
  125. Load my file, execute it in a special namespace (with 'request' and
  126. '__file__' global vars) and finish the request. Output to the web-page
  127. will NOT be handled with print - standard output goes to the log - but
  128. with request.write.
  129. """
  130. request.setHeader(
  131. b"x-powered-by", networkString("Twisted/%s" % copyright.version)
  132. )
  133. namespace = {
  134. "request": request,
  135. "__file__": _coerceToFilesystemEncoding("", self.filename),
  136. "registry": self.registry,
  137. }
  138. try:
  139. execfile(self.filename, namespace, namespace)
  140. except OSError as e:
  141. if e.errno == 2: # file not found
  142. request.setResponseCode(http.NOT_FOUND)
  143. request.write(
  144. resource._UnsafeNoResource("File not found.").render(request)
  145. )
  146. except BaseException:
  147. io = StringIO()
  148. traceback.print_exc(file=io)
  149. output = util._PRE(io.getvalue())
  150. output = output.encode("utf8")
  151. request.write(output)
  152. request.finish()
  153. return server.NOT_DONE_YET