INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Write a new ``message`` into the wire. It uses the :meth:`~.FrameParser.encode` method of the websocket :attr:`parser`. :param message: message to send, must be a string or bytes :param opcode: optional ``opcode``, if not supplied it is set to 1 if ``message`` is a string, ...
def write(self, message, opcode=None, encode=True, **kw): '''Write a new ``message`` into the wire. It uses the :meth:`~.FrameParser.encode` method of the websocket :attr:`parser`. :param message: message to send, must be a string or bytes :param opcode: optional ``opcode``, if...
Write a ping ``frame``.
def ping(self, message=None): '''Write a ping ``frame``. ''' return self.write(self.parser.ping(message), encode=False)
Write a pong ``frame``.
def pong(self, message=None): '''Write a pong ``frame``. ''' return self.write(self.parser.pong(message), encode=False)
Write a close ``frame`` with ``code``.
def write_close(self, code=None): '''Write a close ``frame`` with ``code``. ''' return self.write(self.parser.close(code), opcode=0x8, encode=False)
Returns the given HTML with ampersands, quotes and angle brackets encoded.
def escape(html, force=False): """Returns the given HTML with ampersands, quotes and angle brackets encoded.""" if hasattr(html, '__html__') and not force: return html if html in NOTHING: return '' else: return to_string(html).replace('&', '&amp;').replace( '<', '...
Capitalise the first letter of ``x``.
def capfirst(x): '''Capitalise the first letter of ``x``. ''' x = to_string(x).strip() if x: return x[0].upper() + x[1:].lower() else: return x
Make ``name`` a more user friendly string. Capitalise the first letter and replace dash and underscores with a space
def nicename(name): '''Make ``name`` a more user friendly string. Capitalise the first letter and replace dash and underscores with a space ''' name = to_string(name) return capfirst(' '.join(name.replace('-', ' ').replace('_', ' ').split()))
Set a value in the task context
def set(self, key, value): """Set a value in the task context """ task = Task.current_task() try: context = task._context except AttributeError: task._context = context = {} context[key] = value
Set a value in a task context stack
def stack_push(self, key, value): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: task._context_stack = context = {} if key not in context: context[key] = [...
Set a value in a task context stack
def stack_get(self, key): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: return if key in context: return context[key][-1]
Remove a value in a task context stack
def stack_pop(self, key): """Remove a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: raise KeyError('pop from empty stack') from None value = context[key] stack_value =...
Expand something like 'unuk.tasks.*' into a list of all the modules there.
def expand_star(mod_name): """Expand something like 'unuk.tasks.*' into a list of all the modules there. """ expanded = [] mod_dir = os.path.dirname( __import__(mod_name[:-2], {}, {}, ['']).__file__) for f in glob.glob1(mod_dir, "[!_]*.py"): expanded.append('%s.%s' % (mod_name[:-...
Safely import a list of *modules*
def import_modules(modules, safe=True): '''Safely import a list of *modules* ''' all = [] for mname in modules: if mname.endswith('.*'): to_load = expand_star(mname) else: to_load = [mname] for module in to_load: try: all.append...
Load an attribute from a module. If the module or the attribute is not available, return the default argument if *safe* is `True`.
def module_attribute(dotpath, default=None, safe=False): '''Load an attribute from a module. If the module or the attribute is not available, return the default argument if *safe* is `True`. ''' if dotpath: bits = str(dotpath).split(':') try: if len(bits) == 2: ...
Send a :ref:`message <api-remote_commands>` to ``target`` The message is to perform a given ``action``. The actor sending the message is obtained via the :func:`get_actor` function. :parameter target: the :class:`Actor` id or an :class:`.ActorProxy` or name of the target actor which will receive t...
def send(target, action, *args, **params): '''Send a :ref:`message <api-remote_commands>` to ``target`` The message is to perform a given ``action``. The actor sending the message is obtained via the :func:`get_actor` function. :parameter target: the :class:`Actor` id or an :class:`.ActorProxy` or ...
Called after forking to start the actor's life. This is where logging is configured, the :attr:`mailbox` is registered and the :attr:`_loop` is initialised and started. Calling this method more than once does nothing.
def start(self, exit=True): '''Called after forking to start the actor's life. This is where logging is configured, the :attr:`mailbox` is registered and the :attr:`_loop` is initialised and started. Calling this method more than once does nothing. ''' if self.state == A...
Send a message to ``target`` to perform ``action`` with given positional ``args`` and key-valued ``kwargs``. Returns a coroutine or a Future.
def send(self, target, action, *args, **kwargs): '''Send a message to ``target`` to perform ``action`` with given positional ``args`` and key-valued ``kwargs``. Returns a coroutine or a Future. ''' target = self.monitor if target == 'monitor' else target mailbox = self.ma...
Gracefully stop the :class:`Actor`. Implemented by the :meth:`.Concurrency.stop` method of the :attr:`concurrency` attribute.
def stop(self, exc=None, exit_code=None): '''Gracefully stop the :class:`Actor`. Implemented by the :meth:`.Concurrency.stop` method of the :attr:`concurrency` attribute. ''' return self._concurrency.stop(self, exc, exit_code)
Given an actor unique id return the actor proxy.
def get_actor(self, aid, check_monitor=True): '''Given an actor unique id return the actor proxy. ''' aid = actor_identity(aid) return self._concurrency.get_actor(self, aid, check_monitor=check_monitor)
Return a nested dictionary of information related to the actor status and performance. The dictionary contains the following entries: * ``actor`` a dictionary containing information regarding the type of actor and its status. * ``events`` a dictionary of information about the ...
def info(self): '''Return a nested dictionary of information related to the actor status and performance. The dictionary contains the following entries: * ``actor`` a dictionary containing information regarding the type of actor and its status. * ``events`` a dictionary of inf...
Returns an :class:`Html` factory function for ``tag`` and a given dictionary of ``defaults`` parameters. For example:: >>> input_factory = html_factory('input', type='text') >>> html = input_factory(value='bla')
def html_factory(tag, **defaults): '''Returns an :class:`Html` factory function for ``tag`` and a given dictionary of ``defaults`` parameters. For example:: >>> input_factory = html_factory('input', type='text') >>> html = input_factory(value='bla') ''' def html_input(*children, **params): ...
Insert ``child`` into the list of :attr:`children` at ``index``. :param index: The index (positive integer) where to insert ``child``. :param child: String, bytes or another :class:`String`. If it is an :class:`.String`, this instance will be set as its :attr:`parent`. ...
def insert(self, index, child): '''Insert ``child`` into the list of :attr:`children` at ``index``. :param index: The index (positive integer) where to insert ``child``. :param child: String, bytes or another :class:`String`. If it is an :class:`.String`, this instance will be set a...
Remove a ``child`` from the list of :attr:`children`.
def remove(self, child): '''Remove a ``child`` from the list of :attr:`children`.''' try: self.children.remove(child) if isinstance(child, String): child._parent = None except ValueError: pass
Remove all :attr:`children`.
def remove_all(self): '''Remove all :attr:`children`.''' if self._children: for child in self._children: if isinstance(child, String): child._parent = None self._children = []
Returns an iterable over strings.
def stream(self, request, counter=0): '''Returns an iterable over strings. ''' if self._children: for child in self._children: if isinstance(child, String): yield from child.stream(request, counter+1) else: yield...
Called to transform the collection of ``streams`` into the content string. This method can be overwritten by derived classes. :param streams: a collection (list or dictionary) containing ``strings/bytes`` used to build the final ``string/bytes``. :return: a string or bytes
def to_bytes(self, request=None): '''Called to transform the collection of ``streams`` into the content string. This method can be overwritten by derived classes. :param streams: a collection (list or dictionary) containing ``strings/bytes`` used to build the final ``string/...
Add the specific attribute to the attribute dictionary with key ``name`` and value ``value`` and return ``self``.
def attr(self, *args): '''Add the specific attribute to the attribute dictionary with key ``name`` and value ``value`` and return ``self``.''' attr = self._attr if not args: return attr or {} result, adding = self._attrdata('attr', *args) if adding: ...
Add or retrieve data values for this :class:`Html`.
def data(self, *args): '''Add or retrieve data values for this :class:`Html`.''' data = self._data if not args: return data or {} result, adding = self._attrdata('data', *args) if adding: if data is None: self._extra['data'] = {} ...
Add the specific class names to the class set and return ``self``.
def addClass(self, cn): '''Add the specific class names to the class set and return ``self``. ''' if cn: if isinstance(cn, (tuple, list, set, frozenset)): add = self.addClass for c in cn: add(c) else: cla...
Remove classes
def removeClass(self, cn): '''Remove classes''' if cn: ks = self._classes if ks: for cn in cn.split(): if cn in ks: ks.remove(cn) return self
Return a string with attributes to add to the tag
def flatatt(self, **attr): '''Return a string with attributes to add to the tag''' cs = '' attr = self._attr classes = self._classes data = self._data css = self._css attr = attr.copy() if attr else {} if classes: cs = ' '.join(classes) ...
Update the css dictionary if ``mapping`` is a dictionary, otherwise return the css value at ``mapping``. If ``mapping`` is not given, return the whole ``css`` dictionary if available.
def css(self, mapping=None): '''Update the css dictionary if ``mapping`` is a dictionary, otherwise return the css value at ``mapping``. If ``mapping`` is not given, return the whole ``css`` dictionary if available. ''' css = self._css if mapping is None: ...
Return a suitable absolute url for ``path``. If ``path`` :meth:`is_relative` build a suitable url by prepending the :attr:`media_path` attribute. :return: A url path to insert in a HTML ``link`` or ``script``.
def absolute_path(self, path, minify=True): '''Return a suitable absolute url for ``path``. If ``path`` :meth:`is_relative` build a suitable url by prepending the :attr:`media_path` attribute. :return: A url path to insert in a HTML ``link`` or ``script``. ''' if minify...
Append a link to this container. :param child: a string indicating the location of the linked document :param rel: Specifies the relationship between the document and the linked document. If not given ``stylesheet`` is used. :param type: Specifies the content type of the...
def insert(self, index, child, rel=None, type=None, media=None, condition=None, **kwargs): '''Append a link to this container. :param child: a string indicating the location of the linked document :param rel: Specifies the relationship between the document ...
add a new script to the container. :param child: a ``string`` representing an absolute path to the script or relative path (does not start with ``http`` or ``/``), in which case the :attr:`Media.media_path` attribute is prepended.
def insert(self, index, child, **kwargs): '''add a new script to the container. :param child: a ``string`` representing an absolute path to the script or relative path (does not start with ``http`` or ``/``), in which case the :attr:`Media.media_path` attribute is prepended. ...
Get the ``content`` attribute of a meta tag ``name``. For example:: head.get_meta('decription') returns the ``content`` attribute of the meta tag with attribute ``name`` equal to ``description`` or ``None``. If a different meta key needs to be matched, it can be specified ...
def get_meta(self, name, meta_key=None): '''Get the ``content`` attribute of a meta tag ``name``. For example:: head.get_meta('decription') returns the ``content`` attribute of the meta tag with attribute ``name`` equal to ``description`` or ``None``. If a differen...
Replace the ``content`` attribute of meta tag ``name`` If the meta with ``name`` is not available, it is added, otherwise its content is replaced. If ``content`` is not given or it is empty the meta tag with ``name`` is removed.
def replace_meta(self, name, content=None, meta_key=None): '''Replace the ``content`` attribute of meta tag ``name`` If the meta with ``name`` is not available, it is added, otherwise its content is replaced. If ``content`` is not given or it is empty the meta tag with ``name`` is remov...
Lists of random walks.
def randompaths(request, num_paths=1, size=250, mu=0, sigma=1): '''Lists of random walks.''' r = [] for p in range(num_paths): v = 0 path = [v] r.append(path) for t in range(size): v += normalvariate(mu, sigma) path.append(v) return r
Called once to setup the list of wsgi middleware.
def setup(self, environ): '''Called once to setup the list of wsgi middleware.''' json_handler = Root().putSubHandler('calc', Calculator()) middleware = wsgi.Router('/', post=json_handler, accept_content_types=JSON_CONTENT_TYPES) response = [wsgi.GZipMidd...
This is just for testing the asynchronous response middleware
def AsyncResponseMiddleware(environ, resp): '''This is just for testing the asynchronous response middleware ''' future = create_future() future._loop.call_soon(future.set_result, resp) return future
Encode a message when publishing.
def encode(self, message): '''Encode a message when publishing.''' if not isinstance(message, dict): message = {'message': message} message['time'] = time.time() return json.dumps(message)
When a new websocket connection is established it creates a new :class:`ChatClient` and adds it to the set of clients of the :attr:`pubsub` handler.
def on_open(self, websocket): '''When a new websocket connection is established it creates a new :class:`ChatClient` and adds it to the set of clients of the :attr:`pubsub` handler.''' self.pubsub.add_client(ChatClient(websocket, self.channel))
When a new message arrives, it publishes to all listening clients.
def on_message(self, websocket, msg): '''When a new message arrives, it publishes to all listening clients. ''' if msg: lines = [] for li in msg.split('\n'): li = li.strip() if li: lines.append(li) msg = ' '....
Publish a message via JSON-RPC
async def rpc_message(self, request, message): '''Publish a message via JSON-RPC''' await self.pubsub.publish(self.channel, message) return 'OK'
Called once only to setup the WSGI application handler. Check :ref:`lazy wsgi handler <wsgi-lazy-handler>` section for further information.
def setup(self, environ): '''Called once only to setup the WSGI application handler. Check :ref:`lazy wsgi handler <wsgi-lazy-handler>` section for further information. ''' request = wsgi_request(environ) cfg = request.cache.cfg loop = request.cache._loop ...
Set a cookie key into the cookies dictionary *cookies*.
def set_cookie(cookies, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): '''Set a cookie key into the cookies dictionary *cookies*.''' cookies[key] = value if expires is not None: if isinstance(expires, datetime): now = (expi...
The list of headers for this response
def _get_headers(self, environ): """The list of headers for this response """ headers = self.headers method = environ['REQUEST_METHOD'] if has_empty_content(self.status_code, method) and method != HEAD: headers.pop('content-type', None) headers.pop('conte...
A decorator which exposes a function ``func`` as an rpc function. :param func: The function to expose. :param doc: Optional doc string. If not provided the doc string of ``func`` will be used. :param format: Optional output format. :param request_handler: function which takes ``request``, ``for...
def rpc_method(func, doc=None, format='json', request_handler=None): '''A decorator which exposes a function ``func`` as an rpc function. :param func: The function to expose. :param doc: Optional doc string. If not provided the doc string of ``func`` will be used. :param format: Optional output...
Add a sub :class:`RpcHandler` with prefix ``prefix``. :keyword prefix: a string defining the prefix of the subhandler :keyword handler: the sub-handler.
def putSubHandler(self, prefix, handler): '''Add a sub :class:`RpcHandler` with prefix ``prefix``. :keyword prefix: a string defining the prefix of the subhandler :keyword handler: the sub-handler. ''' self.subHandlers[prefix] = handler handler._parent = self ret...
Clean url from double slashes and redirect if needed.
def clean_path_middleware(environ, start_response=None): '''Clean url from double slashes and redirect if needed.''' path = environ['PATH_INFO'] if path and '//' in path: url = re.sub("/+", '/', path) if not url.startswith('/'): url = '/%s' % url qs = environ['QUERY_STRIN...
Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``. If available, set the ``http.authorization`` key in ``environ`` with the result obtained from :func:`~.parse_authorization_header` function.
def authorization_middleware(environ, start_response=None): '''Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``. If available, set the ``http.authorization`` key in ``environ`` with the result obtained from :func:`~.parse_authorization_header` function. ''' key = 'http.authorization' c =...
Use this middleware to wait for the full body. This middleware wait for the full body to be received before letting other middleware to be processed. Useful when using synchronous web-frameworks such as :django:`django <>`.
async def wait_for_body_middleware(environ, start_response=None): '''Use this middleware to wait for the full body. This middleware wait for the full body to be received before letting other middleware to be processed. Useful when using synchronous web-frameworks such as :django:`django <>`. ''' ...
Use this middleware to run a synchronous middleware in the event loop executor. Useful when using synchronous web-frameworks such as :django:`django <>`.
def middleware_in_executor(middleware): '''Use this middleware to run a synchronous middleware in the event loop executor. Useful when using synchronous web-frameworks such as :django:`django <>`. ''' @wraps(middleware) def _(environ, start_response): loop = get_event_loop() ret...
The ``philosopher`` performs one of these two actions: * eat, if he has both forks and then :meth:`release_forks`. * try to :meth:`pickup_fork`, if he has fewer than 2 forks.
async def eat(self, philosopher): '''The ``philosopher`` performs one of these two actions: * eat, if he has both forks and then :meth:`release_forks`. * try to :meth:`pickup_fork`, if he has fewer than 2 forks. ''' loop = philosopher._loop while True: forks ...
The ``philosopher`` has just eaten and is ready to release both forks. This method releases them, one by one, by sending the ``put_down`` action to the monitor.
async def release_forks(self, philosopher): '''The ``philosopher`` has just eaten and is ready to release both forks. This method releases them, one by one, by sending the ``put_down`` action to the monitor. ''' forks = self.forks self.forks = [] self.sta...
The WSGI_ application handler which returns an iterable over the "Hello World!" message.
def hello(environ, start_response): '''The WSGI_ application handler which returns an iterable over the "Hello World!" message.''' if environ['REQUEST_METHOD'] == 'GET': data = b'Hello World!\n' status = '200 OK' response_headers = [ ('Content-type', 'text/plain'), ...
Create the :class:`.WSGIServer` running :func:`hello`.
def server(description=None, **kwargs): '''Create the :class:`.WSGIServer` running :func:`hello`.''' description = description or 'Pulsar Hello World Application' return wsgi.WSGIServer(hello, description=description, **kwargs)
Close the connection Close the pipeline if open and make sure the other connection is closed too. :param other_side: if True close the other_side connection too. used to avoid infinite loop
def close(self, other_side=True): """Close the connection Close the pipeline if open and make sure the other connection is closed too. :param other_side: if True close the other_side connection too. used to avoid infinite loop """ waiters = [self.close_pipel...
Equivalent to :func:`.create_store` for most cases excepts when the ``url`` is for a pulsar store not yet started. In this case, a :class:`.PulsarDS` is started.
async def start_store(app, url, workers=0, **kw): '''Equivalent to :func:`.create_store` for most cases excepts when the ``url`` is for a pulsar store not yet started. In this case, a :class:`.PulsarDS` is started. ''' store = create_store(url, **kw) if store.name == 'pulsar': client = s...
Parse form data from an request and return a (forms, files) tuple. Both tuple values are dictionaries with the form-field name as a key (unicode) and lists as values (multiple values per key are possible). The forms-dictionary contains form-field values as unicode strings. The files-dictionary contains...
def parse_form_data(request, stream=None, **kw): '''Parse form data from an request and return a (forms, files) tuple. Both tuple values are dictionaries with the form-field name as a key (unicode) and lists as values (multiple values per key are possible). The forms-dictionary contains form-field valu...
Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the correct bytes here, as bytes, for email Parser to parse.
async def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the corr...
``True`` when the client is waiting for 100 Continue.
def _waiting_expect(self): '''``True`` when the client is waiting for 100 Continue. ''' if self._expect_sent is None: if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue': return True self._expect_sent = '' return False
Data encoded as base 64
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
Feed new data into the MultiPart parser or the data stream
def feed_data(self, data): """Feed new data into the MultiPart parser or the data stream""" if data: self._bytes.append(data) if self.parser.stream: self.parser.stream(self) else: self.parser.buffer.extend(data)
Function to Create a WSGI Proxy Server.
def server(name='proxy-server', headers_middleware=None, server_software=None, **kwargs): '''Function to Create a WSGI Proxy Server.''' if headers_middleware is None: headers_middleware = [x_forwarded_for] wsgi_proxy = ProxyServerWsgiHandler(headers_middleware) kwargs['server_software...
The :class:`.HttpClient` used by this proxy middleware for accessing upstream resources
def http_client(self): '''The :class:`.HttpClient` used by this proxy middleware for accessing upstream resources''' client = http.HttpClient(decompress=False, store_cookies=False) client.headers.clear() return client
Perform the Http request to the upstream server
async def request(self): '''Perform the Http request to the upstream server ''' request_headers = self.request_headers() environ = self.environ method = environ['REQUEST_METHOD'] data = None if method in ENCODE_BODY_METHODS: data = DataIterator(self) ...
Fill request headers from the environ dictionary and modify them via the list of :attr:`headers_middleware`. The returned headers will be sent to the target uri.
def request_headers(self): '''Fill request headers from the environ dictionary and modify them via the list of :attr:`headers_middleware`. The returned headers will be sent to the target uri. ''' headers = CIMultiDict() for k in self.environ: if k.startswith('...
Start the tunnel. This is a callback fired once a connection with upstream server is established.
def pre_request(self, response, exc=None): """Start the tunnel. This is a callback fired once a connection with upstream server is established. """ if response.request.method == 'CONNECT': self.start_response( '200 Connection established', ...
Create a new protocol via the :attr:`protocol_factory` This method increase the count of :attr:`sessions` and build the protocol passing ``self`` as the producer.
def create_protocol(self): """Create a new protocol via the :attr:`protocol_factory` This method increase the count of :attr:`sessions` and build the protocol passing ``self`` as the producer. """ self.sessions += 1 protocol = self.protocol_factory(self) protocol...
Sets the :attr:`transport`, fire the ``connection_made`` event and adds a :attr:`timeout` for idle connections.
def connection_made(self, transport): """Sets the :attr:`transport`, fire the ``connection_made`` event and adds a :attr:`timeout` for idle connections. """ self.transport = transport addr = self.transport.get_extra_info('peername') if not addr: addr = self.tr...
Fires the ``connection_lost`` event.
def connection_lost(self, exc=None): """Fires the ``connection_lost`` event. """ if self._loop.get_debug(): self.producer.logger.debug('connection lost %s', self) self.event('connection_lost').fire(exc=exc)
Delegates handling of data to the :meth:`current_consumer`. Once done set a timeout for idle connections when a :attr:`~Protocol.timeout` is a positive number (of seconds).
def data_received(self, data): """Delegates handling of data to the :meth:`current_consumer`. Once done set a timeout for idle connections when a :attr:`~Protocol.timeout` is a positive number (of seconds). """ try: self.data_received_count += 1 while data...
Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. For server side consumer, this method simp...
def start(self, request=None): """Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. ...
Decorator to be used in conjunction with :class:`LocalMixin` methods.
def local_method(f): '''Decorator to be used in conjunction with :class:`LocalMixin` methods. ''' name = f.__name__ def _(self, *args): local = self.local if name not in local: setattr(local, name, f(self, *args)) return getattr(local, name) return _
Decorator to be used in conjunction with :class:`LocalMixin` methods.
def local_property(f): '''Decorator to be used in conjunction with :class:`LocalMixin` methods. ''' name = f.__name__ def _(self): local = self.local if name not in local: setattr(local, name, f(self)) return getattr(local, name) return property(_, doc=f.__doc__...
Access and set global variables for the current process.
def process_global(name, val=None, setval=False): '''Access and set global variables for the current process.''' p = current_process() if not hasattr(p, '_pulsar_globals'): p._pulsar_globals = {'lock': Lock()} if setval: p._pulsar_globals[name] = val else: return p._pulsar_gl...
Configured logger.
def configured_logger(name=None, config=None, level=None, handlers=None): '''Configured logger. ''' name = name or '' with process_global('lock'): logconfig = process_global('_config_logging') # if the logger was not configured, do so. if not logconfig: logconfig = de...
Convert an Internationalised Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987. Returns an ASCII native string containing the encoded result.
def iri_to_uri(iri, kwargs=None): '''Convert an Internationalised Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987. Returns an ASCII native string containing the encoded result. ''' if iri is None: ...
Quote a header value if necessary. :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged.
def quote_header_value(value, extra_chars='', allow_token=True): """Quote a header value if necessary. :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged. """ value ...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it wi...
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] ...
Return a dict of environment proxies. From requests_.
def get_environ_proxies(): """Return a dict of environment proxies. From requests_.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'ws', 'wss', 'no' ] def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper...
Encode a dictionary of ``fields`` using the multipart/form-data format. :param fields: Dictionary of fields or list of (key, value) field tuples. The key is treated as the field name, and the value as the body of the form-data bytes. If the value is a tuple of two elements, then the first ...
def encode_multipart_formdata(fields, boundary=None, charset=None): """Encode a dictionary of ``fields`` using the multipart/form-data format. :param fields: Dictionary of fields or list of (key, value) field tuples. The key is treated as the field name, and the value as the body of the form-d...
Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie").
def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = dict( version=0, name=name, ...
Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar.
def cookiejar_from_dict(*cookie_dicts): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cookie_dicts = tuple((d for d in cookie_dicts if d)) if len(cookie_dicts) == 1 and isinstance(cookie_dicts[0], CookieJar): return ...
Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. For information on the Vary header, see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
def patch_vary_headers(response, newheaders): """Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. For information on the Vary header, see: http://www.w3.org/Protocols...
Checks to see if the response has a given header name in its Vary header.
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_hea...
Execute a new ``request``.
def execute(self, request): '''Execute a new ``request``. ''' handle = None if request: request[0] = command = to_string(request[0]).lower() info = COMMANDS_INFO.get(command) if info: handle = getattr(self.store, info.method_name) ...
Convert a *dte* into a valid unix timestamp.
def date2timestamp(dte): '''Convert a *dte* into a valid unix timestamp.''' seconds = mktime(dte.timetuple()) if isinstance(dte, datetime): return seconds + dte.microsecond / 1000000.0 else: return int(seconds)
Handle response cookies.
def handle_cookies(response, exc=None): '''Handle response cookies. ''' if exc: return headers = response.headers request = response.request client = request.client response._cookies = c = SimpleCookie() if 'set-cookie' in headers or 'set-cookie2' in headers: for cookie i...
Websocket upgrade as ``on_headers`` event.
def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection request = response.request handler = request.websocket_handler if not handler: hand...
Check if this :class:`Path` is a python module.
def ispymodule(self): '''Check if this :class:`Path` is a python module.''' if self.isdir(): return os.path.isfile(os.path.join(self, '__init__.py')) elif self.isfile(): return self.endswith('.py')
Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory three from :attr:`local_path`. :parameter down: Optional tuple of directory names to travel...
def add2python(self, module=None, up=0, down=None, front=False, must_exist=True): '''Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory...
The home page of this router
def get(self, request): '''The home page of this router''' ul = Html('ul') for router in sorted(self.routes, key=lambda r: r.creation_count): a = router.link(escape(router.route.path)) a.addClass(router.name) for method in METHODS: if router.ge...
Live stats for the server. Try sending lots of requests
def stats(self, request): '''Live stats for the server. Try sending lots of requests ''' # scheme = 'wss' if request.is_secure else 'ws' # host = request.get('HTTP_HOST') # address = '%s://%s/stats' % (scheme, host) doc = HtmlDocument(title='Live server stats', m...
Return info about parent needed by child to unpickle process object. Monkey-patch from
def get_preparation_data(name): ''' Return info about parent needed by child to unpickle process object. Monkey-patch from ''' d = dict( name=name, sys_path=sys.path, sys_argv=sys.argv, log_to_stderr=_log_to_stderr, orig_dir=process.ORIGINAL_DIR, ...
Get the command function *name*
def get_command(name): '''Get the command function *name*''' command = global_commands_table.get(name.lower()) if not command: raise CommandNotFound(name) return command
Command for executing remote calls on a remote object
def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor...
Clear the container from all data.
def clear(self): '''Clear the container from all data.''' self._size = 0 self._level = 1 self._head = Node('HEAD', None, [None]*SKIPLIST_MAXLEVEL, [1]*SKIPLIST_MAXLEVEL)
Extend this skiplist with an iterable over ``score``, ``value`` pairs.
def extend(self, iterable): '''Extend this skiplist with an iterable over ``score``, ``value`` pairs. ''' i = self.insert for score_values in iterable: i(*score_values)