_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q226600
MonitorMixin.stop_actors
train
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 ...
python
{ "resource": "" }
q226601
ArbiterMixin.add_monitor
train
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`...
python
{ "resource": "" }
q226602
PubSub.publish_event
train
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...
python
{ "resource": "" }
q226603
Concurrency.spawn
train
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)
python
{ "resource": "" }
q226604
Concurrency.run_actor
train
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...
python
{ "resource": "" }
q226605
Concurrency.setup_event_loop
train
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': ...
python
{ "resource": "" }
q226606
Concurrency.hand_shake
train
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...
python
{ "resource": "" }
q226607
Concurrency.create_mailbox
train
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
python
{ "resource": "" }
q226608
Concurrency.stop
train
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() ...
python
{ "resource": "" }
q226609
DigestAuth.authenticated
train
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...
python
{ "resource": "" }
q226610
Channels.register
train
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...
python
{ "resource": "" }
q226611
Channels.unregister
train
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...
python
{ "resource": "" }
q226612
Channels.connect
train
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...
python
{ "resource": "" }
q226613
Channel.register
train
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...
python
{ "resource": "" }
q226614
add_errback
train
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()) ...
python
{ "resource": "" }
q226615
AsyncObject.timeit
train
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`` ...
python
{ "resource": "" }
q226616
HttpStream.read
train
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)
python
{ "resource": "" }
q226617
notify
train
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...
python
{ "resource": "" }
q226618
FlowControl.write
train
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 ...
python
{ "resource": "" }
q226619
Pipeline.pipeline
train
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)
python
{ "resource": "" }
q226620
FrameParser.encode
train
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 ...
python
{ "resource": "" }
q226621
FrameParser.multi_encode
train
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....
python
{ "resource": "" }
q226622
RedisClient.sort
train
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 ...
python
{ "resource": "" }
q226623
Pipeline.commit
train
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)
python
{ "resource": "" }
q226624
Config.copy_globals
train
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 ...
python
{ "resource": "" }
q226625
Config.parse_command_line
train
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:...
python
{ "resource": "" }
q226626
num2eng
train
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...
python
{ "resource": "" }
q226627
JsonProxy.get_params
train
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...
python
{ "resource": "" }
q226628
MessageConsumer.send
train
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...
python
{ "resource": "" }
q226629
Pidfile.read
train
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...
python
{ "resource": "" }
q226630
GreenLock.acquire
train
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') ...
python
{ "resource": "" }
q226631
WsgiRequest.cookies
train
def cookies(self): """Container of request cookies """ cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
python
{ "resource": "" }
q226632
WsgiRequest.data_and_files
train
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`...
python
{ "resource": "" }
q226633
WsgiRequest.get_host
train
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'] ...
python
{ "resource": "" }
q226634
WsgiRequest.get_client_address
train
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']
python
{ "resource": "" }
q226635
WsgiRequest.full_path
train
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: ...
python
{ "resource": "" }
q226636
WsgiRequest.absolute_uri
train
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): ...
python
{ "resource": "" }
q226637
WsgiRequest.set_response_content_type
train
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...
python
{ "resource": "" }
q226638
checkarity
train
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...
python
{ "resource": "" }
q226639
sphinx_extension
train
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 ...
python
{ "resource": "" }
q226640
setup
train
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)
python
{ "resource": "" }
q226641
Route.url
train
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 '/' ...
python
{ "resource": "" }
q226642
Route.split
train
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: ...
python
{ "resource": "" }
q226643
was_modified_since
train
def was_modified_since(header=None, mtime=0, size=0): '''Check if an item was modified since the user last downloaded it :param header: the value of the ``If-Modified-Since`` header. If this is ``None``, simply return ``True`` :param mtime: the modification time of the item in question. :param ...
python
{ "resource": "" }
q226644
file_response
train
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): ...
python
{ "resource": "" }
q226645
Router.has_parent
train
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
python
{ "resource": "" }
q226646
count_bytes
train
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 ...
python
{ "resource": "" }
q226647
WebSocketProtocol.write
train
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...
python
{ "resource": "" }
q226648
WebSocketProtocol.ping
train
def ping(self, message=None): '''Write a ping ``frame``. ''' return self.write(self.parser.ping(message), encode=False)
python
{ "resource": "" }
q226649
WebSocketProtocol.pong
train
def pong(self, message=None): '''Write a pong ``frame``. ''' return self.write(self.parser.pong(message), encode=False)
python
{ "resource": "" }
q226650
WebSocketProtocol.write_close
train
def write_close(self, code=None): '''Write a close ``frame`` with ``code``. ''' return self.write(self.parser.close(code), opcode=0x8, encode=False)
python
{ "resource": "" }
q226651
escape
train
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( '<', '...
python
{ "resource": "" }
q226652
capfirst
train
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
python
{ "resource": "" }
q226653
nicename
train
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()))
python
{ "resource": "" }
q226654
TaskContext.set
train
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
python
{ "resource": "" }
q226655
TaskContext.stack_pop
train
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 =...
python
{ "resource": "" }
q226656
module_attribute
train
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: ...
python
{ "resource": "" }
q226657
Actor.start
train
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...
python
{ "resource": "" }
q226658
Actor.send
train
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...
python
{ "resource": "" }
q226659
String.stream
train
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...
python
{ "resource": "" }
q226660
String.to_bytes
train
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/...
python
{ "resource": "" }
q226661
Html.attr
train
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: ...
python
{ "resource": "" }
q226662
Html.addClass
train
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...
python
{ "resource": "" }
q226663
Html.flatatt
train
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) ...
python
{ "resource": "" }
q226664
Html.css
train
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: ...
python
{ "resource": "" }
q226665
Media.absolute_path
train
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...
python
{ "resource": "" }
q226666
Links.insert
train
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 ...
python
{ "resource": "" }
q226667
Scripts.insert
train
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. ...
python
{ "resource": "" }
q226668
Head.get_meta
train
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...
python
{ "resource": "" }
q226669
Head.replace_meta
train
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...
python
{ "resource": "" }
q226670
randompaths
train
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
python
{ "resource": "" }
q226671
Site.setup
train
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...
python
{ "resource": "" }
q226672
AsyncResponseMiddleware
train
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
python
{ "resource": "" }
q226673
Protocol.encode
train
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)
python
{ "resource": "" }
q226674
Chat.on_message
train
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 = ' '....
python
{ "resource": "" }
q226675
Rpc.rpc_message
train
async def rpc_message(self, request, message): '''Publish a message via JSON-RPC''' await self.pubsub.publish(self.channel, message) return 'OK'
python
{ "resource": "" }
q226676
WebChat.setup
train
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 ...
python
{ "resource": "" }
q226677
WsgiResponse._get_headers
train
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...
python
{ "resource": "" }
q226678
rpc_method
train
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...
python
{ "resource": "" }
q226679
clean_path_middleware
train
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...
python
{ "resource": "" }
q226680
authorization_middleware
train
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 =...
python
{ "resource": "" }
q226681
wait_for_body_middleware
train
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 <>`. ''' ...
python
{ "resource": "" }
q226682
middleware_in_executor
train
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...
python
{ "resource": "" }
q226683
DiningPhilosophers.release_forks
train
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...
python
{ "resource": "" }
q226684
hello
train
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'), ...
python
{ "resource": "" }
q226685
parse_headers
train
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...
python
{ "resource": "" }
q226686
HttpBodyReader._waiting_expect
train
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
python
{ "resource": "" }
q226687
MultipartPart.base64
train
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
python
{ "resource": "" }
q226688
MultipartPart.feed_data
train
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)
python
{ "resource": "" }
q226689
server
train
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...
python
{ "resource": "" }
q226690
TunnelResponse.request
train
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) ...
python
{ "resource": "" }
q226691
TunnelResponse.pre_request
train
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', ...
python
{ "resource": "" }
q226692
Protocol.connection_lost
train
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)
python
{ "resource": "" }
q226693
ProtocolConsumer.start
train
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. ...
python
{ "resource": "" }
q226694
process_global
train
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...
python
{ "resource": "" }
q226695
get_environ_proxies
train
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...
python
{ "resource": "" }
q226696
has_vary_header
train
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...
python
{ "resource": "" }
q226697
PulsarStoreClient.execute
train
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) ...
python
{ "resource": "" }
q226698
handle_cookies
train
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...
python
{ "resource": "" }
q226699
WebSocket.on_headers
train
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...
python
{ "resource": "" }