Package cherrypy :: Package lib
[hide private]
[frames] | no frames]

Source Code for Package cherrypy.lib

 1  """CherryPy Library""" 
 2   
 3  # Deprecated in CherryPy 3.2 -- remove in CherryPy 3.3 
 4  from cherrypy.lib.reprconf import unrepr, modules, attributes 
 5   
6 -def is_iterator(obj):
7 '''Returns a boolean indicating if the object provided implements 8 the iterator protocol (i.e. like a generator). This will return 9 false for objects which iterable, but not iterators themselves.''' 10 from types import GeneratorType 11 if isinstance(obj, GeneratorType): 12 return True 13 elif not hasattr(obj, '__iter__'): 14 return False 15 else: 16 # Types which implement the protocol must return themselves when 17 # invoking 'iter' upon them. 18 return iter(obj) is obj
19
20 -def is_closable_iterator(obj):
21 22 # Not an iterator. 23 if not is_iterator(obj): 24 return False 25 26 # A generator - the easiest thing to deal with. 27 import inspect 28 if inspect.isgenerator(obj): 29 return True 30 31 # A custom iterator. Look for a close method... 32 if not (hasattr(obj, 'close') and callable(obj.close)): 33 return False 34 35 # ... which doesn't require any arguments. 36 try: 37 inspect.getcallargs(obj.close) 38 except TypeError: 39 return False 40 else: 41 return True
42
43 -class file_generator(object):
44 45 """Yield the given input (a file object) in chunks (default 64k). (Core)""" 46
47 - def __init__(self, input, chunkSize=65536):
48 self.input = input 49 self.chunkSize = chunkSize
50
51 - def __iter__(self):
52 return self
53
54 - def __next__(self):
55 chunk = self.input.read(self.chunkSize) 56 if chunk: 57 return chunk 58 else: 59 if hasattr(self.input, 'close'): 60 self.input.close() 61 raise StopIteration()
62 next = __next__
63 64
65 -def file_generator_limited(fileobj, count, chunk_size=65536):
66 """Yield the given file object in chunks, stopping after `count` 67 bytes has been emitted. Default chunk size is 64kB. (Core) 68 """ 69 remaining = count 70 while remaining > 0: 71 chunk = fileobj.read(min(chunk_size, remaining)) 72 chunklen = len(chunk) 73 if chunklen == 0: 74 return 75 remaining -= chunklen 76 yield chunk
77 78
79 -def set_vary_header(response, header_name):
80 "Add a Vary header to a response" 81 varies = response.headers.get("Vary", "") 82 varies = [x.strip() for x in varies.split(",") if x.strip()] 83 if header_name not in varies: 84 varies.append(header_name) 85 response.headers['Vary'] = ", ".join(varies)
86