INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Write a chunk:: chunk-size(hex) CRLF chunk-data CRLF If the size is 0, this is the last chunk, and an extra CRLF is appended.
def chunk_encoding(chunks, chunk): '''Write a chunk:: chunk-size(hex) CRLF chunk-data CRLF If the size is 0, this is the last chunk, and an extra CRLF is appended. ''' chunks.extend(("%X\r\n" % len(chunk)).encode('utf-8')) chunks.extend(chunk) chunks.extend(CRLF)
Obtain the ``arbiter``. It returns the arbiter instance only if we are on the arbiter context domain, otherwise it returns nothing.
def arbiter(**params): '''Obtain the ``arbiter``. It returns the arbiter instance only if we are on the arbiter context domain, otherwise it returns nothing. ''' arbiter = get_actor() if arbiter is None: # Create the arbiter return set_actor(_spawn_actor('arbiter', None, **param...
Spawn a new :class:`Actor` and return its :class:`.ActorProxyMonitor`.
def spawn(self, monitor, kind=None, **params): '''Spawn a new :class:`Actor` and return its :class:`.ActorProxyMonitor`. ''' proxy = _spawn_actor(kind, monitor, **params) # Add to the list of managed actors if this is a remote actor if isinstance(proxy, Actor): ...
Remove :class:`Actor` which are not alive from the :class:`PoolMixin.managed_actors` and return the number of actors still alive. :parameter stop: if ``True`` stops all alive actor.
def manage_actors(self, monitor, stop=False): '''Remove :class:`Actor` which are not alive from the :class:`PoolMixin.managed_actors` and return the number of actors still alive. :parameter stop: if ``True`` stops all alive actor. ''' alive = 0 if self.managed_ac...
If an actor failed to notify itself to the arbiter for more than the timeout, stop the actor. :param actor: the :class:`Actor` to manage. :param stop: if ``True``, stop the actor. :return: if the actor is alive 0 if it is not.
def manage_actor(self, monitor, actor, stop=False): '''If an actor failed to notify itself to the arbiter for more than the timeout, stop the actor. :param actor: the :class:`Actor` to manage. :param stop: if ``True``, stop the actor. :return: if the actor is alive 0 if it is no...
Spawn new actors if needed.
def spawn_actors(self, monitor): '''Spawn new actors if needed. ''' to_spawn = monitor.cfg.workers - len(self.managed_actors) if monitor.cfg.workers and to_spawn > 0: for _ in range(to_spawn): monitor.spawn()
Maintain the number of workers by spawning or killing as required
def stop_actors(self, monitor): """Maintain the number of workers by spawning or killing as required """ if monitor.cfg.workers: num_to_kill = len(self.managed_actors) - monitor.cfg.workers for i in range(num_to_kill, 0, -1): w, kage = 0, sys.maxsize ...
Add a new ``monitor``. :param monitor_class: a :class:`.Monitor` class. :param monitor_name: a unique name for the monitor. :param kwargs: dictionary of key-valued parameters for the monitor. :return: the :class:`.Monitor` added.
def add_monitor(self, actor, monitor_name, **params): '''Add a new ``monitor``. :param monitor_class: a :class:`.Monitor` class. :param monitor_name: a unique name for the monitor. :param kwargs: dictionary of key-valued parameters for the monitor. :return: the :class:`.Monitor`...
Override the :meth:`.Concurrency.periodic_task` to implement the :class:`.Arbiter` :ref:`periodic task <actor-periodic-task>`.
async def periodic_task(self, actor, **kw): """Override the :meth:`.Concurrency.periodic_task` to implement the :class:`.Arbiter` :ref:`periodic task <actor-periodic-task>`. """ while True: interval = 0 # if actor.started(): # managed a...
Create a new :class:`Store` for a valid ``url``. :param url: a valid ``url`` takes the following forms: :ref:`Pulsar datastore <store_pulsar>`:: pulsar://user:password@127.0.0.1:6410 :ref:`Redis <store_redis>`:: redis://user:password@127.0.0.1:6500/11?namespace=testdb ...
def create_store(url, **kw): '''Create a new :class:`Store` for a valid ``url``. :param url: a valid ``url`` takes the following forms: :ref:`Pulsar datastore <store_pulsar>`:: pulsar://user:password@127.0.0.1:6410 :ref:`Redis <store_redis>`:: redis://user:password@1...
Publish a new event ``message`` to a ``channel``.
def publish_event(self, channel, event, message): '''Publish a new event ``message`` to a ``channel``. ''' assert self.protocol is not None, "Protocol required" msg = {'event': event, 'channel': channel} if message: msg['data'] = message return self.publish(ch...
Broadcast ``message`` to all :attr:`clients`.
def broadcast(self, response): '''Broadcast ``message`` to all :attr:`clients`.''' remove = set() channel = to_string(response[0]) message = response[1] if self.protocol: try: message = self.protocol.decode(message) except ProtocolError: ...
Parse an error response
def response_error(response): "Parse an error response" response = response.split(' ') error_code = response[0] if error_code not in EXCEPTION_CLASSES: error_code = 'ERR' response = ' '.join(response[1:]) return EXCEPTION_CLASSES[error_code](response)
Spawn a new actor from ``actor``.
def spawn(self, actor, aid=None, **params): '''Spawn a new actor from ``actor``. ''' aid = aid or create_aid() future = actor.send('arbiter', 'spawn', aid=aid, **params) return actor_proxy_future(aid, future)
Start running the ``actor``.
def run_actor(self, actor): '''Start running the ``actor``. ''' set_actor(actor) if not actor.mailbox.address: address = ('127.0.0.1', 0) actor._loop.create_task( actor.mailbox.start_serving(address=address) ) actor._loop.run_fo...
Set up the event loop for ``actor``.
def setup_event_loop(self, actor): '''Set up the event loop for ``actor``. ''' actor.logger = self.cfg.configured_logger('pulsar.%s' % actor.name) try: loop = asyncio.get_event_loop() except RuntimeError: if self.cfg and self.cfg.concurrency == 'thread': ...
Perform the hand shake for ``actor`` The hand shake occurs when the ``actor`` is in starting state. It performs the following actions: * set the ``actor`` as the actor of the current thread * bind two additional callbacks to the ``start`` event * fire the ``start`` event ...
def hand_shake(self, actor, run=True): '''Perform the hand shake for ``actor`` The hand shake occurs when the ``actor`` is in starting state. It performs the following actions: * set the ``actor`` as the actor of the current thread * bind two additional callbacks to the ``start...
Create the mailbox for ``actor``.
def create_mailbox(self, actor, loop): '''Create the mailbox for ``actor``.''' client = MailboxClient(actor.monitor.address, actor, loop) loop.call_soon_threadsafe(self.hand_shake, actor) return client
Gracefully stop the ``actor``.
def stop(self, actor, exc=None, exit_code=None): """Gracefully stop the ``actor``. """ if actor.state <= ACTOR_STATES.RUN: # The actor has not started the stopping process. Starts it now. actor.state = ACTOR_STATES.STOPPING actor.event('start').clear() ...
Given an actor unique id return the actor proxy.
def get_actor(self, actor, aid, check_monitor=True): '''Given an actor unique id return the actor proxy.''' a = super().get_actor(actor, aid) if a is None: if aid in self.monitors: # Check in monitors aid return self.monitors[aid] elif aid in self.managed...
Override :meth:`.Concurrency.create_mailbox` to create the mailbox server.
def create_mailbox(self, actor, loop): '''Override :meth:`.Concurrency.create_mailbox` to create the mailbox server. ''' mailbox = TcpServer(mailbox_protocol, loop=loop, name='mailbox') # when the mailbox stop, close the event loop too mailbox.event('stop').bind(lambda _,...
Parse an HTTP basic/digest authorisation header. :param value: the authorisation header to parse. :return: either `None` if the header was invalid or not given, otherwise an :class:`Auth` object.
def parse_authorization_header(value, charset='utf-8'): '''Parse an HTTP basic/digest authorisation header. :param value: the authorisation header to parse. :return: either `None` if the header was invalid or not given, otherwise an :class:`Auth` object. ''' if not value: return ...
Convert the stored values into a WWW-Authenticate header.
def _auth_header(self, type, **options): """Convert the stored values into a WWW-Authenticate header.""" return '%s %s' % (type.title(), ', '.join(( '%s=%s' % (key, quote_header_value( value, allow_token=key not in _require_quoting)) for key, value in options.item...
Called by the server to check if client is authenticated.
def authenticated(self, environ, username=None, password=None, **params): '''Called by the server to check if client is authenticated.''' if username != self.username: return False o = self.options qop = o.get('qop') method = environ['REQUEST_METHOD'] uri = en...
Register a callback to ``channel_name`` and ``event``. A prefix will be added to the channel name if not already available or the prefix is an empty string :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs ...
async def register(self, channel, event, callback): """Register a callback to ``channel_name`` and ``event``. A prefix will be added to the channel name if not already available or the prefix is an empty string :param channel: channel name :param event: event name :para...
Safely unregister a callback from the list of ``event`` callbacks for ``channel_name``. :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel object where the ...
async def unregister(self, channel, event, callback): """Safely unregister a callback from the list of ``event`` callbacks for ``channel_name``. :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :retur...
Connect with store :return: a coroutine and therefore it must be awaited
async def connect(self, next_time=None): """Connect with store :return: a coroutine and therefore it must be awaited """ if self.status in can_connect: loop = self._loop if loop.is_running(): self.status = StatusType.connecting awa...
Register a ``callback`` for ``event``
def register(self, event, callback): """Register a ``callback`` for ``event`` """ pattern = self.channels.event_pattern(event) entry = self.callbacks.get(pattern) if not entry: entry = event_callbacks(event, pattern, re.compile(pattern), []) self.callbacks...
Chain a :class:`~asyncio.Future` to an existing ``future``. This function `chain` the ``next`` future to an existing ``future``. When the input ``future`` receive a result the optional ``callback`` is executed and its result set as the results of ``next``. If an exception occurs the optional ``errback`...
def chain_future(future, callback=None, errback=None, next=None): '''Chain a :class:`~asyncio.Future` to an existing ``future``. This function `chain` the ``next`` future to an existing ``future``. When the input ``future`` receive a result the optional ``callback`` is executed and its result set as th...
Add a ``callback`` to a ``future`` executed only if an exception or cancellation has occurred.
def add_errback(future, callback, loop=None): '''Add a ``callback`` to a ``future`` executed only if an exception or cancellation has occurred.''' def _error_back(fut): if fut._exception: callback(fut.exception()) elif fut.cancelled(): callback(CancelledError()) ...
The asynchronous equivalent of ``while while_clause(*args):`` Use this function within a :ref:`coroutine <coroutine>` when you need to wait ``while_clause`` to be satisfied. :parameter timeout: a timeout in seconds after which this function stop. :parameter while_clause: while clause callable. :pa...
async def async_while(timeout, while_clause, *args): '''The asynchronous equivalent of ``while while_clause(*args):`` Use this function within a :ref:`coroutine <coroutine>` when you need to wait ``while_clause`` to be satisfied. :parameter timeout: a timeout in seconds after which this function stop....
Useful utility for benchmarking an asynchronous ``method``. :param method: the name of the ``method`` to execute :param times: number of times to execute the ``method`` :param args: positional arguments to pass to the ``method`` :param kwargs: key-valued arguments to pass to the ``metho...
def timeit(self, method, times, *args, **kwargs): '''Useful utility for benchmarking an asynchronous ``method``. :param method: the name of the ``method`` to execute :param times: number of times to execute the ``method`` :param args: positional arguments to pass to the ``method`` ...
Read all content
async def read(self, n=None): """Read all content """ if self._streamed: return b'' buffer = [] async for body in self: buffer.append(body) return b''.join(buffer)
Execute a python *callable*.
def run(request, callable, *args, **kwargs): '''Execute a python *callable*.''' return callable(request.actor, *args, **kwargs)
The actor notify itself with a dictionary of information. The command perform the following actions: * Update the mailbox to the current consumer of the actor connection * Update the info dictionary * Returns the time of the update
def notify(request, info): '''The actor notify itself with a dictionary of information. The command perform the following actions: * Update the mailbox to the current consumer of the actor connection * Update the info dictionary * Returns the time of the update ''' t = time() actor = r...
Kill an actor with id ``aid``. This command can only be executed by the arbiter, therefore a valid sintax is only:: send('arbiter', 'kill_actor', 'abc') Return 'killed abc` if successful, otherwise it returns ``None``.
async def kill_actor(request, aid, timeout=5): '''Kill an actor with id ``aid``. This command can only be executed by the arbiter, therefore a valid sintax is only:: send('arbiter', 'kill_actor', 'abc') Return 'killed abc` if successful, otherwise it returns ``None``. ''' arb = request...
Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing.
def write(self, data): """Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing. """ if self.closed: raise ConnectionResetError( 'Transport closed - cannot write on %s' % self ...
Resume writing. Successive calls to this method will fails unless :meth:`pause_writing` is called first.
def resume_writing(self, exc=None): '''Resume writing. Successive calls to this method will fails unless :meth:`pause_writing` is called first. ''' assert self._paused self._paused = False waiter = self._waiter if waiter is not None: self._wai...
Set a new :attr:`timeout` for this protocol
def timeout(self, timeout): '''Set a new :attr:`timeout` for this protocol ''' if self._timeout is None: self.event('connection_made').bind(self._add_timeout) self.event('connection_lost').bind(self._cancel_timeout) self._timeout = timeout or 0 self._add_t...
Add a consumer to the pipeline
def pipeline(self, consumer): """Add a consumer to the pipeline """ if self._pipeline is None: self._pipeline = ResponsePipeline(self) self.event('connection_lost').bind(self._close_pipeline) self._pipeline.put(consumer)
return a `close` :class:`Frame`.
def close(self, code=None): '''return a `close` :class:`Frame`. ''' code = code or 1000 body = pack('!H', code) body += self._close_codes.get(code, '').encode('utf-8') return self.encode(body, opcode=0x8)
return a `continuation` :class:`Frame`.
def continuation(self, body=None, final=True): '''return a `continuation` :class:`Frame`.''' return self.encode(body, opcode=0, final=final)
Encode a ``message`` for writing into the wire. To produce several frames for a given large message use :meth:`multi_encode` method.
def encode(self, message, final=True, masking_key=None, opcode=None, rsv1=0, rsv2=0, rsv3=0): '''Encode a ``message`` for writing into the wire. To produce several frames for a given large message use :meth:`multi_encode` method. ''' fin = 1 if final else 0 ...
Encode a ``message`` into several frames depending on size. Returns a generator of bytes to be sent over the wire.
def multi_encode(self, message, masking_key=None, opcode=None, rsv1=0, rsv2=0, rsv3=0, max_payload=0): '''Encode a ``message`` into several frames depending on size. Returns a generator of bytes to be sent over the wire. ''' max_payload = max(2, max_payload or self....
If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups']
def sort_return_tuples(response, groups=None, **options): """ If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups'] """ if not response or not groups: return response return list(zip(*[response[i::groups] for i in ...
Set the value at key ``name`` to ``value`` :param ex: sets an expire flag on key ``name`` for ``ex`` seconds. :param px: sets an expire flag on key ``name`` for ``px`` milliseconds. :param nx: if set to True, set the value at key ``name`` to ``value`` if it does not already exist. ...
def set(self, name, value, ex=None, px=None, nx=False, xx=False): """Set the value at key ``name`` to ``value`` :param ex: sets an expire flag on key ``name`` for ``ex`` seconds. :param px: sets an expire flag on key ``name`` for ``px`` milliseconds. :param nx: if set to True, set the v...
Set any number of score, element-name pairs to the key ``name``. Pairs can be specified in two ways: As ``*args``, in the form of:: score1, name1, score2, name2, ... or as ``**kwargs``, in the form of:: name1=score1, name2=score2, ... The following example wo...
def zadd(self, name, *args, **kwargs): """ Set any number of score, element-name pairs to the key ``name``. Pairs can be specified in two ways: As ``*args``, in the form of:: score1, name1, score2, name2, ... or as ``**kwargs``, in the form of:: name1=...
Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning i...
def sort(self, key, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=False): '''Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight ...
Send commands to redis.
def commit(self, raise_on_error=True): '''Send commands to redis. ''' cmds = list(chain([(('multi',), {})], self.command_stack, [(('exec',), {})])) self.reset() return self.store.execute_pipeline(cmds, raise_on_error)
Create the :class:`.SocketServer` with :class:`EchoServerProtocol` as protocol factory.
def server(name=None, description=None, **kwargs): '''Create the :class:`.SocketServer` with :class:`EchoServerProtocol` as protocol factory. ''' name = name or 'echoserver' description = description or 'Echo Server' return SocketServer(EchoServerProtocol, name=name, desc...
Implements the :meth:`~.ProtocolConsumer.data_received` method. It simply search for the :attr:`separator` and, if found, it invokes the :meth:`response` method with the value of the message.
def feed_data(self, data): '''Implements the :meth:`~.ProtocolConsumer.data_received` method. It simply search for the :attr:`separator` and, if found, it invokes the :meth:`response` method with the value of the message. ''' if self.buffer is None: self.buffer = byt...
Override :meth:`~EchoProtocol.response` method by writing the ``data`` received back to the client.
def response(self, data, rest): '''Override :meth:`~EchoProtocol.response` method by writing the ``data`` received back to the client. ''' self.connection.write(data) data = data[:-len(self.separator)] # If we get a QUIT message, close the connection # Used by the...
Update this :attr:`Config` with ``data``. :param data: must be a ``Mapping`` like object exposing the ``item`` method for iterating through key-value pairs. :param default: if ``True`` the updated :attr:`settings` will also set their :attr:`~Setting.default` attribute with the ...
def update(self, data, default=False): """Update this :attr:`Config` with ``data``. :param data: must be a ``Mapping`` like object exposing the ``item`` method for iterating through key-value pairs. :param default: if ``True`` the updated :attr:`settings` will also set t...
Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified.
def copy_globals(self, cfg): """Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified. """ for name, setting in cfg.settings.items(): csetting = self.settings.get(name) if (setting.is_global and csetting ...
Get the value at ``name`` for this :class:`Config` container The returned value is obtained from: * the value at ``name`` in the :attr:`settings` dictionary if available. * the value at ``name`` in the :attr:`params` dictionary if available. * the ``default`` value.
def get(self, name, default=None): """Get the value at ``name`` for this :class:`Config` container The returned value is obtained from: * the value at ``name`` in the :attr:`settings` dictionary if available. * the value at ``name`` in the :attr:`params` dictionary if availab...
Set the :class:`Setting` at ``name`` with a new ``value``. If ``default`` is ``True``, the :attr:`Setting.default` is also set.
def set(self, name, value, default=False, imported=False): """Set the :class:`Setting` at ``name`` with a new ``value``. If ``default`` is ``True``, the :attr:`Setting.default` is also set. """ if name in self.__dict__: self.__dict__[name] = value return ...
Create the argparser_ for this configuration by adding all settings via the :meth:`Setting.add_argument` method. :rtype: an instance of :class:`ArgumentParser`.
def parser(self): """Create the argparser_ for this configuration by adding all settings via the :meth:`Setting.add_argument` method. :rtype: an instance of :class:`ArgumentParser`. """ parser = argparse.ArgumentParser(description=self.description, ...
Add this container :attr:`settings` to an existing ``parser``.
def add_to_parser(self, parser): """Add this container :attr:`settings` to an existing ``parser``. """ setts = self.settings def sorter(x): return (setts[x].section, setts[x].order) for k in sorted(setts, key=sorter): setts[k].add_argument(parser) ...
Parse the command line
def parse_command_line(self, argv=None): """Parse the command line """ if self.config: parser = argparse.ArgumentParser(add_help=False) self.settings['config'].add_argument(parser) opts, _ = parser.parse_known_args(argv) if opts.config is not None:...
An address to bind to, only available if a :ref:`bind <setting-bind>` setting has been added to this :class:`Config` container.
def address(self): """An address to bind to, only available if a :ref:`bind <setting-bind>` setting has been added to this :class:`Config` container. """ bind = self.settings.get('bind') if bind: return parse_address(to_bytes(bind.get()))
A copy of this :class:`Config` container. If ``prefix`` is given, it prefixes all non :ref:`global settings <setting-section-global-server-settings>` with it. Used when multiple applications are loaded.
def copy(self, name=None, prefix=None): """A copy of this :class:`Config` container. If ``prefix`` is given, it prefixes all non :ref:`global settings <setting-section-global-server-settings>` with it. Used when multiple applications are loaded. """ cls = self.__class__ ...
Configured logger.
def configured_logger(self, name=None): """Configured logger. """ log_handlers = self.log_handlers # logname if not name: # base name is always pulsar basename = 'pulsar' # the namespace name for this config name = self.name ...
Set ``val`` as the :attr:`value` for this :class:`Setting`. If ``default`` is ``True`` set also the :attr:`default` value.
def set(self, val, default=False, imported=False): """Set ``val`` as the :attr:`value` for this :class:`Setting`. If ``default`` is ``True`` set also the :attr:`default` value. """ if hasattr(self.validator, '__call__'): try: val = self.validator(val) ...
Add this :class:`Setting` to the ``parser``. The operation is carried out only if :attr:`flags` or :attr:`nargs` and :attr:`name` are defined.
def add_argument(self, parser, set_default=False): """Add this :class:`Setting` to the ``parser``. The operation is carried out only if :attr:`flags` or :attr:`nargs` and :attr:`name` are defined. """ default = self.default if set_default else None kwargs = dict( ...
Copy this :class:`SettingBase`
def copy(self, name=None, prefix=None): """Copy this :class:`SettingBase`""" setting = self.__class__.__new__(self.__class__) setting.__dict__.update(self.__dict__) # Keep the modified flag? # setting.modified = False if prefix and not setting.is_global: flags...
English representation of a number up to a trillion.
def num2eng(num): '''English representation of a number up to a trillion. ''' num = str(int(num)) # Convert to string, throw if bad number if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check return num elif num == '0': # Zero is a special case return 'zero' pron = [] # Resul...
Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible.
def get_params(self, *args, **kwargs): ''' Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible. ''' kwargs.update(self._data) if args and kwargs: raise ValueError('Cannot mix positional a...
Used by the server to send messages to the client. Returns a future.
def send(self, command, sender, target, args, kwargs): """Used by the server to send messages to the client. Returns a future. """ command = get_command(command) data = {'command': command.__name__, 'id': create_aid(), 'sender': actor_identity(send...
Create the :class:`.UdpSocketServer`.
def server(name=None, description=None, **kwargs): '''Create the :class:`.UdpSocketServer`. ''' return UdpSocketServer( EchoServerProtocol, name=name or 'echoudpserver', description=description or 'Echo Udp Server', **kwargs )
delete pidfile
def unlink(self): """ delete pidfile""" try: with open(self.fname, "r") as f: pid1 = int(f.read() or 0) if pid1 == self.pid: os.unlink(self.fname) except Exception: pass
Validate pidfile and make it stale if needed
def read(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return return wpid excep...
Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine.
def acquire(self, timeout=None): """Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine. """ green = getcurrent() parent = green.parent if parent is None: raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet') ...
Release the lock. This method should only be called in the locked state; it changes the state to unlocked and returns immediately. If an attempt is made to release an unlocked lock, a RuntimeError will be raised.
def release(self): """Release the lock. This method should only be called in the locked state; it changes the state to unlocked and returns immediately. If an attempt is made to release an unlocked lock, a RuntimeError will be raised. """ if self._local.locked: ...
Container of request cookies
def cookies(self): """Container of request cookies """ cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future` which results in the tuple. The result is cached.
def data_and_files(self, data=True, files=True, stream=None): """Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future`...
Returns the HTTP host using the environment or request headers.
def get_host(self, use_x_forwarded=True): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ): host = self.environ['HTTP_X_FORWARDED_HOST'] ...
Obtain the client IP address
def get_client_address(self, use_x_forwarded=True): """Obtain the client IP address """ xfor = self.environ.get('HTTP_X_FORWARDED_FOR') if use_x_forwarded and xfor: return xfor.split(',')[-1].strip() else: return self.environ['REMOTE_ADDR']
Return a full path
def full_path(self, *args, **query): """Return a full path""" path = None if args: if len(args) > 1: raise TypeError("full_url() takes exactly 1 argument " "(%s given)" % len(args)) path = args[0] if not path: ...
Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`.
def absolute_uri(self, location=None, scheme=None, **query): """Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`. """ if not is_absolute_uri(location): ...
Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match.
def set_response_content_type(self, response_content_types=None): '''Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and fi...
Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer wh...
def checkarity(func, args, kwargs, discount=0): '''Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued p...
Wrapped up as a Sphinx Extension
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if ...
Setup function for Sphinx Extension
def setup(app): "Setup function for Sphinx Extension" app.add_config_value("sphinx_to_github", True, '') app.add_config_value("sphinx_to_github_verbose", True, '') app.connect("build-finished", sphinx_extension)
Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, parameters, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal:
def parse_rule(rule): """Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, parameters, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal: """ m = _rule_re.match(rule) if m is None or m.end() ...
Build a ``url`` from ``urlargs`` key-value parameters
def url(self, **urlargs): '''Build a ``url`` from ``urlargs`` key-value parameters ''' if self.defaults: d = self.defaults.copy() d.update(urlargs) urlargs = d url = '/'.join(self._url_generator(urlargs)) if not url: return '/' ...
Match a path and return ``None`` if no matching, otherwise a dictionary of matched variables with values. If there is more to be match in the path, the remaining string is placed in the ``__remaining__`` key of the dictionary.
def match(self, path): '''Match a path and return ``None`` if no matching, otherwise a dictionary of matched variables with values. If there is more to be match in the path, the remaining string is placed in the ``__remaining__`` key of the dictionary.''' match = self._regex.sear...
Return a two element tuple containing the parent route and the last url bit as route. If this route is the root route, it returns the root route and ``None``.
def split(self): '''Return a two element tuple containing the parent route and the last url bit as route. If this route is the root route, it returns the root route and ``None``. ''' rule = self.rule if not self.is_leaf: rule = rule[:-1] if not rule: ...
Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>") :param request: Wsgi request :param filepath: full path of file to serve :p...
def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): ...
Map a function to :class:`Router` and add to the :attr:`routes` list. Typical usage:: app = Router('/') @app.router('/hello', methods=['post']) def world(request): return wsgi.WsgiResponse(200, 'world')
def router(self, rule, methods=['get']): '''Map a function to :class:`Router` and add to the :attr:`routes` list. Typical usage:: app = Router('/') @app.router('/hello', methods=['post']) def world(request): return wsgi.WsgiResponse(200, 'world') ...
The relative :class:`.Route` served by this :class:`Router`.
def route(self): '''The relative :class:`.Route` served by this :class:`Router`. ''' parent = self._parent if parent and parent._route.is_leaf: return parent.route + self._route else: return self._route
The full :attr:`route` for this :class:`.Router`. It includes the :attr:`parent` portion of the route if a parent router is available.
def full_route(self): '''The full :attr:`route` for this :class:`.Router`. It includes the :attr:`parent` portion of the route if a parent router is available. ''' if self._parent: return self._parent.full_route + self._route else: return self._ro...
A parameter in this :class:`.Router`
def getparam(self, name, default=None, parents=False): '''A parameter in this :class:`.Router` ''' value = getattr(self, name, None) if value is None: if parents and self._parent: return self._parent.getparam(name, default, parents) else: ...
Resolve a path and return a ``(handler, urlargs)`` tuple or ``None`` if the path could not be resolved.
def _resolve(self, path, method, urlargs=None): '''Resolve a path and return a ``(handler, urlargs)`` tuple or ``None`` if the path could not be resolved. ''' match = self.route.match(path) if match is None: if not self.route.is_leaf: # no match retur...
Add a new :class:`Router` to the :attr:`routes` list.
def add_route(self, router, index=None): '''Add a new :class:`Router` to the :attr:`routes` list. ''' assert isinstance(router, Router), 'Not a valid Router' assert router is not self, 'cannot add self to children' for r in self.routes: if r == router: ...
remove a :class:`Router` from the :attr:`routes` list.
def remove_child(self, router): '''remove a :class:`Router` from the :attr:`routes` list.''' if router in self.routes: self.routes.remove(router) router._parent = None
Get a child :class:`Router` by its :attr:`name`. This method search child routes recursively.
def get_route(self, name): '''Get a child :class:`Router` by its :attr:`name`. This method search child routes recursively. ''' for route in self.routes: if route.name == name: return route for child in self.routes: route = child.get_route...
Return an anchor :class:`Html` element with the `href` attribute set to the url of this :class:`Router`.
def link(self, *args, **urlargs): '''Return an anchor :class:`Html` element with the `href` attribute set to the url of this :class:`Router`.''' if len(args) > 1: raise ValueError url = self.route.url(**urlargs) if len(args) == 1: text = args[0] el...
Check if ``router`` is ``self`` or a parent or ``self``
def has_parent(self, router): '''Check if ``router`` is ``self`` or a parent or ``self`` ''' parent = self while parent and parent is not router: parent = parent._parent return parent is not None
Create a new :class:`.Router` from a ``rule`` and parameters. This method is used during initialisation when building child Routers from the :attr:`rule_methods`.
def make_router(self, rule, method=None, handler=None, cls=None, name=None, **params): '''Create a new :class:`.Router` from a ``rule`` and parameters. This method is used during initialisation when building child Routers from the :attr:`rule_methods`. ''' cl...
Count the number of bits in a byte ``array``. It uses the Hamming weight popcount algorithm
def count_bytes(array): '''Count the number of bits in a byte ``array``. It uses the Hamming weight popcount algorithm ''' # this algorithm can be rewritten as # for i in array: # count += sum(b=='1' for b in bin(i)[2:]) # but this version is almost 2 times faster count = 0 for ...