text
stringlengths
81
112k
Remove all blocks from the queue and all sub-queues def unblockall(self): ''' Remove all blocks from the queue and all sub-queues ''' for q in self.queues.values(): q.unblockall() self.blockEvents.clear()
Internal notify for sub-queues :returns: If the append is blocked by parent, an EventMatcher is returned, None else. def notifyAppend(self, queue, force): ''' Internal notify for sub-queues :returns: If the append is blocked by parent, an EventMatcher is returned, None...
Internal notify for sub-queues been blocked def notifyBlock(self, queue, blocked): ''' Internal notify for sub-queues been blocked ''' if blocked: if self.prioritySet[-1] == queue.priority: self.prioritySet.pop() else: pindex = bis...
Internal notify for sub-queues been poped :returns: List of any events generated by this pop def notifyPop(self, queue, length = 1): ''' Internal notify for sub-queues been poped :returns: List of any events generated by this pop ''' self.totalSize = se...
Pop an event from the queue. The event in the queue with higher priority is popped before ones in lower priority. If there are multiple queues with the same priority, events are taken in turn from each queue. May return some queueEvents indicating that some of the queues can be written into. ...
Actual pop def _pop(self): ''' Actual pop ''' if not self.canPop(): raise IndexError('pop from an empty or blocked queue') priority = self.prioritySet[-1] ret = self.queues[priority]._pop() self.outputStat = self.outputStat + 1 self.totalSize ...
Clear all the events in this queue, including any sub-queues. :returns: ((queueEvents,...), (queueEmptyEvents,...)) where queueEvents are QueueCanWriteEvents generated by clearing. def clear(self): ''' Clear all the events in this queue, including any sub-queues. :retu...
Actual clear def _clear(self): ''' Actual clear ''' ret = ([],[]) for q in self.queues.values(): pr = q._clear() ret[0].extend(pr[0]) ret[1].extend(pr[1]) self.totalSize = 0 del self.prioritySet[:] if self.isWaited and ...
Set priority of a sub-queue def setPriority(self, queue, priority): ''' Set priority of a sub-queue ''' q = self.queueindex[queue] self.queues[q[0]].removeSubQueue(q[1]) newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority)) q[0] = pri...
add a sub queue to current queue, with a priority and a matcher :param priority: priority of this queue. Larger is higher, 0 is lowest. :param matcher: an event matcher to catch events. Every event match the criteria will be stored in this queue. :param name: a unique ...
remove a sub queue from current queue. This unblock the sub-queue, retrieve all events from the queue and put them back to the parent. Call clear on the sub-queue first if the events are not needed any more. :param queue: the name or queue object to remove ...
Use walk to try to retrieve all keys def ensure_keys(walk, *keys): """ Use walk to try to retrieve all keys """ all_retrieved = True for k in keys: try: walk(k) except WalkKeyNotRetrieved: all_retrieved = False return all_retrieved
Walk through all the sub modules, find subclasses of vlcp.config.Configurable, list their available configurations through _default_ prefix def list_config(root_package = 'vlcp'): ''' Walk through all the sub modules, find subclasses of vlcp.config.Configurable, list their available configurations thro...
wrap a WSGI-style class method to a HTTPRequest event handler def http(container = None): "wrap a WSGI-style class method to a HTTPRequest event handler" def decorator(func): @functools.wraps(func) def handler(self, event): return _handler(self if container is None else container, e...
wrap a WSGI-style function to a HTTPRequest event handler def statichttp(container = None): "wrap a WSGI-style function to a HTTPRequest event handler" def decorator(func): @functools.wraps(func) def handler(event): return _handler(container, event, func) if hasattr(func, '_...
Start to send response def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False): "Start to send response" if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.status = status ...
Send a new header def header(self, key, value, replace = True): "Send a new header" if hasattr(key, 'encode'): key = key.encode('ascii') if hasattr(value, 'encode'): value = value.encode(self.encoding) if replace: self.sent_headers = [(k,v) for k,v in...
Add a header with "<Header>: Value" string def rawheader(self, kv, replace = True): """ Add a header with "<Header>: Value" string """ if hasattr(kv, 'encode'): kv = kv.encode(self.encoding) k,v = kv.split(b':', 1) self.header(k, v.strip(), replace)
Add a new cookie def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): """ Add a new cookie """ newcookie = Morsel() newcookie.key = key newcookie.value = value newcookie.coded_value = value if ma...
Buffer the whole output until write EOF or flushed. def bufferoutput(self): """ Buffer the whole output until write EOF or flushed. """ new_stream = Stream(writebufferlimit=None) if self._sendHeaders: # An extra copy self.container.subroutine(new_stream.c...
Rewrite this request to another processor. Must be called before header sent async def rewrite(self, path, method = None, keepresponse = True): "Rewrite this request to another processor. Must be called before header sent" if self._sendHeaders: raise HttpProtocolException('Cannot modify res...
Redirect this request with 3xx status async def redirect(self, path, status = 302): """ Redirect this request with 3xx status """ location = urljoin(urlunsplit((b'https' if self.https else b'http', self.host, ...
Replace \'\n\' with \'<br/>\\n\' def nl2br(self, text): """ Replace \'\n\' with \'<br/>\\n\' """ if isinstance(text, bytes): return text.replace(b'\n', b'<br/>\n') else: return text.replace('\n', '<br/>\n')
Escape special characters in HTML def escape(self, text, quote = True): """ Escape special characters in HTML """ if isinstance(text, bytes): return escape_b(text, quote) else: return escape(text, quote)
Show default error response async def error(self, status=500, allowredirect = True, close = True, showerror = None, headers = []): """ Show default error response """ if showerror is None: showerror = self.showerrorinfo if self._sendHeaders: if showerror:...
Write output to current output stream async def write(self, data, eof = False, buffering = True): """ Write output to current output stream """ if not self.outputstream: self.outputstream = Stream() self._startResponse() elif (not buffering or eof) and no...
Write lines to current output stream async def writelines(self, lines, eof = False, buffering = True): """ Write lines to current output stream """ for l in lines: await self.write(l, False, buffering) if eof: await self.write(b'', eof, buffering)
Set output stream and send response immediately def output(self, stream, disabletransferencoding = None): """ Set output stream and send response immediately """ if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.ou...
Send output with fixed length data def outputdata(self, data): """ Send output with fixed length data """ if not isinstance(data, bytes): data = str(data).encode(self.encoding) self.output(MemoryStream(data))
Close this request, send all data. You can still run other operations in the handler. async def close(self): """ Close this request, send all data. You can still run other operations in the handler. """ if not self._sendHeaders: self._startResponse() if self.inputstr...
Parse form-data with multipart/form-data or application/x-www-form-urlencoded In Python3, the keys of form and files are unicode, but values are bytes If the key ends with '[]', it is considered to be a list: a=1&b=2&b=3 => {'a':1,'b':3} a[]=1&b[]=2&b[]=3 => {'a':[1],'b...
Start session. Must start service.utils.session.Session to use this method async def sessionstart(self): "Start session. Must start service.utils.session.Session to use this method" if not hasattr(self, 'session') or not self.session: self.session, setcookies = await call_api(self.container...
Destroy current session. The session object is discarded and can no longer be used in other requests. async def sessiondestroy(self): """ Destroy current session. The session object is discarded and can no longer be used in other requests. """ if hasattr(self, 'session') and self.sessio...
Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise def basicauth(self, realm = b'all', nofail = False): "Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise" if b'authorization' in self.headerdict: ...
Return 401 for authentication failure. This will end the handler. def basicauthfail(self, realm = b'all'): """ Return 401 for authentication failure. This will end the handler. """ if not isinstance(realm, bytes): realm = realm.encode('ascii') self.start_response(401...
Return the real path on disk from the query path, from a root path. The input path from URL might be absolute '/abc', or point to parent '../test', or even with UNC or drive '\\test\abc', 'c:\test.abc', which creates security issues when accessing file contents with the path. With getrea...
Query string arguments are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8). def argstostr(self): "Query string arguments are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8)." self.args = dict((k, self._tostr(v)) for...
Cookie values are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8). def cookietostr(self): "Cookie values are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8)." self.cookies = dict((k, (v.decode(self.encoding) if not ...
Create a anti-CSRF token in the session async def createcsrf(self, csrfarg = '_csrf'): """ Create a anti-CSRF token in the session """ await self.sessionstart() if not csrfarg in self.session.vars: self.session.vars[csrfarg] = uuid.uuid4().hex
Serialize `obj` with JSON and output to the client def outputjson(self, obj): """ Serialize `obj` with JSON and output to the client """ self.header('Content-Type', 'application/json') self.outputdata(json.dumps(obj).encode('ascii'))
Route specified path to a routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routinemethod(event), event is the HttpRequestEvent :param container: routine container. If None, default to self for bound method,...
Route specified path to a WSGI-styled routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routinemethod(env), env is an Environment object see also utils.http.Environment :param container: rout...
Convenient way to route a processor with arguments. Automatically parse arguments and pass them to the corresponding handler arguments. If required arguments are missing, HttpInputException is thrown which creates a 400 Bad Request response. If optional arguments are missing, they are replaced with defa...
If use expand directly, the url-decoded context will be decoded again, which create a security issue. Hack expand to quote the text before expanding def expand(cls, match, expand): """ If use expand directly, the url-decoded context will be decoded again, which create a security issue. ...
Automatically rewrite a request to another location def rewrite(self, path, expand, newmethod = None, host = None, vhost = None, method = [b'GET', b'HEAD'], keepquery = True): "Automatically rewrite a request to another location" async def func(env): newpath = self.expand(env.path_match, ex...
For extra arguments, see Dispatcher.routeargs. They must be specified by keyword arguments def routeargs(path, host = None, vhost = None, method = [b'POST'], **kwargs): "For extra arguments, see Dispatcher.routeargs. They must be specified by keyword arguments" def decorator(func): func.rou...
PyPy 3 generator has a bug that calling `close` caused memory leak. Before it is fixed, use `throw` instead def _close_generator(g): """ PyPy 3 generator has a bug that calling `close` caused memory leak. Before it is fixed, use `throw` instead """ if isinstance(g, generatorwrapper): g....
This wraps a normal coroutine to become a VLCP routine. Usually you do not need to call this yourself; `container.start` and `container.subroutine` calls this automatically. def Routine(coroutine, scheduler, asyncStart = True, container = None, manualStart = False, daemon = False): """ This wraps a normal ...
Register self to scheduler def registerHandler(self, matcher, handler): ''' Register self to scheduler ''' self.handlers[matcher] = handler self.scheduler.register((matcher,), self) self._setDaemon()
Register self to scheduler def registerAllHandlers(self, handlerDict): ''' Register self to scheduler ''' self.handlers.update(handlerDict) if hasattr(handlerDict, 'keys'): self.scheduler.register(handlerDict.keys(), self) else: self.scheduler.reg...
Start `container.main` as the main routine. :param asyncStart: if True, start the routine in background. By default, the routine starts in foreground, which means it is executed to the first `yield` statement before returning. If the started routine...
Start extra routines in this container. :param iterator: A coroutine object i.e the return value of an async method `my_routine()` :param asyncStart: if False, start the routine in foreground. By default, the routine starts in background, which means it is no...
Send an event to the main event queue. Can call without delegate. :param until: if the callback returns True, stop sending and return :return: the last True value the callback returns, or None async def wait_for_send(self, event, *, until=None): ''' Send an event to th...
Wait for multiple event matchers, or until timeout. :param timeout: a timeout value :param \*matchers: event matchers :return: (is_timeout, event, matcher). When is_timeout = True, event = matcher = None. async def wait_with_timeout(self, timeout, *matchers): ...
Execute a subprocess with timeout. If time limit exceeds, the subprocess is terminated, and `is_timeout` is set to True; otherwise the `is_timeout` is set to False. You can uses `execute_with_timeout` with other help functions to create time limit for them:: timeout, result...
Monitoring event matchers while executing a subprocess. If events are matched before the subprocess ends, the subprocess is terminated and a RoutineException is raised. async def with_exception(self, subprocess, *matchers): """ Monitoring event matchers while executing a subprocess. If events a...
Monitoring event matchers while executing a subprocess. `callback(event, matcher)` is called each time an event is matched by any event matchers. If the callback raises an exception, the subprocess is terminated. :param intercept_callback: a callback called before a event is delegated to the in...
Wait until each matcher matches an event. When this coroutine method returns, `eventlist` is set to the list of events in the arriving order (may not be the same as the matchers); `eventdict` is set to a dictionary `{matcher1: event1, matcher2: event2, ...}` :param eventlist: us...
Similar to `waitForAll`, but set `canignore=True` for these events. This ensures blocking events are processed correctly. async def wait_for_all_to_process(self, *matchers, eventlist = None, eventdict = None, callback = None): """ Similar to `waitForA...
Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers async def wait_for_all_empty(self, *queues): """ Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines runnin...
Call a syscall method. A syscall method is executed outside of any routines, directly in the scheduler loop, which gives it chances to directly operate the event loop. See :py:method::`vlcp.event.core.Scheduler.syscall`. def syscall_noreturn(self, func): ''' Call a syscall method. A sys...
Call a syscall method and retrieve its return value async def syscall(self, func, ignoreException = False): """ Call a syscall method and retrieve its return value """ ev = await self.syscall_noreturn(func) if hasattr(ev, 'exception'): if ignoreException: ...
Run a subprocess without container support Many subprocess assume itself running in a specified container, it uses container reference like self.events. Calling the subprocess in other containers will fail. With delegate, you can call a subprocess in any container (or without a...
Retrieve a begin_delegate result. Must be called immediately after begin_delegate before any other `await`, or the result might be lost. Do not use this method without thinking. Always use `RoutineFuture` when possible. async def end_delegate(self, delegate_matcher, routine = None, forceclose ...
Start the delegate routine, but do not wait for result, instead returns a (matcher, routine) tuple. Useful for advanced delegates (e.g. delegate multiple subprocesses in the same time). This is NOT a coroutine method. WARNING: this is not a safe way for asynchronous executing and get th...
DEPRECATED Start the delegate routine, but do not wait for result, instead returns a (matcher routine) tuple. Useful for advanced delegates (e.g. delegate multiple subprocesses in the same time). This is NOT a coroutine method. :param subprocess: a coroutine :param cont...
DEPRECATED Another format of delegate allows delegate a subprocess in another container, and get some returning values the subprocess is actually running in 'container'. :: ret = await self.delegate_other(c.method(), c) :return: a tuple for retnames values async def delega...
DEPRECATED Execute all subprocesses and get the return values. :param subprocesses: sequence of subroutines (coroutines) :param container: if specified, run subprocesses in another container. :param retnames: DEPRECATED get return value from container.(name) for each n...
Execute all subprocesses and get the return values. :param subprocesses: sequence of subroutines (coroutines) :param forceclose: force close the routines on exit, so all the subprocesses are terminated on timeout if used with executeWithTimeout ...
Create temporary instance for helper functions def get_container(cls, scheduler): """ Create temporary instance for helper functions """ if scheduler in cls._container_cache: return cls._container_cache[scheduler] else: c = cls(scheduler) cls....
Decorator to declare dependencies to other modules. Recommended usage is:: import other_module @depend(other_module.ModuleClass) class MyModule(Module): ... :param \*args: depended module classes. def depend(*args): """ Decorator to declare dependencie...
Return an API def for a generic function :param func: a function or bounded method :param container: if None, this is used as a synchronous method, the return value of the method is used for the return value. If not None, this is used as an asynchronous method, ...
Create a proxy module. A proxy module has a default implementation, but can be redirected to other implementations with configurations. Other modules can depend on proxy modules. def proxy(name, default = None): """ Create a proxy module. A proxy module has a default implementation, but can be redirected t...
Send API and discard the result async def send_api(container, targetname, name, params = {}): """ Send API and discard the result """ handle = object() apiEvent = ModuleAPICall(handle, targetname, name, params = params) await container.wait_for_send(apiEvent)
Call module API `targetname/name` with parameters. :param targetname: module targetname. Usually the lower-cased name of the module class, or 'public' for public APIs. :param name: method name :param params: module API parameters, should be a dictionary of `{parameter: ...
DEPRECATED - use execute_all instead async def batch_call_api(container, apis, timeout = 120.0): """ DEPRECATED - use execute_all instead """ apiHandles = [(object(), api) for api in apis] apiEvents = [ModuleAPICall(handle, targetname, name, params = params) for handle, (targetname...
API definition is in format: `(name, handler, container, discoverinfo)` if the handler is a generator, container should be specified handler should accept two arguments:: def handler(name, params): ... `name` is the method name, `params` is ...
Append new API to this handler def registerAPI(self, name, handler, container = None, discoverinfo = None, criteria = None): """ Append new API to this handler """ self.handler.registerHandler(*self._createHandler(name, handler, container, criteria)) if discoverinfo is None: ...
Remove an API from this handler def unregisterAPI(self, name): """ Remove an API from this handler """ if name.startswith('public/'): target = 'public' name = name[len('public/'):] else: target = self.servicename name = name ...
Discover API definitions. Set details=true to show details def discover(self, details = False): 'Discover API definitions. Set details=true to show details' if details and not (isinstance(details, str) and details.lower() == 'false'): return copy.deepcopy(self.discoverinfo) else: ...
Load a module class async def loadmodule(self, module): ''' Load a module class ''' self._logger.debug('Try to load module %r', module) if hasattr(module, '_instance'): self._logger.debug('Module is already initialized, module state is: %r', module._instance.state) ...
Unload a module class async def unloadmodule(self, module, ignoreDependencies = False): ''' Unload a module class ''' self._logger.debug('Try to unload module %r', module) if hasattr(module, '_instance'): self._logger.debug('Module %r is loaded, module state is %r', ...
Load a module by full path. If there are dependencies, they are also loaded. async def load_by_path(self, path): """ Load a module by full path. If there are dependencies, they are also loaded. """ try: p, module = findModule(path, True) except KeyError as exc: ...
Unload a module by full path. Dependencies are automatically unloaded if they are marked to be services. async def unload_by_path(self, path): """ Unload a module by full path. Dependencies are automatically unloaded if they are marked to be services. """ p, module = fin...
Reload modules with a full path in the pathlist async def reload_modules(self, pathlist): """ Reload modules with a full path in the pathlist """ loadedModules = [] failures = [] for path in pathlist: p, module = findModule(path, False) if module ...
Return the module instance for a target name. def get_module_by_name(self, targetname): """ Return the module instance for a target name. """ if targetname == 'public': target = None elif not targetname not in self.activeModules: raise KeyError('Module %r...
Decorator to set this class to configuration base class. A configuration base class uses `<parentbase>.key.` for its configuration base, and uses `<parentbase>.key.default` for configuration mapping. def configbase(key): """ Decorator to set this class to configuration base class. A configuration base clas...
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping. def config(key): """ Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping. ...
Generate a default configuration mapping bases on the class name. If this class does not have a parent with `configbase` defined, it is set to a configuration base with `configbase=<lowercase-name>` and `configkey=<lowercase-name>.default`; otherwise it inherits `configbase` of its parent and set `configkey...
Return all configuration keys in this node, including configurations on children nodes. def config_keys(self, sortkey = False): """ Return all configuration keys in this node, including configurations on children nodes. """ if sortkey: items = sorted(self.items()) el...
Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes. def config_items(self, sortkey = False): """ Return all `(key, value)` tuples for configurations in this node, including configurations on children nodes. """ if sortkey: ...
Return configuration keys directly stored in this node. Configurations in child nodes are not included. def config_value_keys(self, sortkey = False): """ Return configuration keys directly stored in this node. Configurations in child nodes are not included. """ if sortkey: i...
Copy all configurations from this node into obj def loadconfig(self, keysuffix, obj): """ Copy all configurations from this node into obj """ subtree = self.get(keysuffix) if subtree is not None and isinstance(subtree, ConfigTree): for k,v in subtree.items(): ...
Load configurations with this decorator def withconfig(self, keysuffix): """ Load configurations with this decorator """ def decorator(cls): return self.loadconfig(keysuffix, cls) return decorator
Get a subtree node from the key (path relative to this node) def gettree(self, key, create = False): """ Get a subtree node from the key (path relative to this node) """ tree, _ = self._getsubitem(key + '.tmp', create) return tree
Support dict-like get (return a default value if not found) def get(self, key, defaultvalue = None): """ Support dict-like get (return a default value if not found) """ (t, k) = self._getsubitem(key, False) if t is None: return defaultvalue else: ...
Support dict-like setdefault (create if not existed) def setdefault(self, key, defaultvalue = None): """ Support dict-like setdefault (create if not existed) """ (t, k) = self._getsubitem(key, True) return t.__dict__.setdefault(k, defaultvalue)
Convert this node to a dictionary tree. def todict(self): """ Convert this node to a dictionary tree. """ dict_entry = [] for k,v in self.items(): if isinstance(v, ConfigTree): dict_entry.append((k, v.todict())) else: dict_...
Read configurations from a file-like object, or a sequence of strings. Old values are not cleared, if you want to reload the configurations completely, you should call `clear()` before using `load*` methods. def loadfromfile(self, filelike): """ Read configurations from a file-like obje...
Save configurations to a list of strings def save(self, sortkey = True): """ Save configurations to a list of strings """ return [k + '=' + repr(v) for k,v in self.config_items(sortkey)]