Uh oh!
There was an error while loading. Please reload this page.
forked from ajaxorg/ace
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic.py
More file actions
Latest commit
executable file
·242 lines (198 loc) · 8.24 KB
/
Copy pathstatic.py
File metadata and controls
executable file
·242 lines (198 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python
"""static - A stupidly simple WSGI way to serve static (or mixed) content.
(See the docstrings of the various functions and classes.)
Copyright (C) 2006-2009 Luke Arno - http://lukearno.com/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to:
The Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Luke Arno can be found at http://lukearno.com/
"""
importmimetypes
importrfc822
importtime
importstring
importsys
fromosimportpath, stat, getcwd
fromwsgirefimportutil
fromwsgiref.headersimportHeaders
fromwsgiref.simple_serverimportmake_server
fromoptparseimportOptionParser
try: frompkg_resourcesimportresource_filename, Requirement
except: pass
try: importkid
except: pass
classMagicError(Exception): pass
classStatusApp:
"""Used by WSGI apps to return some HTTP status."""
def__init__(self, status, message=None):
self.status=status
ifmessageisNone:
self.message=status
else:
self.message=message
def__call__(self, environ, start_response, headers=[]):
ifself.message:
Headers(headers).add_header('Content-type', 'text/plain')
start_response(self.status, headers)
ifenviron['REQUEST_METHOD'] =='HEAD':
return [""]
else:
return [self.message]
classCling(object):
"""A stupidly simple way to serve static content via WSGI.
Serve the file of the same path as PATH_INFO in self.datadir.
Look up the Content-type in self.content_types by extension
or use 'text/plain' if the extension is not found.
Serve up the contents of the file or delegate to self.not_found.
"""
block_size=16*4096
index_file='index.html'
not_found=StatusApp('404 Not Found')
not_modified=StatusApp('304 Not Modified', "")
moved_permanently=StatusApp('301 Moved Permanently')
method_not_allowed=StatusApp('405 Method Not Allowed')
def__init__(self, root, **kw):
"""Just set the root and any other attribs passes via **kw."""
self.root=root
fork, vinkw.iteritems():
setattr(self, k, v)
def__call__(self, environ, start_response):
"""Respond to a request when called in the usual WSGI way."""
ifenviron['REQUEST_METHOD'] notin ('GET', 'HEAD'):
headers= [('Allow', 'GET, HEAD')]
returnself.method_not_allowed(environ, start_response, headers)
path_info=environ.get('PATH_INFO', '')
full_path=self._full_path(path_info)
ifnotself._is_under_root(full_path):
returnself.not_found(environ, start_response)
ifpath.isdir(full_path):
iffull_path[-1] <>'/'orfull_path==self.root:
location=util.request_uri(environ, include_query=False) +'/'
ifenviron.get('QUERY_STRING'):
location+='?'+environ.get('QUERY_STRING')
headers= [('Location', location)]
returnself.moved_permanently(environ, start_response, headers)
else:
full_path=self._full_path(path_info+self.index_file)
content_type=self._guess_type(full_path)
try:
etag, last_modified=self._conditions(full_path, environ)
headers= [('Date', rfc822.formatdate(time.time())),
('Last-Modified', last_modified),
('ETag', etag)]
if_modified=environ.get('HTTP_IF_MODIFIED_SINCE')
ifif_modifiedand (rfc822.parsedate(if_modified)
>=rfc822.parsedate(last_modified)):
returnself.not_modified(environ, start_response, headers)
if_none=environ.get('HTTP_IF_NONE_MATCH')
ifif_noneand (if_none=='*'oretaginif_none):
returnself.not_modified(environ, start_response, headers)
file_like=self._file_like(full_path)
headers.append(('Content-Type', content_type))
start_response("200 OK", headers)
ifenviron['REQUEST_METHOD'] =='GET':
returnself._body(full_path, environ, file_like)
else:
return ['']
except (IOError, OSError), e:
printe
returnself.not_found(environ, start_response)
def_full_path(self, path_info):
"""Return the full path from which to read."""
returnself.root+path_info
def_is_under_root(self, full_path):
"""Guard against arbitrary file retrieval."""
if (path.abspath(full_path) +path.sep)\
.startswith(path.abspath(self.root) +path.sep):
returnTrue
else:
returnFalse
def_guess_type(self, full_path):
"""Guess the mime type using the mimetypes module."""
returnmimetypes.guess_type(full_path)[0] or'text/plain'
def_conditions(self, full_path, environ):
"""Return a tuple of etag, last_modified by mtime from stat."""
mtime=stat(full_path).st_mtime
returnstr(mtime), rfc822.formatdate(mtime)
def_file_like(self, full_path):
"""Return the appropriate file object."""
returnopen(full_path, 'rb')
def_body(self, full_path, environ, file_like):
"""Return an iterator over the body of the response."""
way_to_send=environ.get('wsgi.file_wrapper', iter_and_close)
returnway_to_send(file_like, self.block_size)
defiter_and_close(file_like, block_size):
"""Yield file contents by block then close the file."""
while1:
try:
block=file_like.read(block_size)
ifblock: yieldblock
else: raiseStopIteration
exceptStopIteration, si:
file_like.close()
return
defcling_wrap(package_name, dir_name, **kw):
"""Return a Cling that serves from the given package and dir_name.
This uses pkg_resources.resource_filename which is not the
recommended way, since it extracts the files.
I think this works fine unless you have some _very_ serious
requirements for static content, in which case you probably
shouldn't be serving it through a WSGI app, IMHO. YMMV.
"""
resource=Requirement.parse(package_name)
returnCling(resource_filename(resource, dir_name), **kw)
defcommand():
parser=OptionParser(usage="%prog DIR [HOST][:][PORT]",
version="static 0.3.6")
options, args=parser.parse_args()
iflen(args) in (1, 2):
iflen(args) ==2:
parts=args[1].split(":")
iflen(parts) ==1:
host=parts[0]
port=None
eliflen(parts) ==2:
host, port=parts
else:
sys.exit("Invalid host:port specification.")
eliflen(args) ==1:
host, port=None, None
ifnothost:
host='0.0.0.0'
ifnotport:
port=8888
try:
port=int(port)
except:
sys.exit("Invalid host:port specification.")
app=Cling(args[0])
try:
make_server(host, port, app).serve_forever()
exceptKeyboardInterrupt, ki:
print"Cio, baby!"
except:
sys.exit("Problem initializing server.")
else:
parser.print_help(sys.stderr)
sys.exit(1)
deftest():
fromwsgiref.validateimportvalidator
app=Cling(getcwd())
try:
print"Serving "+getcwd() +" to http://localhost:8888"
make_server('0.0.0.0', 8888, validator(app)).serve_forever()
exceptKeyboardInterrupt, ki:
print""
print"Ciao, baby!"
if__name__=='__main__':
test()