54. Usage: ultima.py [OPTIONS] [--name=value...] <required> [value...]
OPTIONS may be one or more of:
-a, --age=VAL Override this value.
Default: 18
-h, --help Display this help and exit.
-n, --name=VAL Override this value.
Default: 'world'
-s, --switch Toggle this value.
Default: False
-v, --value=VAL Set this value.
111. 1 class Tag(Fragment):
2 def __call__(self, data_=None, strip=NoDefault, *args, **kw):
3 self = deepcopy(self)
4
5 self.data = data_
6 if strip is not NoDefault: self.strip = strip
7 self.args.extend(list(args))
8 self.attrs.update(kw)
9
10 return self
112. 12 def __getitem__(self, k):
13 if not k: return self
14
15 self = deepcopy(self)
16
17 if not isinstance(k, (tuple, list)):
18 k = [k]
19
20 for fragment in k:
21 if isinstance(fragment, basestring):
22 self.children.append(escape(fragment))
23 continue
24
25 self.children.append(fragment)
26
27 return self
113. 29 def __unicode__(self):
30 """Return a serialized version of this tree/branch."""
31 return ''.join(self.render('utf8')).decode('utf8')
32
33 def enter(self):
34 if self.strip:
35 raise StopIteration()
36
37 if self.prefix:
38 yield self.prefix
39
40 yield u'<' + self.name + u''.join([attr for attr in quoteattrs(self, self.attrs)]) + u'>'
41
42 def exit(self):
43 if self.simple or self.strip:
44 raise StopIteration()
45
46 yield u'</' + self.name + u'>'
114. 48 def render(self, encoding='ascii'):
49 # ...
50
51 for k, t in self:
52 if k == 'enter':
53 # ...
54 continue
55
56 if k == 'exit':
57 # ...
58 continue
59
60 if k == 'text':
61 # ...
62 continue
63
64 if k == 'flush':
65 yield buf.getvalue()
66 del buf
67 buf = IO()
68
69 yield buf.getvalue()
115. 71 def __iter__(self):
72 yield 'enter', self
73
74 for child in self.children:
75 if isinstance(child, Fragment):
76 for element in child:
77 yield element
78 continue
79
80 if hasattr(child, '__call__'):
81 value = child(self)
82
83 if isinstance(value, basestring):
84 yield 'text', unicode(value)
85 continue
86
87 for element in child(self):
88 yield element
89
90 continue
91
92 yield 'text', unicode(child)
93
94 yield 'exit', self
116. 29 def __unicode__(self):
30 """Return a serialized version of this tree/branch."""
31 return ''.join(self.render('utf8')).decode('utf8')
96 def clear(self):
97 self.children = list()
98 self.args = list()
99 self.attrs = dict()
100
100 def empty(self):
101 self.children = list()
156. An application is any function, method, or instance with a __call__ method. Applications must:
1. Be able to be invoked more than once. If this can not be guaranteed by the application implementation, it must be wrapped in a function
that creates a new instance on each call.
2. Accept a single positional argument which must be an instance of a base Python dictionary containing what is referred to as the WSGI
environment. The contents of this dictionary are fully described in the WSGI Environment section.
3. Return a 3-tuple of (status, headers, body) where:
1.status must contain the HTTP status code and reason phrase of the response. The status code and reason must be present, in that
order, separated by a single space. (See RFC 2616, Section 6.1.1 for more information.)
2.headers must be a standard Python list containing 2-tuples of (name, value) pairs representing the HTTP headers of the response. Each
header name must represent a valid HTTP header field name (as defined by RFC 2616, Section 4.2) without trailing colon or other
punctuation.
3.body must be an iterable representing the HTTP response body.
4.status and the name of each header present in headers must not have leading or trailing whitespace.
5.status, and the contents of headers (both name and value) must not contain control characters including carriage returns or linefeeds.
6.status, headers, and the chunks yielded by the body iterator should be returned as byte strings, though for implementations where
native strings are unicode, native strings may be returned. The server must encode unicode values using ISO-8859-1.
7. The amount of data yielded by the body iterable must not exceed the length specified by the Content-Length response header, if
defined.
8. The body iterable may be a native string, instead of a native string wrapped in a list for the simple case, but this is not recommended.
Additionally, applications and middleware must not alter HTTP 1.1 "hop-by-hop" features or headers, any equivalent features in HTTP 1.0, or
any headers that would affect the persistence of the client's connection to the web server. Applications and middleware may, however,
interrogate the environment for their presence and value. These features are the exclusive province of the server, and a server should consider
it a fatal error for an application to attempt sending them, and raise an error if they are supplied as return values from an application in the
headers structure.
158. A WSGI 2 server must:
1. Invoke the application callable once for each request it receives from an HTTP client that is directed at the application.
2. Pass a single positional value to the application callable representing the request environment, described in detail in the WSGI Environment
section.
3. Ensure that correct response headers are sent to the client. If the application omits a header required by the HTTP standard (or other relevant
specifications that are in effect), the server must add it. E.g. the Date and Server headers.
1. The server must not override values with the same name if they are emitted by the application.
4. Raise an exception if the application attempts to set HTTP 1.1 "hop-by-hop" or persistence headers, or equivalent headers in HTTP 1.0, as
described above.
5. Encode unicode data (where returned by the application) using ISO-8859-1.
6. Ensure that line endings within the body are not altered.
7. Transmit body chunks to the client in an unbuffered fashion, completing the transmission of each set of bytes before requesting another one.
(Applications should perform their own buffering.)
8. Call the close() method of the body returned by the application, if present, upon completion of the current request. This should be called
regardless of the termination status of the request. This is to support resource release by the application and is intended to complement PEP
325's generator support, and other common iterables with close() methods.
9. Support the HTTP 1.1 specification where such support is made possible by the underlying transport channel, including full URL REQUEST_URI,
pipelining of requests, chunked transfer, and any other HTTP 1.1 features mandated in the relevant RFC.
Additionally,
1. HTTP header names are case-insensitive, so be sure to take that into consideration when examining application-supplied headers.
2. The server may apply HTTP transfer encodings or perform other transformations for the purpose of implementing HTTP features such as
chunked transfer.
3. The server must not attempt to handle byte range requests; the application can optimize this use case far more easily than a server. (For example
an application can generate the correct body length vs. generating the whole body and having the server buffer and slice it.)
4. Servers must not directly use any other attributes of the body iterable returned by the application.
208. 38 class CompressionFilter(object):
39 def __init__(self, level=6):
40 self.level = level
41
42 super(CompressionFilter, self).__init__()
43
44 def __call__(self, request, status, headers, body):
45 """Compress, if able, the response.
46
47 This has the side effect that if your application does not declare a content-length, this filter will.
48 """
49
50 # TODO: Remove some of this debug logging; it'll slow things down and isn't really needed.
51
52 if request.get('wsgi.compression', True) is False:
53 log.debug("Bypassing compression at application's request.")
54 return status, headers, body
55
56 if request.get('wsgi.async') and hasattr(body, '__call__'):
57 log.debug("Can not compress async responses, returning original response.")
58 return status, headers, body
59
60 if b'gzip' not in request.get('HTTP_ACCEPT_ENCODING', b''):
61 log.debug("Browser support for GZip encoding not found, returning original response.")
62 return status, headers, body
209. 38 class CompressionFilter(object):
39 def __init__(self, level=6):
40 self.level = level
41
42 super(CompressionFilter, self).__init__()
43
44 def __call__(self, request, status, headers, body):
45 """Compress, if able, the response.
46
47 This has the side effect that if your application does not declare a content-length, this filter will.
48 """
49
50 # TODO: Remove some of this debug logging; it'll slow things down and isn't really needed.
51
52 if request.get('wsgi.compression', True) is False:
53 log.debug("Bypassing compression at application's request.")
54 return status, headers, body
55
56 if request.get('wsgi.async') and hasattr(body, '__call__'):
57 log.debug("Can not compress async responses, returning original response.")
58 return status, headers, body
59
60 if b'gzip' not in request.get('HTTP_ACCEPT_ENCODING', b''):
61 log.debug("Browser support for GZip encoding not found, returning original response.")
62 return status, headers, body
210. 38 class CompressionFilter(object):
39 def __init__(self, level=6):
40 self.level = level
41
42 super(CompressionFilter, self).__init__()
43
44 def __call__(self, request, status, headers, body):
45 """Compress, if able, the response.
46
47 This has the side effect that if your application does not declare a content-length, this filter will.
48 """
49
50 # TODO: Remove some of this debug logging; it'll slow things down and isn't really needed.
51
52 if request.get('wsgi.compression', True) is False:
53 log.debug("Bypassing compression at application's request.")
54 return status, headers, body
55
56 if request.get('wsgi.async') and hasattr(body, '__call__'):
57 log.debug("Can not compress async responses, returning original response.")
58 return status, headers, body
59
60 if b'gzip' not in request.get('HTTP_ACCEPT_ENCODING', b''):
61 log.debug("Browser support for GZip encoding not found, returning original response.")
62 return status, headers, body
281. Chasing Corporate care of Air Review Relevant Specifications
myspace.com/airreview PEP 333
WSGI 1.0
PEP 391
Dict Logging Configuration
Core Developers PEP 444
WSGI 2.0
Alice Bevan-McGregor PEP 3148
Futures
Alex Grönholm PEP 3333
WSGI 1.1
Resources RFC 1945 — HTTP 1.0
HTTP: The Definitive Guide, David RFC 2616 — HTTP 1.1
Gourley & Brian Totty, O’Reilly Press
Porting to Python 3, Lennart Regebro, Get GA to GA for PyCon!
CreateSpace http://pledgie.com/campaigns/14434