desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
raise NotImplemented
'Process the current request.'
def respond(self):
response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in response: if chunk: if isinstance(chunk, unicodestr): chunk = chunk.encode('ISO-8859-1') self.write(chunk) finally: if hasattr(response, 'close...
'WSGI callable to begin the HTTP response.'
def start_response(self, status, headers, exc_info=None):
if (self.started_response and (not exc_info)): raise AssertionError('WSGI start_response called a second time with no exc_info.') self.started_response = True if self.req.sent_headers: try: raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) ...
'WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).'
def write(self, chunk):
if (not self.started_response): raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if ((rbo is not None) and (chunklen > rbo)): if (not self.req.sent_headers): self.req.simple_response('500 Inte...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env = {'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': req.path.decode('ISO-8859-1'), 'QUERY_STRING': req.qs.decode('ISO-8859-1'), 'REMOTE_ADDR': (req.conn.remote_addr or ''), 'REMOTE_PORT': str((req.conn.remote_port or '')), 'REQUEST_METHOD': req.method.decode('ISO-8859-1'), 'REQUEST...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env_10 = WSGIGateway_10.get_environ(self) env = env_10.copy() env['wsgi.version'] = ('u', 0) env.setdefault('wsgi.url_encoding', 'utf-8') try: env['PATH_INFO'] = req.path.decode(env['wsgi.url_encoding']) env['QUERY_STRING'] = req.qs.decode(env['wsgi.url_encoding'])...
'Wrap and return the given socket.'
def bind(self, sock):
return sock
'Wrap and return the given socket, plus WSGI environ entries.'
def wrap(self, sock):
try: s = ssl.wrap_socket(sock, do_handshake_on_connect=True, server_side=True, certfile=self.certificate, keyfile=self.private_key, ssl_version=ssl.PROTOCOL_SSLv23) except ssl.SSLError: e = sys.exc_info()[1] if (e.errno == ssl.SSL_ERROR_EOF): return (None, {}) elif (e...
'Create WSGI environ entries to be merged into each request.'
def get_environ(self, sock):
cipher = sock.cipher() ssl_environ = {'wsgi.url_scheme': 'https', 'HTTPS': 'on', 'SSL_PROTOCOL': cipher[1], 'SSL_CIPHER': cipher[0]} return ssl_environ
'Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets).'
def _safe_call(self, is_reader, call, *args, **kwargs):
start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if (is_reader and (e.args == ...
'Wrap and return the given socket.'
def bind(self, sock):
if (self.context is None): self.context = self.get_context() conn = SSLConnection(self.context, sock) self._environ = self.get_environ() return conn
'Wrap and return the given socket, plus WSGI environ entries.'
def wrap(self, sock):
return (sock, self._environ.copy())
'Return an SSL.Context from self attributes.'
def get_context(self):
c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
'Return WSGI environ entries to be merged into each request.'
def get_environ(self):
ssl_environ = {'HTTPS': 'on'} if self.certificate: cert = open(self.certificate, 'rb').read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ssl_environ.update({'SSL_SERVER_M_VERSION': cert.get_version(), 'SSL_SERVER_M_SERIAL': cert.get_serial_number()}) for (prefix, d...
'Parse the next HTTP request start-line and message-headers.'
def parse_request(self):
self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: success = self.read_request_line() except MaxSizeExceeded: self.simple_response('414 Request-URI Too Long', 'The Request-URI sent with the request exceeds the maximum ...
'Read self.rfile into self.inheaders. Return success.'
def read_request_headers(self):
try: read_headers(self.rfile, self.inheaders) except ValueError: ex = sys.exc_info()[1] self.simple_response('400 Bad Request', ex.args[0]) return False mrbs = self.server.max_request_body_size if (mrbs and (int(self.inheaders.get('Content-Length', 0)) > mrbs)): ...
'Parse a Request-URI into (scheme, authority, path). Note that Request-URI\'s must be one of:: Request-URI = "*" | absoluteURI | abs_path | authority Therefore, a Request-URI which starts with a double forward-slash cannot be a "net_path":: net_path = "//" authority [ abs_path ] Instead, it must be interpreted ...
def parse_request_uri(self, uri):
if (uri == ASTERISK): return (None, None, uri) i = uri.find('://') if ((i > 0) and (QUESTION_MARK not in uri[:i])): (scheme, remainder) = (uri[:i].lower(), uri[(i + 3):]) (authority, path) = remainder.split(FORWARD_SLASH, 1) path = (FORWARD_SLASH + path) return (schem...
'Call the gateway and write its iterable output.'
def respond(self):
mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get('Content-Length', 0)) if (mrbs and (mrbs < cl)): if (not self.sent_headers): self.simple_response('413 Requ...
'Write a simple response back to the client.'
def simple_response(self, status, msg=''):
status = str(status) buf = [(((self.server.protocol + SPACE) + status) + CRLF), ('Content-Length: %s\r\n' % len(msg)), 'Content-Type: text/plain\r\n'] if (status[:3] in ('413', '414')): self.close_connection = True if (self.response_protocol == 'HTTP/1.1'): buf.append('Conn...
'Write unbuffered data to the client.'
def write(self, chunk):
if (self.chunked_write and chunk): buf = [hex(len(chunk))[2:], CRLF, chunk, CRLF] self.conn.wfile.sendall(EMPTY.join(buf)) else: self.conn.wfile.sendall(chunk)
'Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.'
def send_headers(self):
hkeys = [key.lower() for (key, value) in self.outheaders] status = int(self.status[:3]) if (status == 413): self.close_connection = True elif ('content-length' not in hkeys): if ((status < 200) or (status in (204, 205, 304))): pass elif ((self.response_protocol == 'HT...
'Sendall for non-blocking sockets.'
def sendall(self, data):
while data: try: bytes_sent = self.send(data) data = data[bytes_sent:] except socket.error as e: if (e.args[0] not in socket_errors_nonblocking): raise
'Read each request and respond appropriately.'
def communicate(self):
request_seen = False try: while True: req = None req = self.RequestHandlerClass(self.server, self) req.parse_request() if self.server.stats['Enabled']: self.requests_seen += 1 if (not req.ready): return ...
'Close the socket underlying this connection.'
def close(self):
self.rfile.close() if (not self.linger): if hasattr(self.socket, '_sock'): self.socket._sock.close() self.socket.close() else: pass
'Start the pool of threads.'
def start(self):
for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName(('CP Server ' + worker.getName())) worker.start() for worker in self._threads: while (not worker.ready): time.sleep(0.1)
'Number of worker threads which are idle. Read-only.'
def _get_idle(self):
return len([t for t in self._threads if (t.conn is None)])
'Spawn new worker threads (not above self.max).'
def grow(self, amount):
if (self.max > 0): budget = max((self.max - len(self._threads)), 0) else: budget = float('inf') n_new = min(amount, budget) workers = [self._spawn_worker() for i in range(n_new)] while (not self._all(operator.attrgetter('ready'), workers)): time.sleep(0.1) self._threads.e...
'Kill off worker threads (not below self.min).'
def shrink(self, amount):
for t in self._threads: if (not t.isAlive()): self._threads.remove(t) amount -= 1 n_extra = max((len(self._threads) - self.min), 0) n_to_remove = min(amount, n_extra) for n in range(n_to_remove): self._queue.put(_SHUTDOWNREQUEST)
'Run the server forever.'
def start(self):
self._interrupt = None if (self.software is None): self.software = ('%s Server' % self.version) if ((self.ssl_adapter is None) and getattr(self, 'ssl_certificate', None) and getattr(self, 'ssl_private_key', None)): warnings.warn('SSL attributes are deprecated in CherryPy ...
'Create (or recreate) the actual socket object.'
def bind(self, family, type, proto=0):
self.socket = socket.socket(family, type, proto) prevent_socket_inheritance(self.socket) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if (self.nodelay and (not isinstance(self.bind_addr, str))): self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if (self.s...
'Accept a new connection and put it on the Queue.'
def tick(self):
try: (s, addr) = self.socket.accept() if self.stats['Enabled']: self.stats['Accepts'] += 1 if (not self.ready): return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.timeout) makefile = CP_fileobject ...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
self.ready = False if (self._start_time is not None): self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: if (not isinstance(self.bind_addr, basestring)): try: (host, port) = sock.getsock...
'Process the current request. Must be overridden in a subclass.'
def respond(self):
raise NotImplemented
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
raise NotImplemented
'Process the current request.'
def respond(self):
response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in response: if chunk: if isinstance(chunk, unicodestr): chunk = chunk.encode('ISO-8859-1') self.write(chunk) finally: if hasattr(response, 'close...
'WSGI callable to begin the HTTP response.'
def start_response(self, status, headers, exc_info=None):
if (self.started_response and (not exc_info)): raise AssertionError('WSGI start_response called a second time with no exc_info.') self.started_response = True if self.req.sent_headers: try: raise exc_info[0], exc_info[1], exc_info[2] finally: ...
'WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).'
def write(self, chunk):
if (not self.started_response): raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if ((rbo is not None) and (chunklen > rbo)): if (not self.req.sent_headers): self.req.simple_response('500 Inte...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env = {'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': req.path, 'QUERY_STRING': req.qs, 'REMOTE_ADDR': (req.conn.remote_addr or ''), 'REMOTE_PORT': str((req.conn.remote_port or '')), 'REQUEST_METHOD': req.method, 'REQUEST_URI': req.uri, 'SCRIPT_NAME': '', 'SERVER_NAME': req.server.se...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env_10 = WSGIGateway_10.get_environ(self) env = dict([(k.decode('ISO-8859-1'), v) for (k, v) in env_10.iteritems()]) env[u'wsgi.version'] = ('u', 0) env.setdefault(u'wsgi.url_encoding', u'utf-8') try: for key in [u'PATH_INFO', u'SCRIPT_NAME', u'QUERY_STRING']: ...
'Close and de-reference the current request and response. (Core)'
def close(self):
streaming = _cherrypy.serving.response.stream self.cpapp.release_serving() if (streaming and is_closable_iterator(self.iter_response)): iter_close = self.iter_response.close try: iter_close() except Exception: _cherrypy.log(traceback=True, severity=40)
'Create a Request object using environ.'
def run(self):
env = self.environ.get local = httputil.Host('', int(env('SERVER_PORT', 80)), env('SERVER_NAME', '')) remote = httputil.Host(env('REMOTE_ADDR', ''), int((env('REMOTE_PORT', (-1)) or (-1))), env('REMOTE_HOST', '')) scheme = env('wsgi.url_scheme') sproto = env('ACTUAL_SERVER_PROTOCOL', 'HTTP/1.1') ...
'Translate CGI-environ header names to HTTP header names.'
def translate_headers(self, environ):
for cgiName in environ: if (cgiName in self.headerNames): (yield (self.headerNames[cgiName], environ[cgiName])) elif (cgiName[:5] == 'HTTP_'): translatedHeader = cgiName[5:].replace('_', '-') (yield (translatedHeader, environ[cgiName]))
'WSGI application callable for the actual CherryPy application. You probably shouldn\'t call this; call self.__call__ instead, so that any WSGI middleware in self.pipeline can run first.'
def tail(self, environ, start_response):
return self.response_class(environ, start_response, self.cpapp)
'Config handler for the \'wsgi\' namespace.'
def namespace_handler(self, k, v):
if (k == 'pipeline'): self.pipeline.extend(v) elif (k == 'response_class'): self.response_class = v else: (name, arg) = k.split('.', 1) bucket = self.config.setdefault(name, {}) bucket[arg] = v
'Initializes a new ThreadPoolExecutor instance. Args: max_workers: The maximum number of threads that can be used to execute the given calls.'
def __init__(self, max_workers):
self._max_workers = max_workers self._work_queue = queue.Queue() self._threads = set() self._shutdown = False self._shutdown_lock = threading.Lock()
'Initializes the future. Should not be called by clients.'
def __init__(self):
self._condition = threading.Condition() self._state = PENDING self._result = None self._exception = None self._traceback = None self._waiters = [] self._done_callbacks = []
'Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.'
def cancel(self):
with self._condition: if (self._state in [RUNNING, FINISHED]): return False if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): return True self._state = CANCELLED self._condition.notify_all() self._invoke_callbacks() return True
'Return True if the future has cancelled.'
def cancelled(self):
with self._condition: return (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED])
'Return True if the future is currently executing.'
def running(self):
with self._condition: return (self._state == RUNNING)
'Return True of the future was cancelled or finished executing.'
def done(self):
with self._condition: return (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED])
'Attaches a callable that will be called when the future finishes. Args: fn: A callable that will be called with this future as its only argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or be...
def add_done_callback(self, fn):
with self._condition: if (self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]): self._done_callbacks.append(fn) return fn(self)
'Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn\'t done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. Raises: CancelledError: If the future was cancelled. TimeoutErro...
def result(self, timeout=None):
with self._condition: if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): raise CancelledError() elif (self._state == FINISHED): return self.__get_result() self._condition.wait(timeout) if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): ...
'Return a tuple of (exception, traceback) raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn\'t done. If None, then there is no limit on the wait time. Returns: The exception raised by the call that the future represents or None if the call co...
def exception_info(self, timeout=None):
with self._condition: if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): raise CancelledError() elif (self._state == FINISHED): return (self._exception, self._traceback) self._condition.wait(timeout) if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]...
'Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn\'t done. If None, then there is no limit on the wait time. Returns: The exception raised by the call that the future represents or None if the call completed without rais...
def exception(self, timeout=None):
return self.exception_info(timeout)[0]
'Mark the future as running or process any cancel notifications. Should only be used by Executor implementations and unit tests. If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is...
def set_running_or_notify_cancel(self):
with self._condition: if (self._state == CANCELLED): self._state = CANCELLED_AND_NOTIFIED for waiter in self._waiters: waiter.add_cancelled(self) return False elif (self._state == PENDING): self._state = RUNNING return True ...
'Sets the return value of work associated with the future. Should only be used by Executor implementations and unit tests.'
def set_result(self, result):
with self._condition: self._result = result self._state = FINISHED for waiter in self._waiters: waiter.add_result(self) self._condition.notify_all() self._invoke_callbacks()
'Sets the result of the future as being the given exception and traceback. Should only be used by Executor implementations and unit tests.'
def set_exception_info(self, exception, traceback):
with self._condition: self._exception = exception self._traceback = traceback self._state = FINISHED for waiter in self._waiters: waiter.add_exception(self) self._condition.notify_all() self._invoke_callbacks()
'Sets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests.'
def set_exception(self, exception):
self.set_exception_info(exception, None)
'Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call.'
def submit(self, fn, *args, **kwargs):
raise NotImplementedError()
'Returns a iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated...
def map(self, fn, *iterables, **kwargs):
timeout = kwargs.get('timeout') if (timeout is not None): end_time = (timeout + time.time()) fs = [self.submit(fn, *args) for args in zip(*iterables)] try: for future in fs: if (timeout is None): (yield future.result()) else: (yield...
'Clean-up the resources associated with the Executor. It is safe to call this method several times. Otherwise, no other methods can be called after this one. Args: wait: If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.'
def shutdown(self, wait=True):
pass
'Initializes a new ProcessPoolExecutor instance. Args: max_workers: The maximum number of processes that can be used to execute the given calls. If None or not given then as many worker processes will be created as the machine has processors.'
def __init__(self, max_workers=None):
_check_system_limits() if (max_workers is None): self._max_workers = multiprocessing.cpu_count() else: self._max_workers = max_workers self._call_queue = multiprocessing.Queue((self._max_workers + EXTRA_QUEUED_CALLS)) self._result_queue = multiprocessing.Queue() self._work_ids = ...
'Changes anything not dundered or not a descriptor. If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values). If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single un...
def __setitem__(self, key, value):
if ((pyver >= 3.0) and (key == '__order__')): return if _is_sunder(key): raise ValueError('_names_ are reserved for future Enum use') elif _is_dunder(key): pass elif (key in self._member_names): raise TypeError(('Attempted to reuse key: %r' %...
'Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum(\'Color\', names=\'red green blue\')). When used for the functional API: `module`, if set, will be...
def __call__(cls, value, names=None, module=None, type=None):
if (names is None): return cls.__new__(cls, value) return cls._create_(value, names, module=module, type=type)
'Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping.'
@property def __members__(cls):
return cls._member_map_.copy()
'Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class\' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class\' __dict__) and enum members themselves.'
def __getattr__(cls, name):
if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name)
'Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration.'
def __setattr__(cls, name, value):
member_map = cls.__dict__.get('_member_map_', {}) if (name in member_map): raise AttributeError('Cannot reassign members.') super(EnumMeta, cls).__setattr__(name, value)
'Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value....
def _create_(cls, class_name, names=None, module=None, type=None):
if (pyver < 3.0): if isinstance(class_name, unicode): try: class_name = class_name.encode('ascii') except UnicodeEncodeError: raise TypeError(('%r is not representable in ASCII' % class_name)) metacls = cls.__class__ if (type is ...
'Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__'
@staticmethod def _get_mixins_(bases):
if ((not bases) or (Enum is None)): return (object, Enum) member_type = first_enum = None for base in bases: if ((base is not Enum) and issubclass(base, Enum) and base._member_names_): raise TypeError('Cannot extend enumerations') if (not issubclass(base, Enum)): ...
'Changes anything not dundered or not a descriptor. If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values). If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single un...
def __setitem__(self, key, value):
if ((pyver >= 3.0) and (key == '__order__')): return if _is_sunder(key): raise ValueError('_names_ are reserved for future Enum use') elif _is_dunder(key): pass elif (key in self._member_names): raise TypeError(('Attempted to reuse key: %r' %...
'Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum(\'Color\', names=\'red green blue\')). When used for the functional API: `module`, if set, will be...
def __call__(cls, value, names=None, module=None, type=None):
if (names is None): return cls.__new__(cls, value) return cls._create_(value, names, module=module, type=type)
'Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping.'
@property def __members__(cls):
return cls._member_map_.copy()
'Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class\' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class\' __dict__) and enum members themselves.'
def __getattr__(cls, name):
if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name)
'Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration.'
def __setattr__(cls, name, value):
member_map = cls.__dict__.get('_member_map_', {}) if (name in member_map): raise AttributeError('Cannot reassign members.') super(EnumMeta, cls).__setattr__(name, value)
'Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value....
def _create_(cls, class_name, names=None, module=None, type=None):
if (pyver < 3.0): if isinstance(class_name, unicode): try: class_name = class_name.encode('ascii') except UnicodeEncodeError: raise TypeError(('%r is not representable in ASCII' % class_name)) metacls = cls.__class__ if (type is ...
'Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__'
@staticmethod def _get_mixins_(bases):
if ((not bases) or (Enum is None)): return (object, Enum) member_type = first_enum = None for base in bases: if ((base is not Enum) and issubclass(base, Enum) and base._member_names_): raise TypeError('Cannot extend enumerations') if (not issubclass(base, Enum)): ...
'Check the icon to see if it\'s valid If it\'s a simple URL icon, then we return True. If it\'s a data icon then we return False'
def _checkIcon(self, data):
logger.info('Checking icon') return gntp.shim.u(data).startswith('http')
'Send GNTP Registration .. warning:: Before sending notifications to Growl, you need to have sent a registration message at least once'
def register(self):
logger.info('Sending registration to %s:%s', self.hostname, self.port) register = gntp.core.GNTPRegister() register.add_header('Application-Name', self.applicationName) for notification in self.notifications: enabled = (notification in self.defaultNotifications) register.add_not...
'Send a GNTP notifications .. warning:: Must have registered with growl beforehand or messages will be ignored :param string noteType: One of the notification names registered earlier :param string title: Notification title (usually displayed on the notification) :param string description: The main content of the notif...
def notify(self, noteType, title, description, icon=None, sticky=False, priority=None, callback=None, identifier=None, custom={}):
logger.info('Sending notification [%s] to %s:%s', noteType, self.hostname, self.port) assert (noteType in self.notifications) notice = gntp.core.GNTPNotice() notice.add_header('Application-Name', self.applicationName) notice.add_header('Notification-Name', noteType) notice.add_header...
'Send a Subscribe request to a remote machine'
def subscribe(self, id, name, port):
sub = gntp.core.GNTPSubscribe() sub.add_header('Subscriber-ID', id) sub.add_header('Subscriber-Name', name) sub.add_header('Subscriber-Port', port) if self.password: sub.set_password(self.password, self.passwordHash) self.add_origin_info(sub) self.subscribe_hook(sub) return self....
'Add optional Origin headers to message'
def add_origin_info(self, packet):
packet.add_header('Origin-Machine-Name', platform.node()) packet.add_header('Origin-Software-Name', 'gntp.py') packet.add_header('Origin-Software-Version', __version__) packet.add_header('Origin-Platform-Name', platform.system()) packet.add_header('Origin-Platform-Version', platform.platform())
'Send the GNTP Packet'
def _send(self, messagetype, packet):
packet.validate() data = packet.encode() logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(self.socketTimeout) try: s.connect((self.hostname, self.port)) s.send(data) ...
'Parse the first line of a GNTP message to get security and other info values :param string data: GNTP Message :return dict: Parsed GNTP Info line'
def _parse_info(self, data):
match = GNTP_INFO_LINE.match(data) if (not match): raise errors.ParseError('ERROR_PARSING_INFO_LINE') info = match.groupdict() if (info['encryptionAlgorithmID'] == 'NONE'): info['encryptionAlgorithmID'] = None return info
'Set a password for a GNTP Message :param string password: Null to clear password :param string encryptAlgo: Supports MD5, SHA1, SHA256, SHA512'
def set_password(self, password, encryptAlgo='MD5'):
if (not password): self.info['encryptionAlgorithmID'] = None self.info['keyHashAlgorithm'] = None return self.password = gntp.shim.b(password) self.encryptAlgo = encryptAlgo.upper() if (not (self.encryptAlgo in self.hash_algo)): raise errors.UnsupportedError(('INVALID ...
'Helper function to decode hex string to `proper` hex string :param string value: Human readable hex string :return string: Hex string'
def _decode_hex(self, value):
result = '' for i in range(0, len(value), 2): tmp = int(value[i:(i + 2)], 16) result += chr(tmp) return result
'Validate GNTP Message against stored password'
def _validate_password(self, password):
self.password = password if (password is None): raise errors.AuthError('Missing password') keyHash = self.info.get('keyHash', None) if ((keyHash is None) and (self.password is None)): return True if (keyHash is None): raise errors.AuthError('Invalid keyHash') if (se...
'Verify required headers'
def validate(self):
for header in self._requiredHeaders: if (not self.headers.get(header, False)): raise errors.ParseError(('Missing Notification Header: ' + header))
'Generate info line for GNTP Message :return string:'
def _format_info(self):
info = ('GNTP/%s %s' % (self.info.get('version'), self.info.get('messagetype'))) if self.info.get('encryptionAlgorithmID', None): info += (' %s:%s' % (self.info.get('encryptionAlgorithmID'), self.info.get('ivValue'))) else: info += ' NONE' if self.info.get('keyHashAlgorithmID', ...
'Helper function to parse blocks of GNTP headers into a dictionary :param string data: :return dict: Dictionary of parsed GNTP Headers'
def _parse_dict(self, data):
d = {} for line in data.split('\r\n'): match = GNTP_HEADER.match(line) if (not match): continue key = match.group(1).strip() val = match.group(2).strip() d[key] = val return d
'Add binary resource :param string data: Binary Data'
def add_resource(self, data):
data = gntp.shim.b(data) identifier = hashlib.md5(data).hexdigest() self.resources[identifier] = data return ('x-growl-resource://%s' % identifier)
'Decode GNTP Message :param string data:'
def decode(self, data, password=None):
self.password = password self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self.headers = self._parse_dict(parts[0])
'Encode a generic GNTP Message :return string: GNTP Message ready to be sent. Returned as a byte string'
def encode(self):
buff = _GNTPBuffer() buff.writeln(self._format_info()) for (k, v) in self.headers.items(): buff.writeheader(k, v) buff.writeln() for (resource, data) in self.resources.items(): buff.writeheader('Identifier', resource) buff.writeheader('Length', len(data)) buff.writeln...
'Validate required headers and validate notification headers'
def validate(self):
for header in self._requiredHeaders: if (not self.headers.get(header, False)): raise errors.ParseError(('Missing Registration Header: ' + header)) for notice in self.notifications: for header in self._requiredNotificationHeaders: if (not notice.get(header, False)...
'Decode existing GNTP Registration message :param string data: Message to decode'
def decode(self, data, password):
self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) for (i, part) in enumerate(parts): if (i == 0): continue if (part.strip() == ''): ...
'Add new Notification to Registration message :param string name: Notification Name :param boolean enabled: Enable this notification by default'
def add_notification(self, name, enabled=True):
notice = {} notice['Notification-Name'] = name notice['Notification-Enabled'] = enabled self.notifications.append(notice) self.add_header('Notifications-Count', len(self.notifications))
'Encode a GNTP Registration Message :return string: Encoded GNTP Registration message. Returned as a byte string'
def encode(self):
buff = _GNTPBuffer() buff.writeln(self._format_info()) for (k, v) in self.headers.items(): buff.writeheader(k, v) buff.writeln() if (len(self.notifications) > 0): for notice in self.notifications: for (k, v) in notice.items(): buff.writeheader(k, v) ...
'Decode existing GNTP Notification message :param string data: Message to decode.'
def decode(self, data, password):
self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) for (i, part) in enumerate(parts): if (i == 0): continue if (part.strip() == ''): ...
'Return a mapping from field names to getter functions.'
@classmethod def _getters(cls):
raise NotImplementedError()
'Return a mapping from function names to text-transformer functions.'
def _template_funcs(self):
raise NotImplementedError()
'Create a new object with an optional Database association and initial field values.'
def __init__(self, db=None, **values):
self._db = db self._dirty = set() self._values_fixed = {} self._values_flex = {} self.update(values) self.clear_dirty()