• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

twisted / twisted / 1

22 Jul 2021 06:33AM UTC coverage: 80.076% (-2.3%) from 82.403%
1

push

github

web-flow
Merge branch 'trunk' into trunk

27108 of 35905 branches covered (75.5%)

1810 of 1944 new or added lines in 189 files covered. (93.11%)

119955 of 149802 relevant lines covered (80.08%)

0.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.16
/src/twisted/web/script.py
1
# -*- test-case-name: twisted.web.test.test_script -*-
2
# Copyright (c) Twisted Matrix Laboratories.
3
# See LICENSE for details.
4

5
"""
1✔
6
I contain PythonScript, which is a very simple python script resource.
7
"""
8

9

10
import os
1✔
11
import traceback
1✔
12
from io import StringIO
1✔
13

14
from twisted import copyright
1✔
15
from twisted.python.filepath import _coerceToFilesystemEncoding
1✔
16
from twisted.python.compat import execfile, networkString
1✔
17
from twisted.web import http, server, static, resource, util
1✔
18

19

20
rpyNoResource = """<p>You forgot to assign to the variable "resource" in your script. For example:</p>
1✔
21
<pre>
22
# MyCoolWebApp.rpy
23

24
import mygreatresource
25

26
resource = mygreatresource.MyGreatResource()
27
</pre>
28
"""
29

30

31
class AlreadyCached(Exception):
1✔
32
    """
33
    This exception is raised when a path has already been cached.
34
    """
35

36

37
class CacheScanner:
1✔
38
    def __init__(self, path, registry):
1✔
39
        self.path = path
1✔
40
        self.registry = registry
1✔
41
        self.doCache = 0
1✔
42

43
    def cache(self):
1✔
44
        c = self.registry.getCachedPath(self.path)
×
45
        if c is not None:
×
46
            raise AlreadyCached(c)
×
47
        self.recache()
×
48

49
    def recache(self):
1✔
50
        self.doCache = 1
×
51

52

53
noRsrc = resource.ErrorPage(500, "Whoops! Internal Error", rpyNoResource)
1✔
54

55

56
def ResourceScript(path, registry):
1✔
57
    """
58
    I am a normal py file which must define a 'resource' global, which should
59
    be an instance of (a subclass of) web.resource.Resource; it will be
60
    renderred.
61
    """
62
    cs = CacheScanner(path, registry)
1✔
63
    glob = {
1✔
64
        "__file__": _coerceToFilesystemEncoding("", path),
65
        "resource": noRsrc,
66
        "registry": registry,
67
        "cache": cs.cache,
68
        "recache": cs.recache,
69
    }
70
    try:
1✔
71
        execfile(path, glob, glob)
1✔
72
    except AlreadyCached as ac:
×
73
        return ac.args[0]
×
74
    rsrc = glob["resource"]
1✔
75
    if cs.doCache and rsrc is not noRsrc:
1!
76
        registry.cachePath(path, rsrc)
×
77
    return rsrc
1✔
78

79

80
def ResourceTemplate(path, registry):
1✔
NEW
81
    from quixote import ptl_compile  # type: ignore[import]
×
82

83
    glob = {
×
84
        "__file__": _coerceToFilesystemEncoding("", path),
85
        "resource": resource.ErrorPage(500, "Whoops! Internal Error", rpyNoResource),
86
        "registry": registry,
87
    }
88

89
    with open(path) as f:  # Not closed by quixote as of 2.9.1
×
90
        e = ptl_compile.compile_template(f, path)
×
91
    code = compile(e, "<source>", "exec")
×
92
    eval(code, glob, glob)
×
93
    return glob["resource"]
×
94

95

96
class ResourceScriptWrapper(resource.Resource):
1✔
97
    def __init__(self, path, registry=None):
1✔
98
        resource.Resource.__init__(self)
×
99
        self.path = path
×
100
        self.registry = registry or static.Registry()
×
101

102
    def render(self, request):
1✔
103
        res = ResourceScript(self.path, self.registry)
×
104
        return res.render(request)
×
105

106
    def getChildWithDefault(self, path, request):
1✔
107
        res = ResourceScript(self.path, self.registry)
×
108
        return res.getChildWithDefault(path, request)
×
109

110

111
class ResourceScriptDirectory(resource.Resource):
1✔
112
    """
113
    L{ResourceScriptDirectory} is a resource which serves scripts from a
114
    filesystem directory.  File children of a L{ResourceScriptDirectory} will
115
    be served using L{ResourceScript}.  Directory children will be served using
116
    another L{ResourceScriptDirectory}.
117

118
    @ivar path: A C{str} giving the filesystem path in which children will be
119
        looked up.
120

121
    @ivar registry: A L{static.Registry} instance which will be used to decide
122
        how to interpret scripts found as children of this resource.
123
    """
124

125
    def __init__(self, pathname, registry=None):
1✔
126
        resource.Resource.__init__(self)
1✔
127
        self.path = pathname
1✔
128
        self.registry = registry or static.Registry()
1✔
129

130
    def getChild(self, path, request):
1✔
131
        fn = os.path.join(self.path, path)
1✔
132

133
        if os.path.isdir(fn):
1!
134
            return ResourceScriptDirectory(fn, self.registry)
×
135
        if os.path.exists(fn):
1✔
136
            return ResourceScript(fn, self.registry)
1✔
137
        return resource.NoResource()
1✔
138

139
    def render(self, request):
1✔
140
        return resource.NoResource().render(request)
1✔
141

142

143
class PythonScript(resource.Resource):
1✔
144
    """
145
    I am an extremely simple dynamic resource; an embedded python script.
146

147
    This will execute a file (usually of the extension '.epy') as Python code,
148
    internal to the webserver.
149
    """
150

151
    isLeaf = True
1✔
152

153
    def __init__(self, filename, registry):
1✔
154
        """
155
        Initialize me with a script name.
156
        """
157
        self.filename = filename
1✔
158
        self.registry = registry
1✔
159

160
    def render(self, request):
1✔
161
        """
162
        Render me to a web client.
163

164
        Load my file, execute it in a special namespace (with 'request' and
165
        '__file__' global vars) and finish the request.  Output to the web-page
166
        will NOT be handled with print - standard output goes to the log - but
167
        with request.write.
168
        """
169
        request.setHeader(
1✔
170
            b"x-powered-by", networkString("Twisted/%s" % copyright.version)
171
        )
172
        namespace = {
1✔
173
            "request": request,
174
            "__file__": _coerceToFilesystemEncoding("", self.filename),
175
            "registry": self.registry,
176
        }
177
        try:
1✔
178
            execfile(self.filename, namespace, namespace)
1✔
179
        except OSError as e:
1✔
180
            if e.errno == 2:  # file not found
1!
181
                request.setResponseCode(http.NOT_FOUND)
1✔
182
                request.write(resource.NoResource("File not found.").render(request))
1✔
183
        except BaseException:
1✔
184
            io = StringIO()
1✔
185
            traceback.print_exc(file=io)
1✔
186
            output = util._PRE(io.getvalue())
1✔
187
            output = output.encode("utf8")
1✔
188
            request.write(output)
1✔
189
        request.finish()
1✔
190
        return server.NOT_DONE_YET
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc