rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
old_query_string = environ['QUERY_STRING']
old_query_string = environ.get('QUERY_STRING','')
def parse_formvars(environ, include_get_vars=True): """Parses the request, returning a MultiDict of form variables. If ``include_get_vars`` is true then GET (query string) variables will also be folded into the MultiDict. All values should be strings, except for file uploads which are left as FieldStorage instances. ...
name, self.template_description().splitlines()[0])
name, self.template_description(dir).splitlines()[0])
def command(self): any = False app_template_dir = os.path.join(os.path.dirname(__file__), 'app_templates') for name in os.listdir(app_template_dir): dir = os.path.join(app_template_dir, name) if not os.path.exists(os.path.join(dir, 'description.txt')): if self.options.verbose >= 2: print 'Skipping %s (no description.tx...
self.name, self.template_description())
self.name, self.template_description(dir))
def command(self): any = False app_template_dir = os.path.join(os.path.dirname(__file__), 'app_templates') for name in os.listdir(app_template_dir): dir = os.path.join(app_template_dir, name) if not os.path.exists(os.path.join(dir, 'description.txt')): if self.options.verbose >= 2: print 'Skipping %s (no description.tx...
def template_description(self): f = open(os.path.join(self.template_dir, 'description.txt'))
def template_description(self, dir): f = open(os.path.join(dir, 'description.txt'))
def template_description(self): f = open(os.path.join(self.template_dir, 'description.txt')) content = f.read().strip() f.close() return content
body = "<html><body>simple</body></html>" start_response("200 OK",[('Content-Type','text/html'), ('Content-Length',len(body))])
length = environ.get('CONTENT_LENGTH', 0) if length and int(length) > self.threshold: self.monitor.append(environ) environ[ENVIRON_RECEIVED] = 0 environ[REQUEST_STARTED] = time.time() environ[REQUEST_FINISHED] = None environ['wsgi.input'] = \ _ProgressFile(environ, environ['wsgi.input']) def finalizer(exc_info=None): ...
def __call__(self, environ, start_response): body = "<html><body>simple</body></html>" start_response("200 OK",[('Content-Type','text/html'), ('Content-Length',len(body))]) return [body]
class SlowConsumer: """ Consumes an upload slowly... NOTE: This should use the iterator form of ``wsgi.input``, but it isn't implemented in paste.httpserver. """ def __init__(self, chunk_size = 4096, delay = 1, progress = True): self.chunk_size = chunk_size self.delay = delay self.progress = True def __call__(self, e...
__all__ = ['UploadProgressMonitor','UploadProgressReporter'] if "__main__" == __name__: import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
def __call__(self, environ, start_response): body = "<html><body>simple</body></html>" start_response("200 OK",[('Content-Type','text/html'), ('Content-Length',len(body))]) return [body]
return self.catching_iter(app_iter, environ)
try: return_iter = list(app_iter) return return_iter finally: if hasattr(app_iter, 'close'): app_iter.close()
def detect_start_response(status, headers, exc_info=None): try: return start_response(status, headers, exc_info) except: raise else: started.append(True)
Example usage:
Example usage::
def / name
"""
doc = """
def Usage(): """ ----------------------------------------------------------------------------- PySourceColor.py ver: %s ----------------------------------------------------------------------------- Module summary: This module is designed to colorize python source code. Input--->python source Output-->colorized (html, h...
print Usage.__doc__% (__version__)
print doc % (__version__)
def Usage(): """ ----------------------------------------------------------------------------- PySourceColor.py ver: %s ----------------------------------------------------------------------------- Module summary: This module is designed to colorize python source code. Input--->python source Output-->colorized (html, h...
newhead = '-'.join(x.capitalize() for x in \ key.replace("_","-").split("-"))
newhead = '-'.join([x.capitalize() for x in \ key.replace("_","-").split("-")])
def normalize_headers(response_headers, strict=True): """ sort headers as suggested by RFC 2616 This alters the underlying response_headers to use the common name for each header; as well as sorting them with general headers first, followed by request/response headers, then entity headers, and unknown headers last. "...
else: del self.close
def next(self): try: return self.app_iter.next() except StopIteration: if self.ok_callback: self.ok_callback() raise except self.catch: if hasattr(self.app_iterable, 'close'): try: self.app_iterable.close() except: # @@: Print to wsgi.errors? pass new_app_iterable = self.error_callback_app( self.environ, self.start_res...
'<a href="http://localhost/view" onclick="return prompt(&quot;\'Really?\'&quot;)">goto</a>'
'<a href="http://localhost/view" onclick="return prompt(\'Really?\')">goto</a>'
def _add_positional(self, args): raise NotImplementedError
attrs.append(('onclick', 'return prompt(%r)'
attrs.append(('onclick', 'return prompt(%s)'
def _html_attrs(self): attrs = self.attrs.items() attrs.insert(0, ('href', self.href)) if self.params.get('confirm'): attrs.append(('onclick', 'return prompt(%r)' % js_repr(self.params['confirm']))) return attrs
return 'location.href=%r; return false' % js_repr(self.href)
return 'location.href=%s; return false' % js_repr(self.href)
def onclick_goto__get(self): return 'location.href=%r; return false' % js_repr(self.href)
print " from paste.cgiserver import run_with_cgi" print " run_with_cgi(app)"
print " from paste.servers.cgi_wsgi import run_with_cgi" print " run_with_cgi(app, redirect_stdout=True)"
def serve(conf, app): replacements = {} replacements['default_config_fn'] = os.path.abspath( server.default_config_fn) # Ideally, other_conf should be any options that came from the # command-line. # @@: This assumes too much about the ordering of namespaces. other_conf = dict(conf.namespaces[-2]) # Not a good idea to...
scgi_server.SCGIServer(SCGIAppHandler, port=port).serve()
kwargs = dict(handler_class=SCGIAppHandler) for kwarg in ('host', 'port', 'max_children'): if locals()[kwarg] is not None: kwargs[kwarg] = locals()[kwarg] scgi_server.SCGIServer(**kwargs).serve()
def __init__ (self, *args, **kwargs): self.prefix = prefix self.app_obj = application SWAP.__init__(self, *args, **kwargs)
if '?' in self.script: assert query_string is None, ( "You cannot have '?' in your script name (%r) and also " "give a query_string (%r)" % (self.script, query_string)) self.script, query_string = self.script.split('?', 1)
def __init__(self, script, path=None, include_os_environ=True, query_string=None): self.script_filename = script if isinstance(path, (str, unicode)): path = [path] if path is None: path = os.environ.get('PATH', '').split(':') self.path = path if os.path.abspath(script) != script: # relative path for path_dir in self.pa...
stdout=CGIWriter(environ, start_response),
stdout=writer,
def __call__(self, environ, start_response): if 'REQUEST_URI' not in environ: environ['REQUEST_URI'] = ( environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')) if self.include_os_environ: cgi_environ = os.environ.copy() else: cgi_environ = {} for name in environ: # Should unicode values be encoded? if (name.upp...
if var_value is not None:
if var_value is not None and var_value is not False:
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None): """ Define a cookie to be sent via the outgoing HTTP headers """ self.cookies[key] = value for var_name, var_value in [ ('max_age', max_age), ('path', path), ('domain', domain), ('secure', secure), ('expires', expires)]...
'instead', DeprecationWarning, 1)
'instead', DeprecationWarning, 2)
def error_body_response(error_code, message, __warn=True): """ Returns a standard HTML response page for an HTTP error. **Note:** Deprecated """ if __warn: warnings.warn( 'wsgilib.error_body_response is deprecated; use the ' 'wsgi_application method on an HTTPException object ' 'instead', DeprecationWarning, 1) return ...
'instead', DeprecationWarning, 1)
'instead', DeprecationWarning, 2)
def error_response(environ, error_code, message, debug_message=None, __warn=True): """ Returns the status, headers, and body of an error response. Use like:: status, headers, body = wsgilib.error_response( '301 Moved Permanently', 'Moved to <a href="%s">%s</a>' % (url, url)) start_response(status, headers) return [bo...
return StaticURLParser(document_root, **kw)
return StaticURLParser( document_root, cache_max_age=cache_max_age)
def make_static(global_conf, document_root, cache_max_age=None): """ Return a WSGI application that serves a directory (configured with document_root) max_cache_age - integer specifies CACHE_CONTROL max_age in seconds """ if cache_max_age is not None: cache_max_age = int(cache_max_age) return StaticURLParser(document_...
list(app_iter)
def change_response(status, headers, exc_info=None): status_code = status.split(' ') try: code = int(status_code[0]) except ValueError, TypeError: raise Exception( 'StatusBasedForward middleware ' 'received an invalid status code %s'%repr(status_code[0]) ) message = ' '.join(status_code[1:]) new_url = self.mapper( cod...
if self.debug: environ['wsgi.errors'].write( '=> paste.errordocuments: -> %r\n'%url[0][0] )
def change_response(status, headers, exc_info=None): status_code = status.split(' ') try: code = int(status_code[0]) except ValueError, TypeError: raise Exception( 'StatusBasedForward middleware ' 'received an invalid status code %s'%repr(status_code[0]) ) message = ' '.join(status_code[1:]) new_url = self.mapper( cod...
files = files or []
if files is None: files = []
def get_data_files(relpath, files=None): files = files or [] for name in os.listdir(os.path.join(BASEDIR, relpath)): if name.startswith("."): continue fn = os.path.join(relpath, name) if os.path.isdir(os.path.join(BASEDIR, fn)): get_data_files(fn, files) elif os.path.isfile(os.path.join(BASEDIR, fn)): files.append(fn) ...
self.headers = None
self.content_length = None
def __init__(self, start_response, compress_level): self.start_response = start_response self.compress_level = compress_level self.buffer = StringIO() self.compressible = False self.headers = None
return self.start_response(status, headers, exc_info)
remove_header(headers, 'content-length') self.headers = headers self.status = status return self.buffer.write
def gzip_start_response(self, status, headers, exc_info=None): self.headers = headers ct = header_value(headers,'content-type') ce = header_value(headers,'content-encoding') self.compressible = False if (ct.startswith('text') or ct.startswith('application')) \ and not 'z' in ct: self.compressible = True if ce: self.com...
if self.compressible and self.headers is not None: CONTENT_LENGTH.update(self.headers, str(len(s)))
def write(self): out = self.buffer out.seek(0) s = out.getvalue() out.close() if self.compressible and self.headers is not None: CONTENT_LENGTH.update(self.headers, str(len(s))) return [s]
prefix = conf.get('scgi_prefix', '/')
prefix = conf.get('root_url', '') while prefix.endswith('/'): prefix = prefix[:-1]
def serve(conf, app): prefix = conf.get('scgi_prefix', '/') serve_application(app, prefix, port=int(conf.get('port', 4000)))
setattr(self.current_obj(), name, value)
setattr(self.current_obj(), attr, value)
def __setattr__(self, attr, value): setattr(self.current_obj(), name, value)
response = IncludedResponse
response = IncludedResponse()
def activate(self, environ): response = IncludedResponse def start_response(status, headers, exc_info=None): if exc_info: raise exc_info[0], exc_info[1], exc_info[2] response.status = status response.headers = headers return response.write app_iter = self.application(environ, start_response) try: for s in app_iter: res...
def write(self):
def write(self, s):
def write(self): assert self.output is not None, ( "This response has already been closed and no further data " "can be written.") self.output.write()
self.output.write()
self.output.write(s)
def write(self): assert self.output is not None, ( "This response has already been closed and no further data " "can be written.") self.output.write()
status, headers, body = capture_output(
status, headers, body = intercept_output(
def replacement_app(environ, start_response): status, headers, body = capture_output( environ, application, lambda s, h: header_value(headers, 'content-type').startswith('text/html'), start_response) if status is None: return body body = re.sub(r'<.*?>', '', body) return [body]
return self.environ.get('X-Requested-With', '') == 'XMLHttpRequest'
return self.environ.get('HTTP_X-Requested-With', '') == 'XMLHttpRequest'
def is_xhr(self): """Returns a boolean if X-Requested-With is present and a XMLHttpRequest""" return self.environ.get('X-Requested-With', '') == 'XMLHttpRequest'
_start_re = re.compile(r'<div class=".*?" id="contents">') _end_re = re.compile(r'</div>[ \n]*</div>[ \n]*</body>')
_start_re = re.compile(r'<body>[ \n]*(?:<div.*?>[ \n]*)?<h1.*?>.*?</h1>') _end_re = re.compile(r'(?:</div>[ \n]*)?</div>[ \n]*</body>')
def read_properties(self): props = self.properties = {} m = self._title_re.search(self.html) if m: props['title'] = m.group(1) else: print 'No title in %s' % self.filename props['title'] = ''
self.not_found_application = self.not_found_app
if not not_found_app: not_found_app = self.not_found_app self.not_found_application = not_found_app
def __init__(self, not_found_app=None): self.applications = [] self.not_found_application = self.not_found_app
for header, value in res.getheaders():
for full_header in res.msg.headers: header, value = full_header.split(':', 1) value = value.strip()
def __call__(self, environ, start_response): if (self.allowed_request_methods and environ['REQUEST_METHOD'].lower() not in self.allowed_request_methods): return httpexceptions.HTTPBadRequest("Disallowed")(environ, start_response)
for header, value in res.getheaders():
for full_header in res.msg.headers: header, value = full_header.split(':', 1) value = value.strip()
def __call__(self, environ, start_response): scheme = environ['wsgi.url_scheme'] if self.force_host is None: conn_scheme = scheme else: conn_scheme = self.force_scheme if conn_scheme == 'http': ConnClass = httplib.HTTPConnection elif conn_scheme == 'https': ConnClass = httplib.HTTPSConnection else: raise ValueError( "U...
headertable = someheaderdict
headertable = {}
def headers(self): """Access to incoming headers""" # @@ Just needs a header table object headertable = someheaderdict for key in self.environ.keys(): if key.startswith('HTTP'): headertable.add(key[5:], self.environ[key]) return headertable
headertable.add(key[5:], self.environ[key])
headertable[key[5:]] = self.environ[key]
def headers(self): """Access to incoming headers""" # @@ Just needs a header table object headertable = someheaderdict for key in self.environ.keys(): if key.startswith('HTTP'): headertable.add(key[5:], self.environ[key]) return headertable
headers = property(headers, doc=headers.__doc__)
headers = property(LazyCache(headers), doc=headers.__doc__)
def headers(self): """Access to incoming headers""" # @@ Just needs a header table object headertable = someheaderdict for key in self.environ.keys(): if key.startswith('HTTP'): headertable.add(key[5:], self.environ[key]) return headertable
attrs.get('selected')))
'selected' in attrs))
def _parse_fields(self): in_select = None in_textarea = None fields = {} for match in self._tag_re.finditer(self.text): end = match.group(1) == '/' tag = match.group(2).lower() if tag not in ('input', 'select', 'option', 'textarea', 'button'): continue if tag == 'select' and end: assert in_select, ( '%r without startin...
attrs.get('checked')))
'checked' in attrs))
def _parse_fields(self): in_select = None in_textarea = None fields = {} for match in self._tag_re.finditer(self.text): end = match.group(1) == '/' tag = match.group(2).lower() if tag not in ('input', 'select', 'option', 'textarea', 'button'): continue if tag == 'select' and end: assert in_select, ( '%r without startin...
_attr_re = re.compile(r'([^= \n\r\t]*)[ \n\r\t]*=[ \n\r\t]*(?:"([^"]*)"|([^"][^ \n\r\t>]*))', re.S)
_attr_re = re.compile(r'([^= \n\r\t]+)[ \n\r\t]*(?:=[ \n\r\t]*(?:"([^"]*)"|([^"][^ \n\r\t>]*)))?', re.S)
def submit_fields(self, name=None, index=None): """ Return a list of ``[(name, value), ...]`` for the current state of the form. """ submit = [] if name is not None: field = self.get(name, index=index) submit.append((field.name, field.value_if_submitted())) for name, fields in self.fields.items(): for field in fields: ...
self.checked = attrs.get('checked') is not None
self.checked = 'checked' in attrs
def __init__(self, *args, **attrs): super(Checkbox, self).__init__(*args, **attrs) self.checked = attrs.get('checked') is not None
session_class=None, **session_class_kw):
session_class=None, expiration=60*12, **session_class_kw):
def __init__(self, environ, cookie_name='_SID_', session_class=None, **session_class_kw): self.created = False self.used = False self.environ = environ self.cookie_name = cookie_name self.session = None self.session_class = session_class or FileSession self.session_class_kw = session_class_kw
chmod=None):
chmod=None, expiration=2880, ):
def __init__(self, sid, create=False, session_file_path='/tmp', chmod=None): if chmod and isinstance(chmod, basestring): chmod = int(chmod, 8) self.chmod = chmod if not sid: # Invalid... raise KeyError self.session_file_path = session_file_path self.sid = sid if not create: if not os.path.exists(self.filename()): raise...
def __init__(self, address):
def __init__(self, address, allowed_request_methods=()):
def __init__(self, address): self.address = address self.parsed = urlparse.urlsplit(address) self.scheme = self.parsed[0].lower() self.host = self.parsed[1]
print (environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers)
if self.path: request_path = environ['PATH_INFO'] if request_path[0] == '/': request_path = request_path[1:] path = urlparse.urljoin(self.path, request_path) else: path = environ['PATH_INFO']
def __call__(self, environ, start_response): if self.scheme == 'http': ConnClass = httplib.HTTPConnection elif self.scheme == 'https': ConnClass = httplib.HTTPSConnection else: raise ValueError( "Unknown scheme for %r: %r" % (self.address, self.scheme)) conn = ConnClass(self.host) headers = {} for key, value in environ...
environ['PATH_INFO'],
path,
def __call__(self, environ, start_response): if self.scheme == 'http': ConnClass = httplib.HTTPConnection elif self.scheme == 'https': ConnClass = httplib.HTTPSConnection else: raise ValueError( "Unknown scheme for %r: %r" % (self.address, self.scheme)) conn = ConnClass(self.host) headers = {} for key, value in environ...
headers_out = res.getheaders()
headers_out = [] for header, value in res.getheaders(): if header.lower() not in filtered_headers: headers_out.append((header, value))
def __call__(self, environ, start_response): if self.scheme == 'http': ConnClass = httplib.HTTPConnection elif self.scheme == 'https': ConnClass = httplib.HTTPSConnection else: raise ValueError( "Unknown scheme for %r: %r" % (self.address, self.scheme)) conn = ConnClass(self.host) headers = {} for key, value in environ...
body = res.read(int(length))
if length is not None: body = res.read(int(length)) else: body = res.read()
def __call__(self, environ, start_response): if self.scheme == 'http': ConnClass = httplib.HTTPConnection elif self.scheme == 'https': ConnClass = httplib.HTTPSConnection else: raise ValueError( "Unknown scheme for %r: %r" % (self.address, self.scheme)) conn = ConnClass(self.host) headers = {} for key, value in environ...
if 'gzip' not in environ.get('HTTP_ACCEPT_ENCODING'):
if 'gzip' not in environ.get('HTTP_ACCEPT_ENCODING', ''):
def __call__(self, environ, start_response): if 'gzip' not in environ.get('HTTP_ACCEPT_ENCODING'): # nothing for us to do, so this middleware will # be a no-op: return self.application(environ, start_response) response = GzipResponse(start_response, self.compress_level) app_iter = self.application(environ, response.gzi...
doc = """Host name provided in HTTP_HOST, with fall-back to SERVER_NAME""" def fget(self): return self.environ.get('HTTP_HOST', self.environ.get('SERVER_NAME'))
doc = textwrap.dedent("""\ Host name provided in HTTP_HOST, with fall-back to SERVER_NAME """) def fget(self): return self.environ.get('HTTP_HOST', self.environ.get('SERVER_NAME'))
def host(): doc = """Host name provided in HTTP_HOST, with fall-back to SERVER_NAME""" def fget(self): return self.environ.get('HTTP_HOST', self.environ.get('SERVER_NAME')) return locals()
if domain:
if port:
def parse_path_expression(path): """ Parses a path expression like 'domain foobar.com port 20 /' or just '/foobar' for a path alone. Returns as an address that URLMap likes. """ parts = path.split() domain = port = path = None while parts: if parts[0] == 'domain': parts.pop(0) if not parts: raise ValueError("'domain' ...
def post(self, url, params=None, headers={}, extra_environ={},
def post(self, url, params='', headers={}, extra_environ={},
def post(self, url, params=None, headers={}, extra_environ={}, status=None, upload_files=None, expect_errors=False): """ Do a POST request. Very like the ``.get()`` method. ``params`` are put in the body of the request.
href = urlparse.urljoin(self.request.url, href)
href = urlparse.urljoin(self.request.full_url, href)
def goto(self, href, method='get', **args): """ Go to the (potentially relative) link ``href``, using the given method (``'get'`` or ``'post'``) and any extra arguments you want to pass to the ``app.get()`` or ``app.post()`` methods.
start_response("200 OK", (('Content-Type', 'text/html'), ('Content-Length', len(content))))
start_response("200 OK", [('Content-Type', 'text/html'), ('Content-Length', str(len(content)))])
def __call__(self, environ, start_response): username = environ.get('REMOTE_USER','') if username: return self.application(environ, start_response)
status=None, time_request=False):
status=None):
def get(self, url, params=None, headers={}, status=None, time_request=False): if params: if isinstance(params, dict): params = urllib.urlencode(params) if '?' in url: url += '&' else: url += '?' url += params environ = self.make_environ() for header, value in headers.items(): environ['HTTP_%s' % header.replace('-', '_'...
return self.do_request(req, status=status, time_request=time_request)
return self.do_request(req, status=status)
def get(self, url, params=None, headers={}, status=None, time_request=False): if params: if isinstance(params, dict): params = urllib.urlencode(params) if '?' in url: url += '&' else: url += '?' url += params environ = self.make_environ() for header, value in headers.items(): environ['HTTP_%s' % header.replace('-', '_'...
upload_files=None, time_request=False):
upload_files=None):
def post(self, url, params=None, headers={}, status=None, upload_files=None, time_request=False): environ = self.make_environ() if params and isinstance(params, dict): params = urllib.urlencode(params) if upload_files: params = cgi.parse_qsl(params, keep_blank_values=True) content_type, params = self.encode_multipart( ...
return self.do_request(req, status=status, time_request=time_request)
return self.do_request(req, status=status)
def post(self, url, params=None, headers={}, status=None, upload_files=None, time_request=False): environ = self.make_environ() if params and isinstance(params, dict): params = urllib.urlencode(params) if upload_files: params = cgi.parse_qsl(params, keep_blank_values=True) content_type, params = self.encode_multipart( ...
def do_request(self, req, status, time_request):
def do_request(self, req, status):
def do_request(self, req, status, time_request): app = lint.middleware(self.app) old_stdout = sys.stdout out = StringIO() try: sys.stdout = out start_time = time.time() raw_res = wsgilib.raw_interactive(app, req.url, **req.environ) end_time = time.time() finally: sys.stdout = old_stdout sys.stderr.write(out.getvalue())...
res = self.make_response(raw_res)
res = self.make_response(raw_res, end_time - start_time)
def do_request(self, req, status, time_request): app = lint.middleware(self.app) old_stdout = sys.stdout out = StringIO() try: sys.stdout = out start_time = time.time() raw_res = wsgilib.raw_interactive(app, req.url, **req.environ) end_time = time.time() finally: sys.stdout = old_stdout sys.stderr.write(out.getvalue())...
if time_request: return end_time - start_time
if self.namespace is None: return res
def do_request(self, req, status, time_request): app = lint.middleware(self.app) old_stdout = sys.stdout out = StringIO() try: sys.stdout = out start_time = time.time() raw_res = wsgilib.raw_interactive(app, req.url, **req.environ) end_time = time.time() finally: sys.stdout = old_stdout sys.stderr.write(out.getvalue())...
def make_response(self, (status, headers, body, errors)): return TestResponse(self, status, headers, body, errors)
def make_response(self, (status, headers, body, errors), total_time): return TestResponse(self, status, headers, body, errors, total_time)
def make_response(self, (status, headers, body, errors)): return TestResponse(self, status, headers, body, errors)
def __init__(self, test_app, status, headers, body, errors):
def __init__(self, test_app, status, headers, body, errors, total_time):
def __init__(self, test_app, status, headers, body, errors): self.test_app = test_app self.status = int(status.split()[0]) self.full_status = status self.headers = headers self.body = body self.errors = errors self._normal_body = None
status, headers, body = capture_output(
status, headers, body = intercept_output(
def replacement_app(environ, start_response): status, headers, body = capture_output( environ, application) content_type = header_value(headers, 'content-type') if (not content_type or not content_type.startswith('text/html')): return [body] body = re.sub(r'<.*?>', '', body) return [body]
stacked._push_object(obj)
def replace(self, stacked, obj): """Replace the object referenced by a StackedObjectProxy with a different object
pass
print_exception(exc_info[0], exc_info[1], exc_info[2], file=errors)
def start_response(status, headers, exc_info=None): if exc_info: try: if headers_sent: # Re-raise original exception only if headers sent raise exc_info[0], exc_info[1], exc_info[2] else: # We assume that the sender, who is probably setting # the headers a second time /w a 500 has produced # a more appropriate response...
if 'html' in environ.get('HTTP_ACCEPT',''):
if 'html' in environ.get('HTTP_ACCEPT','') or \ '*/*' in environ.get('HTTP_ACCEPT',''):
def wsgi_application(self, environ, start_response, exc_info=None): """ This exception as a WSGI application """ if self.headers: headers = list(self.headers) else: headers = [] if 'html' in environ.get('HTTP_ACCEPT',''): replace_header(headers, 'content-type', 'text/html') content = self.html(environ) else: replace_he...
self.app = app
self.application = app
def __init__(self, app, global_conf, session_type=NoDefault, cookie_name=NoDefault, **store_config ): self.app = app if session_type is NoDefault: session_type = global_conf.get('session_type', 'disk') self.session_type = session_type try: self.store_class, self.store_args = self.session_classes[self.session_type] exce...
ok_callback()
if ok_callback: ok_callback()
def catch_errors(application, environ, start_response, error_callback, ok_callback=None): """ Runs the application, and returns the application iterator (which should be passed upstream). If an error occurs then error_callback will be called with exc_info as its sole argument. If no errors occur and ok_callback is gi...
abs_regex = re.compile(r'^[a-zA-Z]:')
abs_regex = re.compile(r'^[a-zA-Z]+:')
def forward_to_wsgiapp(self, app): """ Forwards the request to the given WSGI application """ raise ForwardRequest(app)
status, headers, body = wsgilib.capture_output( environ, start_response, self.app)
status, headers, body = wsgilib.intercept_output( environ, self.app)
def __call__(self, environ, start_response): global _threadedprint_installed if environ.get('paste.testing'): # In a testing environment this interception isn't # useful: return self.app(environ, start_response) if not _threadedprint_installed: # @@: Not strictly threadsafe _threadedprint_installed = True threadedprint...
for name, value in req.environ['paste.testing_variables']: setattr(res, name, value)
def do_request(self, req, status): __tracebackhide__ = True if self.cookies: c = SimpleCookie() for name, value in self.cookies.items(): c[name] = value req.environ['HTTP_COOKIE'] = str(c).split(': ', 1)[1] req.environ['paste.testing'] = True req.environ['paste.testing_variables'] = {} app = lint.middleware(self.app) o...
', '.join(map(repr, matches)))
',\n '.join(map(repr, matches)))
def not_found_app(self, environ, start_response): mapper = environ.get('paste.urlmap_object') if mapper: matches = [p for p, a in mapper.applications] extra = 'defined apps: %s' % ( ', '.join(map(repr, matches))) else: extra = '' extra += '\nSCRIPT_NAME: %r' % environ.get('SCRIPT_NAME') extra += '\nPATH_INFO: %r' % env...
host = host.split(':', 1)[0]
host, port = host.split(':', 1)[0] else: if environ['wsgi.url_scheme'] == 'http': port = '80' else: port = '443'
def __call__(self, environ, start_response): host = environ.get('HTTP_HOST', environ.get('SERVER_NAME')).lower() if ':' in host: host = host.split(':', 1)[0] path_info = environ.get('PATH_INFO') path_info = self.normalize_url(path_info, False)[1] for (domain, app_url), app in self.applications: if domain and domain != ...
if domain and domain != host:
if domain and domain != host and domain != host+':'+port:
def __call__(self, environ, start_response): host = environ.get('HTTP_HOST', environ.get('SERVER_NAME')).lower() if ':' in host: host = host.split(':', 1)[0] path_info = environ.get('PATH_INFO') path_info = self.normalize_url(path_info, False)[1] for (domain, app_url), app in self.applications: if domain and domain != ...
cache_max_age=None): if os.path.sep != '/': directory = directory.replace(os.path.sep, '/') self.directory = directory
cache_max_age=None, index_files=None): self.index_files = index_files if self.index_files is None: self.index_files = ['index.html'] self.directory = os.path.normpath(directory).replace(os.path.sep, '/')
def __init__(self, directory, root_directory=None, cache_max_age=None): if os.path.sep != '/': directory = directory.replace(os.path.sep, '/') self.directory = directory self.root_directory = root_directory if root_directory is not None: self.root_directory = os.path.normpath(self.root_directory) else: self.root_direct...
self.root_directory = os.path.normpath(self.root_directory) else: self.root_directory = directory
self.root_directory = os.path.normpath(self.root_directory).replace(os.path.sep, '/') else: self.root_directory = self.directory
def __init__(self, directory, root_directory=None, cache_max_age=None): if os.path.sep != '/': directory = directory.replace(os.path.sep, '/') self.directory = directory self.root_directory = root_directory if root_directory is not None: self.root_directory = os.path.normpath(self.root_directory) else: self.root_direct...
if os.path.sep != '/': directory = directory.replace('/', os.path.sep) self.root_directory = self.root_directory.replace('/', os.path.sep)
def __init__(self, directory, root_directory=None, cache_max_age=None): if os.path.sep != '/': directory = directory.replace(os.path.sep, '/') self.directory = directory self.root_directory = root_directory if root_directory is not None: self.root_directory = os.path.normpath(self.root_directory) else: self.root_direct...
if path_info == '/': filename = 'index.html' else: filename = request.path_info_pop(environ) full = os.path.normpath(os.path.join(self.directory, filename)) if os.path.sep != '/': full = full.replace('/', os.path.sep) if self.root_directory is not None and not full.startswith(self.root_directory): return self.not_fou...
if '/../' in path_info: start_response('400 Bad Request', headers) return [''] full = self.directory + path_info
def __call__(self, environ, start_response): path_info = environ.get('PATH_INFO', '') if not path_info: return self.add_slash(environ, start_response) if path_info == '/': # @@: This should obviously be configurable filename = 'index.html' else: filename = request.path_info_pop(environ) full = os.path.normpath(os.path....
child_root = self.root_directory is not None and \ self.root_directory or self.directory return self.__class__(full, root_directory=child_root, cache_max_age=self.cache_max_age)(environ, start_response) if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/': return self.error_extra_path(environ, start_response...
for file in self.index_files: full = os.path.normpath(os.path.join(full, file)).replace(os.path.sep, '/') if not os.path.exists(full): return self.no_index(environ, start_response) elif os.path.isdir(full): return self.not_found(environ, start_response) else: break
def __call__(self, environ, start_response): path_info = environ.get('PATH_INFO', '') if not path_info: return self.add_slash(environ, start_response) if path_info == '/': # @@: This should obviously be configurable filename = 'index.html' else: filename = request.path_info_pop(environ) full = os.path.normpath(os.path....
if ';' in value: value = value.split(';', 1)[0]
def parse(self, *args, **kwargs): """ return the time value (in seconds since 1970) """ value = self.__call__(*args, **kwargs) if ';' in value: value = value.split(';', 1)[0] if value: try: return mktime_tz(parsedate_tz(value)) except TypeError: raise HTTPBadRequest(( "Received an ill-formed timestamp for %s: %s\r\n") ...
else: return None
def parse(self, *args, **kwargs): """ return the time value (in seconds since 1970) """ value = self.__call__(*args, **kwargs) if ';' in value: value = value.split(';', 1)[0] if value: try: return mktime_tz(parsedate_tz(value)) except TypeError: raise HTTPBadRequest(( "Received an ill-formed timestamp for %s: %s\r\n") ...
return _DateHeader.__call__(self, *args, **kwargs).split(';')[0]
return _DateHeader.__call__(self, *args, **kwargs).split(';', 1)[0]
def __call__(self, *args, **kwargs): """ Split the value on ';' incase the header includes extra attributes. E.g. IE 6 is known to send: If-Modified-Since: Sun, 25 Jun 2006 20:36:35 GMT; length=1506 """ return _DateHeader.__call__(self, *args, **kwargs).split(';')[0]
return self.init_module.application
return self.init_module.application, None
def find_application(self, environ): if (self.init_module and getattr(self.init_module, 'application', None) and not environ.get('paste.urlparser.init_application') == environ['SCRIPT_NAME']): environ['paste.urlparser.init_application'] = environ['SCRIPT_NAME'] return self.init_module.application name, rest_of_path = w...
if global_conf.has_key('debug') and global_conf['debug'].lower() == 'true': self.debug = True else: self.debug = False
self.debug = converters.asbool(global_conf.get('debug'))
def __init__(self, app, mapper, global_conf=None, **params): if global_conf is None: global_conf = {} if global_conf.has_key('debug') and global_conf['debug'].lower() == 'true': self.debug = True else: self.debug = False self.application = app self.mapper = mapper self.global_conf = global_conf self.params = params
print k, key
def wsgi_setup(self, environ=None): """ Setup the member variables used by this WSGI mixin, including the ``environ`` and status member variables.
filename = file_info[2]
filename = file_info[1]
def _get_file_info(self, file_info): if len(file_info) == 2: # It only has a filename filename = file_info[2] if self.relative_to: filename = os.path.join(self.relative_to, filename) f = open(filename, 'rb') content = f.read() f.close() return (file_info[0], filename, content) elif len(file_info) == 3: return file_info...
data_files=get_data_files(os.path.join("paste","app_templates")) +
data_files=get_data_files(os.path.join("paste","app_templates")) + get_data_files(os.path.join("paste", "frameworks")) +
def get_data_files(path, files = []): l = [] for name in os.listdir(path): if name[0] == ".": continue relpath = os.path.join(path, name) f = os.path.join(BASEDIR, relpath) if os.path.isdir(f): get_data_files(relpath, files) elif os.path.isfile(f): l.append(f) pref = sysconfig.get_python_lib()[len(sysconfig.PREFIX) + 1...
path = environ['REQUEST_URI'][len(prefix):]
path = environ['REQUEST_URI'][len(prefix):].split('?', 1)[0]
def handle_connection(self, conn): """ Handle an individual connection. """ input = conn.makefile("r") output = conn.makefile("w")
<<<<<<< .working class HTTPConflict(HTTPException): =======
def html(self, environ): """ text/html representation of the exception """ return ''
>>>>>>> .merge-right.r4008
def html(self, environ): """ text/html representation of the exception """ return ''
<<<<<<< .working class HTTPNotImplemented(HTTPException): code = 501 =======
def html(self, environ): """ text/html representation of the exception """ return ''
local_dict()[self._local_key] = []
def __init__(self): self._constructor_lock.acquire() try: self.dispatching_id = 0 while 1: self._local_key = 'paste.processconfig_%i' % self.dispatching_id if not local_dict().has_key(self._local_key): break self.dispatching_id += 1 finally: self._constructor_lock.release() local_dict()[self._local_key] = [] self._proc...
local_dict()[self._local_key].append(conf)
local_dict().setdefault(self._local_key, []).append(conf)
def push_thread_config(self, conf): """ Make ``conf`` the active configuration for this thread. Thread-local configuration always overrides process-wide configuration.