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. If the request was not a normal form request (e.g., a POST with an XML body) then ``environ['wsgi.input']`` won't be read. """ source = (environ.get('QUERY_STRING', ''), environ['wsgi.input'], include_get_vars) if 'paste.parsed_formvars' in environ: parsed, check_source = environ['paste.parsed_formvars'] if check_source == source: return parsed # @@: Shouldn't bother FieldStorage parsing during GET/HEAD and # fake_out_cgi requests type = environ.get('CONTENT_TYPE', '').lower() fake_out_cgi = type not in ('', 'application/x-www-form-urlencoded') and \ not type.startswith('multipart/form-data') # Prevent FieldStorage from parsing QUERY_STRING during GET/HEAD # requests old_query_string = environ['QUERY_STRING'] environ['QUERY_STRING'] = '' if fake_out_cgi: input = StringIO('') old_content_type = environ.get('CONTENT_TYPE') old_content_length = environ.get('CONTENT_LENGTH') environ['CONTENT_LENGTH'] = '0' environ['CONTENT_TYPE'] = '' else: input = environ['wsgi.input'] fs = cgi.FieldStorage(fp=input, environ=environ, keep_blank_values=1) environ['QUERY_STRING'] = old_query_string if fake_out_cgi: environ['CONTENT_TYPE'] = old_content_type environ['CONTENT_LENGTH'] = old_content_length formvars = MultiDict() if isinstance(fs.value, list): for name in fs.keys(): values = fs[name] if not isinstance(values, list): values = [values] for value in values: if not value.filename: value = value.value formvars.add(name, value) if include_get_vars: formvars.update(parse_querystring(environ)) environ['paste.parsed_formvars'] = (formvars, source) return formvars
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.txt)' % dir continue if self.args and not fnmatch.fnmatch(name, self.args[0]): continue if not self.options.verbose: print '%s: %s\n' % ( name, self.template_description().splitlines()[0]) else: return '%s: %s\n' % ( self.name, self.template_description()) # @@: for verbosity >= 2 we should give lots of metadata any = True if not any: print 'No application templates found'
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.txt)' % dir continue if self.args and not fnmatch.fnmatch(name, self.args[0]): continue if not self.options.verbose: print '%s: %s\n' % ( name, self.template_description().splitlines()[0]) else: return '%s: %s\n' % ( self.name, self.template_description()) # @@: for verbosity >= 2 we should give lots of metadata any = True if not any: print 'No application templates found'
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): environ[REQUEST_FINISHED] = time.time() return catch_errors(self.application, environ, start_response, finalizer, finalizer) return self.application(environ, start_response) def uploads(self): return self.monitor class UploadProgressReporter: """ reports on the progress of uploads for a given user This reporter returns a JSON file (for use in AJAX) listing the uploads in progress for the given user. By default, this reporter uses the ``REMOTE_USER`` environment to compare between the current request and uploads in-progress. If they match, then a response record is formed. ``match()`` This member function can be overriden to provide alternative matching criteria. It takes two environments, the first is the current request, the second is a current upload. ``report()`` This member function takes an environment and builds a ``dict`` that will be used to create a JSON mapping for the given upload. By default, this just includes the percent complete and the request url. """ def __init__(self, monitor): self.monitor = monitor def match(self, search_environ, upload_environ): if search_environ.get('REMOTE_USER',None) == \ upload_environ.get('REMOTE_USER',0): return True return False def report(self, environ): retval = { 'started': time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(environ[REQUEST_STARTED])), 'finished': '', 'content_length': environ.get('CONTENT_LENGTH'), 'bytes_received': environ[ENVIRON_RECEIVED], 'path_info': environ.get('PATH_INFO',''), 'query_string': environ.get('QUERY_STRING','')} finished = environ[REQUEST_FINISHED] if finished: retval['finished'] = time.strftime("%Y:%m:%d %H:%M:%S", time.gmtime(finished)) return retval def __call__(self, environ, start_response): body = [] for map in [self.report(env) for env in self.monitor.uploads() if self.match(environ, env)]: parts = [] for k,v in map.items(): v = str(v).replace("\\","\\\\").replace('"','\\"') parts.append('%s: "%s"' % (k,v)) body.append("{ %s }" % ", ".join(parts)) body = "[ %s ]" % ", ".join(body) start_response("200 OK", [ ('Content-Type', 'text/plain'), ('Content-Length', len(body))])
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, environ, start_response): size = 0 total = environ.get('CONTENT_LENGTH') if total: remaining = int(total) while remaining > 0: if self.progress: print "%s of %s remaining" % (remaining, total) if remaining > 4096: chunk = environ['wsgi.input'].read(4096) else: chunk = environ['wsgi.input'].read(remaining) if not chunk: break size += len(chunk) remaining -= len(chunk) if self.delay: time.sleep(self.delay) body = "<html><body>%d bytes</body></html>" % size else: body = ('<html><body>\n' '<form method="post" enctype="multipart/form-data">\n' '<input type="file" name="file">\n' '<input type="submit" >\n' '</form></body></html>\n') print "bingles" start_response("200 OK",[('Content-Type', 'text/html'), ('Content-Length', len(body))]) return [body]
__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, html4.01/css, xhtml1.0) Standalone: This module will work from the command line with options. This module will work with redirected stdio. Imported: This module can be imported and used directly in your code. ----------------------------------------------------------------------------- Command line options: -h, --help Optional-> Display this help message. -t, --test Optional-> Will ignore all others flags but --profile test all schemes and markup combinations -p, --profile Optional-> Works only with --test or -t runs profile.py and makes the test work in quiet mode. -i, --in, --input Optional-> If you give input on stdin. Use any of these for the current dir (.,cwd) Input can be file or dir. Input from stdin use one of the following (-,stdin) If stdin is used as input stdout is output unless specified. -o, --out, --output Optional-> output dir for the colorized source. default: output dir is the input dir. To output html to stdout use one of the following (-,stdout) Stdout can be used without stdin if you give a file as input. -c, --color Optional-> null, mono, dark, dark2, lite, idle, pythonwin, viewcvs default: dark -s, --show Optional-> Show page after creation. default: no show -m, --markup Optional-> html, css, xhtml css, xhtml also support external stylesheets (-e,--external) default: HTML -e, --external Optional-> use with css, xhtml Writes an style sheet instead of embedding it in the page saves it as pystyle.css in the same directory. html markup will silently ignore this flag. -H, --header Opional-> add a page header to the top of the output -H Builtin header (name,date,hrule) --header You must specify a filename. The header file must be valid html and must handle its own font colors. ex. --header c:/tmp/header.txt -F, --footer Opional-> add a page footer to the bottom of the output -F Builtin footer (hrule,name,date) --footer You must specify a filename. The footer file must be valid html and must handle its own font colors. ex. --footer c:/tmp/footer.txt -l, --linenumbers Optional-> default is no linenumbers Adds line numbers to the start of each line in the code. --convertpage Given a webpage that has code embedded in tags it will convert embedded code to colorized html. (see pageconvert for details) ----------------------------------------------------------------------------- Option usage: # Test and show pages python PySourceColor.py -t -s # Test and only show profile results python PySourceColor.py -t -p # Colorize all .py,.pyw files in cwdir you can also use: (.,cwd) python PySourceColor.py -i . # Using long options w/ = python PySourceColor.py --in=c:/myDir/my.py --color=lite --show # Using short options w/out = python PySourceColor.py -i c:/myDir/ -c idle -m css -e # Using any mix python PySourceColor.py --in . -o=c:/myDir --show # Place a custom header on your files python PySourceColor.py -i . -o c:/tmp -m xhtml --header c:/header.txt ----------------------------------------------------------------------------- Stdio usage: # Stdio using no options python PySourceColor.py < c:/MyFile.py > c:/tmp/MyFile.html # Using stdin alone automatically uses stdout for output: (stdin,-) python PySourceColor.py -i- < c:/MyFile.py > c:/tmp/myfile.html # Stdout can also be written to directly from a file instead of stdin python PySourceColor.py -i c:/MyFile.py -m css -o- > c:/tmp/myfile.html # Stdin can be used as input , but output can still be specified python PySourceColor.py -i- -o c:/pydoc.py.html -s < c:/Python22/my.py _____________________________________________________________________________ """ print Usage.__doc__% (__version__) sys.exit(1)
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, html4.01/css, xhtml1.0) Standalone: This module will work from the command line with options. This module will work with redirected stdio. Imported: This module can be imported and used directly in your code. ----------------------------------------------------------------------------- Command line options: -h, --help Optional-> Display this help message. -t, --test Optional-> Will ignore all others flags but --profile test all schemes and markup combinations -p, --profile Optional-> Works only with --test or -t runs profile.py and makes the test work in quiet mode. -i, --in, --input Optional-> If you give input on stdin. Use any of these for the current dir (.,cwd) Input can be file or dir. Input from stdin use one of the following (-,stdin) If stdin is used as input stdout is output unless specified. -o, --out, --output Optional-> output dir for the colorized source. default: output dir is the input dir. To output html to stdout use one of the following (-,stdout) Stdout can be used without stdin if you give a file as input. -c, --color Optional-> null, mono, dark, dark2, lite, idle, pythonwin, viewcvs default: dark -s, --show Optional-> Show page after creation. default: no show -m, --markup Optional-> html, css, xhtml css, xhtml also support external stylesheets (-e,--external) default: HTML -e, --external Optional-> use with css, xhtml Writes an style sheet instead of embedding it in the page saves it as pystyle.css in the same directory. html markup will silently ignore this flag. -H, --header Opional-> add a page header to the top of the output -H Builtin header (name,date,hrule) --header You must specify a filename. The header file must be valid html and must handle its own font colors. ex. --header c:/tmp/header.txt -F, --footer Opional-> add a page footer to the bottom of the output -F Builtin footer (hrule,name,date) --footer You must specify a filename. The footer file must be valid html and must handle its own font colors. ex. --footer c:/tmp/footer.txt -l, --linenumbers Optional-> default is no linenumbers Adds line numbers to the start of each line in the code. --convertpage Given a webpage that has code embedded in tags it will convert embedded code to colorized html. (see pageconvert for details) ----------------------------------------------------------------------------- Option usage: # Test and show pages python PySourceColor.py -t -s # Test and only show profile results python PySourceColor.py -t -p # Colorize all .py,.pyw files in cwdir you can also use: (.,cwd) python PySourceColor.py -i . # Using long options w/ = python PySourceColor.py --in=c:/myDir/my.py --color=lite --show # Using short options w/out = python PySourceColor.py -i c:/myDir/ -c idle -m css -e # Using any mix python PySourceColor.py --in . -o=c:/myDir --show # Place a custom header on your files python PySourceColor.py -i . -o c:/tmp -m xhtml --header c:/header.txt ----------------------------------------------------------------------------- Stdio usage: # Stdio using no options python PySourceColor.py < c:/MyFile.py > c:/tmp/MyFile.html # Using stdin alone automatically uses stdout for output: (stdin,-) python PySourceColor.py -i- < c:/MyFile.py > c:/tmp/myfile.html # Stdout can also be written to directly from a file instead of stdin python PySourceColor.py -i c:/MyFile.py -m css -o- > c:/tmp/myfile.html # Stdin can be used as input , but output can still be specified python PySourceColor.py -i- -o c:/pydoc.py.html -s < c:/Python22/my.py _____________________________________________________________________________ """ print Usage.__doc__% (__version__) sys.exit(1)
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. """ category = {} for idx in range(len(response_headers)): (key,val) = response_headers[idx] head = get_header(key, strict) if not head: newhead = '-'.join(x.capitalize() for x in \ key.replace("_","-").split("-")) response_headers[idx] = (newhead,val) category[newhead] = 4 continue response_headers[idx] = (str(head),val) category[str(head)] = head.sort_order def compare(a,b): ac = category[a[0]] bc = category[b[0]] if ac == bc: return cmp(a[0],b[0]) return cmp(ac,bc) response_headers.sort(compare)
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_response, sys.exc_info()) app_iter = iter(new_app_iterable) if hasattr(new_app_iterable, 'close'): self.close = new_app_iterable.close else: del self.close self.next = app_iter.next return self.next()
'<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 let 'verbose' through, but this doesn't really # stop any sourced configs from setting it either... if other_conf.has_key('verbose'): del other_conf['verbose'] replacements['other_conf'] = other_conf template_fn = os.path.join(os.path.dirname(__file__), 'server_script_template.py.txt') template = open(template_fn).read() for name, value in replacements.items(): template = template.replace('@@' + name + '@@', repr(value)) print "#!%s" % sys.executable print template print "if __name__ == '__main__':" print " from paste.cgiserver import run_with_cgi" print " run_with_cgi(app)"
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.path: if os.path.exists(os.path.join(path_dir, script)): self.script = os.path.join(path_dir, script) break else: raise CGIError( "Script %r not found in path %r" % (script, self.path)) else: self.script = script self.include_os_environ = include_os_environ 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) self.query_string = query_string
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.upper() == name and isinstance(environ[name], str)): cgi_environ[name] = environ[name] if self.query_string is not None: old = cgi_environ.get('QUERY_STRING', '') if old: old += '&' cgi_environ['QUERY_STRING'] = old + self.query_string proc = subprocess.Popen( [self.script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=cgi_environ, cwd=os.path.dirname(self.script), ) proc_communicate( proc, stdin=StdinReader.from_environ(environ), stdout=CGIWriter(environ, start_response), stderr=environ['wsgi.errors']) return []
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)]: if var_value is not None: self.cookies[key][var_name.replace('_', '-')] = var_value
'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 [body] **Note:** Deprecated """ if __warn: warnings.warn( 'wsgilib.error_response is deprecated; use the ' 'wsgi_application method on an HTTPException object ' 'instead', DeprecationWarning, 1) if debug_message and environ.get('paste.config', {}).get('debug'): message += '\n\n<!-- %s -->' % debug_message body = error_body_response(error_code, message, __warn=False) headers = [('content-type', 'text/html'), ('content-length', str(len(body)))] return error_code, headers, body
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_root, **kw)
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( code, message, environ, self.global_conf, **self.params ) if not (new_url == None or isinstance(new_url, str)): raise TypeError( 'Expected the url to internally ' 'redirect to in the StatusBasedForward mapper' 'to be a string or None, not %s'%repr(new_url) ) if new_url: url.append([new_url, status]) else: return start_response(status, headers, exc_info)
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( code, message, environ, self.global_conf, **self.params ) if not (new_url == None or isinstance(new_url, str)): raise TypeError( 'Expected the url to internally ' 'redirect to in the StatusBasedForward mapper' 'to be a string or None, not %s'%repr(new_url) ) if new_url: url.append([new_url, status]) else: return start_response(status, headers, exc_info)
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) return files
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.compressible = False if self.compressible: headers.append(('content-encoding', 'gzip')) return self.start_response(status, headers, exc_info)
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: response.write(s) finally: if hasattr(app_iter, 'close'): app_iter.close() response.close() return response
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( "Unknown scheme %r" % scheme) if 'HTTP_HOST' not in environ: raise ValueError( "WSGI environ must contain an HTTP_HOST key") host = environ['HTTP_HOST'] if self.force_host is None: conn_host = host else: conn_host = self.force_host conn = ConnClass(conn_host) headers = {} for key, value in environ.items(): if key.startswith('HTTP_'): key = key[5:].lower().replace('_', '-') headers[key] = value headers['host'] = host if 'REMOTE_ADDR' in environ: headers['x-forwarded-for'] = environ['REMOTE_ADDR'] if environ.get('CONTENT_TYPE'): headers['content-type'] = environ['CONTENT_TYPE'] if environ.get('CONTENT_LENGTH'): length = int(environ['CONTENT_LENGTH']) body = environ['wsgi.input'].read(length) elif 'CONTENT_LENGTH' not in environ: body = environ['wsgi.input'].read() length = len(body) else: body = '' length = 0 path = (environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')) if 'QUERY_STRING' in environ: path += '?' + environ['QUERY_STRING'] conn.request(environ['REQUEST_METHOD'], path, body, headers) res = conn.getresponse() headers_out = [] for header, value in res.getheaders(): if header.lower() not in filtered_headers: headers_out.append((header, value)) status = '%s %s' % (res.status, res.reason) start_response(status, headers_out) # @@: Default? length = res.getheader('content-length') if length is not None: body = res.read(int(length)) else: body = res.read() conn.close() return [body]
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 starting select' % match.group(0)) in_select = None continue if tag == 'textarea' and end: assert in_textarea, ( "</textarea> with no <textarea> at %s" % match.start()) in_textarea[0].value = html_unquote(self.text[in_textarea[1]:match.start()]) in_textarea = None continue if end: continue attrs = _parse_attrs(match.group(3)) if 'name' in attrs: name = attrs.pop('name') else: name = None if tag == 'option': in_select.options.append((attrs.get('value'), attrs.get('selected'))) continue if tag == 'input' and attrs.get('type') == 'radio': field = self.fields.get(name) if not field: field = Radio(self, tag, name, match.start(), **attrs) fields.setdefault(name, []).append(field) else: field = field[0] assert isinstance(field, Radio) field.options.append((attrs.get('value'), attrs.get('checked'))) continue tag_type = tag if tag == 'input': tag_type = attrs.get('type', 'text').lower() FieldClass = Field.classes.get(tag_type, Field) field = FieldClass(self, tag, name, match.start(), **attrs) if tag == 'textarea': assert not in_textarea, ( "Nested textareas: %r and %r" % (in_textarea, match.group(0))) in_textarea = field, match.end() elif tag == 'select': assert not in_select, ( "Nested selects: %r and %r" % (in_select, match.group(0))) in_select = field fields.setdefault(name, []).append(field) self.fields = fields
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 starting select' % match.group(0)) in_select = None continue if tag == 'textarea' and end: assert in_textarea, ( "</textarea> with no <textarea> at %s" % match.start()) in_textarea[0].value = html_unquote(self.text[in_textarea[1]:match.start()]) in_textarea = None continue if end: continue attrs = _parse_attrs(match.group(3)) if 'name' in attrs: name = attrs.pop('name') else: name = None if tag == 'option': in_select.options.append((attrs.get('value'), attrs.get('selected'))) continue if tag == 'input' and attrs.get('type') == 'radio': field = self.fields.get(name) if not field: field = Radio(self, tag, name, match.start(), **attrs) fields.setdefault(name, []).append(field) else: field = field[0] assert isinstance(field, Radio) field.options.append((attrs.get('value'), attrs.get('checked'))) continue tag_type = tag if tag == 'input': tag_type = attrs.get('type', 'text').lower() FieldClass = Field.classes.get(tag_type, Field) field = FieldClass(self, tag, name, match.start(), **attrs) if tag == 'textarea': assert not in_textarea, ( "Nested textareas: %r and %r" % (in_textarea, match.group(0))) in_textarea = field, match.end() elif tag == 'select': assert not in_select, ( "Nested selects: %r and %r" % (in_select, match.group(0))) in_select = field fields.setdefault(name, []).append(field) self.fields = fields
_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: value = field.value if value is None: continue submit.append((name, value)) return submit
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 KeyError self._data = None
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.items(): if key.startswith('HTTP_'): key = key[5:].lower().replace('_', '-') if key == 'host': continue headers[key] = value headers['host'] = self.host if 'REMOTE_ADDR' in environ: headers['x-forwarded-for'] = environ['REMOTE_ADDR'] if environ.get('CONTENT_TYPE'): headers['content-type'] = environ['CONTENT_TYPE'] if environ.get('CONTENT_LENGTH'): length = int(environ['CONTENT_LENGTH']) body = environ['wsgi.input'].read(length) else: body = '' print (environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) conn.request(environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) res = conn.getresponse() # @@: 2.4ism: headers_out = res.getheaders() status = '%s %s' % (res.status, res.reason) start_response(status, headers_out) # @@: Default? length = res.getheader('content-length') body = res.read(int(length)) conn.close() return [body]
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.items(): if key.startswith('HTTP_'): key = key[5:].lower().replace('_', '-') if key == 'host': continue headers[key] = value headers['host'] = self.host if 'REMOTE_ADDR' in environ: headers['x-forwarded-for'] = environ['REMOTE_ADDR'] if environ.get('CONTENT_TYPE'): headers['content-type'] = environ['CONTENT_TYPE'] if environ.get('CONTENT_LENGTH'): length = int(environ['CONTENT_LENGTH']) body = environ['wsgi.input'].read(length) else: body = '' print (environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) conn.request(environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) res = conn.getresponse() # @@: 2.4ism: headers_out = res.getheaders() status = '%s %s' % (res.status, res.reason) start_response(status, headers_out) # @@: Default? length = res.getheader('content-length') body = res.read(int(length)) conn.close() return [body]
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.items(): if key.startswith('HTTP_'): key = key[5:].lower().replace('_', '-') if key == 'host': continue headers[key] = value headers['host'] = self.host if 'REMOTE_ADDR' in environ: headers['x-forwarded-for'] = environ['REMOTE_ADDR'] if environ.get('CONTENT_TYPE'): headers['content-type'] = environ['CONTENT_TYPE'] if environ.get('CONTENT_LENGTH'): length = int(environ['CONTENT_LENGTH']) body = environ['wsgi.input'].read(length) else: body = '' print (environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) conn.request(environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) res = conn.getresponse() # @@: 2.4ism: headers_out = res.getheaders() status = '%s %s' % (res.status, res.reason) start_response(status, headers_out) # @@: Default? length = res.getheader('content-length') body = res.read(int(length)) conn.close() return [body]
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.items(): if key.startswith('HTTP_'): key = key[5:].lower().replace('_', '-') if key == 'host': continue headers[key] = value headers['host'] = self.host if 'REMOTE_ADDR' in environ: headers['x-forwarded-for'] = environ['REMOTE_ADDR'] if environ.get('CONTENT_TYPE'): headers['content-type'] = environ['CONTENT_TYPE'] if environ.get('CONTENT_LENGTH'): length = int(environ['CONTENT_LENGTH']) body = environ['wsgi.input'].read(length) else: body = '' print (environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) conn.request(environ['REQUEST_METHOD'], environ['PATH_INFO'], body, headers) res = conn.getresponse() # @@: 2.4ism: headers_out = res.getheaders() status = '%s %s' % (res.status, res.reason) start_response(status, headers_out) # @@: Default? length = res.getheader('content-length') body = res.read(int(length)) conn.close() return [body]
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.gzip_start_response) try: if app_iter: response.finish_response(app_iter) finally: response.close() return None
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' must be followed with a domain name") if domain: raise ValueError("'domain' given twice") domain = parts.pop(0) elif parts[0] == 'port': parts.pop(0) if not parts: raise ValueError("'port' must be followed with a port number") if domain: raise ValueError("'port' given twice") port = parts.pop(0) else: if path: raise ValueError("more than one path given (have %r, got %r)" % (path, parts[0])) path = parts.pop(0) s = '' if domain: s = 'http://%s' % domain if port: if not domain: raise ValueError("If you give a port, you must also give a domain") s += ':' + port if path: if s: s += '/' s += path return s
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('-', '_').upper()] = value if '?' in url: url, environ['QUERY_STRING'] = url.split('?', 1) req = TestRequest(url, environ) return self.do_request(req, status=status, time_request=time_request)
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('-', '_').upper()] = value if '?' in url: url, environ['QUERY_STRING'] = url.split('?', 1) req = TestRequest(url, environ) return self.do_request(req, status=status, time_request=time_request)
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( params, upload_files) environ['CONTENT_TYPE'] = content_type environ['CONTENT_LENGTH'] = str(len(params)) environ['REQUEST_METHOD'] = 'POST' environ['wsgi.input'] = StringIO(params) req = TestRequest(url, environ) return self.do_request(req, status=status, time_request=time_request)
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( params, upload_files) environ['CONTENT_TYPE'] = content_type environ['CONTENT_LENGTH'] = str(len(params)) environ['REQUEST_METHOD'] = 'POST' environ['wsgi.input'] = StringIO(params) req = TestRequest(url, environ) return self.do_request(req, status=status, time_request=time_request)
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.request = req if self.namespace is not None: self.namespace['res'] = res self.check_status(status, res) self.check_errors(res) if time_request: return end_time - start_time
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()) res = self.make_response(raw_res) res.request = req if self.namespace is not None: self.namespace['res'] = res self.check_status(status, res) self.check_errors(res) if time_request: return end_time - start_time
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()) res = self.make_response(raw_res) res.request = req if self.namespace is not None: self.namespace['res'] = res self.check_status(status, res) self.check_errors(res) if time_request: return end_time - start_time
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. pass finally: # avoid dangling circular reference exc_info = None elif headers_set: # You cannot set the headers more than once, unless the # exc_info is provided. raise AssertionError("Headers already set and no exc_info!") headers_set.append(True) data['status'] = status data['headers'] = headers return output.write
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_header(headers, 'content-type', 'text/plain') content = self.plain(environ) if isinstance(content, unicode): content = content.encode('utf8') cur_content_type = ( response.header_value(headers, 'content-type') or 'text/html') reponse.replace_header( headers, 'content-type', cur_content_type + '; charset=utf8') start_response('%s %s' % (self.code, self.title), headers, exc_info) return [content]
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] except KeyError: raise KeyError( "The session_type %s is unknown (I know about %s)" % (self.session_type, ', '.join(self.session_classes.keys()))) kw = {} for config_name, kw_name, coercer, default in self.store_args: value = coercer(store_config.get(config_name, default)) kw[kw_name] = value self.store = self.store_class(**kw) if cookie_name is NoDefault: cookie_name = global_conf.get('session_cookie', '_SID_') self.cookie_name = cookie_name
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 given, then it will be called with no arguments. """ error_occurred = False try: app_iter = application(environ, start_response) except: error_callback(sys.exc_info()) raise if type(app_iter) in (list, tuple): # These won't produce exceptions ok_callback() return app_iter else: return _wrap_app_iter(app_iter, error_callback, ok_callback)
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.install(leave_stdout=True) logged = StringIO() if self.print_wsgi_errors: replacement_stdout = TeeFile(environ['wsgi.errors'], logged) else: replacement_stdout = logged output = StringIO() try: threadedprint.register(replacement_stdout) status, headers, body = wsgilib.capture_output( environ, start_response, self.app) if status is None: # Some error occurred status = '500 Server Error' headers = [('Content-type', 'text/html')] start_response(status, headers) if not body: body = 'An error occurred' content_type = wsgilib.header_value(headers, 'content-type') if (not self.force_content_type and (not content_type or not content_type.startswith('text/html'))): if replacement_stdout == logged: # Then the prints will be lost, unless... environ['wsgi.errors'].write(logged.getvalue()) return [body] body = self.add_log(body, logged.getvalue()) return [body] finally: threadedprint.deregister()
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) 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, end_time - start_time) res.request = req if self.namespace is not None: self.namespace['res'] = res if not req.expect_errors: self.check_status(status, res) self.check_errors(res) for header in res.all_headers('set-cookie'): c = SimpleCookie(header) for key, morsel in c.items(): self.cookies[key] = morsel.value for name, value in req.environ['paste.testing_variables']: setattr(res, name, value) if self.namespace is None: # It's annoying to return the response in doctests, as it'll # be printed, so we only return it is we couldn't assign # it anywhere return res
', '.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' % environ.get('PATH_INFO') app = httpexceptions.HTTPNotFound( 'The resource was not found', comment=extra).wsgi_application return app(environ, start_response)
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 != host: continue if (path_info == app_url or path_info.startswith(app_url + '/')): environ['SCRIPT_NAME'] += app_url environ['PATH_INFO'] = path_info[len(app_url):] return app(environ, start_response) environ['paste.urlmap_object'] = self return self.not_found_application(environ, start_response)
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 != host: continue if (path_info == app_url or path_info.startswith(app_url + '/')): environ['SCRIPT_NAME'] += app_url environ['PATH_INFO'] = path_info[len(app_url):] return app(environ, start_response) environ['paste.urlmap_object'] = self return self.not_found_application(environ, start_response)
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_directory = directory self.cache_max_age = cache_max_age if os.path.sep != '/': directory = directory.replace('/', os.path.sep) self.root_directory = self.root_directory.replace('/', os.path.sep)
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_directory = directory self.cache_max_age = cache_max_age if os.path.sep != '/': directory = directory.replace('/', os.path.sep) self.root_directory = self.root_directory.replace('/', os.path.sep)
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_directory = directory self.cache_max_age = cache_max_age if os.path.sep != '/': directory = directory.replace('/', os.path.sep) self.root_directory = self.root_directory.replace('/', os.path.sep)
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_found(environ, start_response)
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.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): # Out of bounds return self.not_found(environ, start_response) if not os.path.exists(full): return self.not_found(environ, start_response) if os.path.isdir(full): # @@: Cache? 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) if_none_match = environ.get('HTTP_IF_NONE_MATCH') if if_none_match: mytime = os.stat(full).st_mtime if str(mytime) == if_none_match: headers = [] ETAG.update(headers, mytime) start_response('304 Not Modified', headers) return [''] # empty body fa = fileapp.FileApp(full) if self.cache_max_age: fa.cache_control(max_age=self.cache_max_age) return fa(environ, start_response)
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.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): # Out of bounds return self.not_found(environ, start_response) if not os.path.exists(full): return self.not_found(environ, start_response) if os.path.isdir(full): # @@: Cache? 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) if_none_match = environ.get('HTTP_IF_NONE_MATCH') if if_none_match: mytime = os.stat(full).st_mtime if str(mytime) == if_none_match: headers = [] ETAG.update(headers, mytime) start_response('304 Not Modified', headers) return [''] # empty body fa = fileapp.FileApp(full) if self.cache_max_age: fa.cache_control(max_age=self.cache_max_age) return fa(environ, start_response)
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") % (self.name, value)) else: return None
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") % (self.name, value)) else: return None
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 = wsgilib.path_info_split(environ['PATH_INFO']) environ['PATH_INFO'] = rest_of_path if name is not None: environ['SCRIPT_NAME'] = environ.get('SCRIPT_NAME', '') + '/' + name if not name: names = self.option(environ, 'index_names') or [] for index_name in names: filename = self.find_file(environ, index_name) if filename: break else: # None of the index files found filename = None else: filename = self.find_file(environ, name) if filename is None: return None, filename else: return self.get_application(environ, filename), filename
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 else: raise ValueError( "upload_files need to be a list of tuples of (fieldname, " "filename, filecontent) or (fieldname, filename); " "you gave: %r" % repr(file_info)[:100])
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:] files.append((os.path.join(pref, path), l)) return files
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._process_configs = []
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.