INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Remove all children ( and descendants ) below ADDRESS.
def prune(self, address): ''' Remove all children (and descendants) below ADDRESS. Arguments: address (str): the address to be pruned ''' try: for step in self._walk_to_address(address): node = step except AddressNotInTree: ...
Returns a stream of pairs of node addresses and data raising AddressNotInTree if ADDRESS is not in the tree.
def walk(self, address): ''' Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded i...
Returns all predecessor transaction ids for a write of the provided address.
def find_write_predecessors(self, address): """Returns all predecessor transaction ids for a write of the provided address. Arguments: address (str): the radix address Returns: a set of transaction ids """ # A write operation must be preceded by: # ...
Add a predecessor - successor relationship between one txn id and a set of predecessors.
def add_relationship(self, txn_id, predecessors): """Add a predecessor-successor relationship between one txn id and a set of predecessors. Args: txn_id (str): The transaction id of the transaction. predecessors (set): The transaction ids of the transacti...
Returns whether the predecessor is a predecessor or a predecessor of a predecessor... of any of the others.
def is_predecessor_of_other(self, predecessor, others): """Returns whether the predecessor is a predecessor or a predecessor of a predecessor...of any of the others. Args: predecessor (str): The txn id of the predecessor. others (list(str)): The txn id of the successor. ...
Use the predecessor tree to find dependencies based on inputs.
def _find_input_dependencies(self, inputs): """Use the predecessor tree to find dependencies based on inputs. Returns: A list of transaction ids. """ dependencies = [] for address in inputs: dependencies.extend( self._predecessor_tree.find_read_predec...
Use the predecessor tree to find dependencies based on outputs.
def _find_output_dependencies(self, outputs): """Use the predecessor tree to find dependencies based on outputs. Returns: A list of transaction ids. """ dependencies = [] for address in outputs: dependencies.extend( self._predecessor_tree.find_write_p...
Starting with the batch referenced by batch_signature iterate back through the batches and for each valid batch collect the context_id. At the end remove contexts for txns that are other txn s predecessors.
def _get_contexts_for_squash(self, batch_signature): """Starting with the batch referenced by batch_signature, iterate back through the batches and for each valid batch collect the context_id. At the end remove contexts for txns that are other txn's predecessors. Args: batch...
Decide if possible_successor should be replayed.
def _is_txn_to_replay(self, txn_id, possible_successor, already_seen): """Decide if possible_successor should be replayed. Args: txn_id (str): Id of txn in failed batch. possible_successor (str): Id of txn to possibly replay. already_seen (list): A list of possible_s...
Remove transactions from scheduled and txn_results for successors of txns in a failed batch. These transactions will now or in the future be rescheduled in next_transaction ; giving a replay ability.
def _remove_subsequent_result_because_of_batch_failure(self, sig): """Remove transactions from scheduled and txn_results for successors of txns in a failed batch. These transactions will now, or in the future be rescheduled in next_transaction; giving a replay ability. Args: ...
Set the first batch id that doesn t have all results.
def _set_least_batch_id(self, txn_signature): """Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set. """ batch = self._batches_by_txn_id[txn_signature] least...
Returns whether the transaction is in a valid batch.
def _txn_is_in_valid_batch(self, txn_id): """Returns whether the transaction is in a valid batch. Args: txn_id (str): The transaction header signature. Returns: (bool): True if the txn's batch is valid, False otherwise. """ batch = self._batches_by_txn_...
Executes the key generation operation given the parsed arguments.
def do_keygen(args): """Executes the key generation operation, given the parsed arguments. Args: args (:obj:`Namespace`): The parsed args. """ if args.key_name is not None: key_name = args.key_name else: key_name = 'validator' key_dir = get_key_dir() if not os.path...
Determines the height and width of the console window
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
Sends a message containing our peers to the connection identified by connection_id.
def send_peers(self, connection_id): """Sends a message containing our peers to the connection identified by connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. """ with self._lock...
Adds candidate endpoints to the list of endpoints to attempt to peer with.
def add_candidate_peer_endpoints(self, peer_endpoints): """Adds candidate endpoints to the list of endpoints to attempt to peer with. Args: peer_endpoints ([str]): A list of public uri's which the validator can attempt to peer with. """ if self._topol...
Returns the list of public keys for all peers.
def get_peers_public_keys(self): """Returns the list of public keys for all peers.""" with self._lock: # Use a generator inside the list comprehension to filter out None # values in a single pass return [key for key in (self._network.connection_id_...
Registers a connected connection_id.
def register_peer(self, connection_id, endpoint): """Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new ...
Removes a connection_id from the registry.
def unregister_peer(self, connection_id): """Removes a connection_id from the registry. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. """ public_key = self.peer_to_public_key(connection_id) ...
Sends a message via the network.
def send(self, message_type, message, connection_id, one_way=False): """Sends a message via the network. Args: message_type (str): The type of the message. message (bytes): The message to be sent. connection_id (str): The connection to send it to. """ ...
Broadcast gossip messages.
def broadcast(self, gossip_message, message_type, exclude=None): """Broadcast gossip messages. Broadcast the message to all peers unless they are in the excluded list. Args: gossip_message: The message to be broadcast. message_type: Type of the message. ...
Adds candidate endpoints to the list of endpoints to attempt to peer with.
def add_candidate_peer_endpoints(self, peer_endpoints): """Adds candidate endpoints to the list of endpoints to attempt to peer with. Args: peer_endpoints ([str]): A list of public uri's which the validator can attempt to peer with. """ with self._loc...
Check to see if the successful connection is meant to be peered with. If not it should be used to get the peers from the endpoint.
def connect_success(self, connection_id): """ Check to see if the successful connection is meant to be peered with. If not, it should be used to get the peers from the endpoint. """ endpoint = self._network.connection_id_to_endpoint(connection_id) endpoint_info = self._te...
Returns pair of byte pointer and size value for use as return parameters in a LIBRARY call
def prepare_vec_result(pointer_type=ctypes.c_uint8): """Returns pair of byte pointer and size value for use as return parameters in a LIBRARY call """ return ( ctypes.POINTER(pointer_type)(), ctypes.c_size_t(0), ctypes.c_size_t(0), )
Explicitly drop this pointer. The memory will be deallocated via the drop_ffi_call_fn passed to the constructor.
def drop(self): """Explicitly drop this pointer. The memory will be deallocated via the drop_ffi_call_fn passed to the constructor. """ if self._ptr: LIBRARY.call(self._drop_ffi_fn, self._ptr) self._ptr = None
Returns the default PathConfig as calculated based on SAWTOOTH_HOME ( if set ) and operating system.
def get_default_path_config(): """Returns the default PathConfig as calculated based on SAWTOOTH_HOME (if set) and operating system. """ if 'SAWTOOTH_HOME' in os.environ: home_dir = os.environ['SAWTOOTH_HOME'] return PathConfig( config_dir=os.path.join(home_dir, 'etc'), ...
Returns a PathConfig created by loading a TOML file from the filesystem.
def load_toml_path_config(filename): """Returns a PathConfig created by loading a TOML file from the filesystem. """ if not os.path.exists(filename): LOGGER.info( "Skipping path loading from non-existent config file: %s", filename) return PathConfig() LOGGER....
Given a list of PathConfig objects merges them into a single PathConfig giving priority in the order of the configs ( first has highest priority ).
def merge_path_config(configs, config_dir_override): """ Given a list of PathConfig objects, merges them into a single PathConfig, giving priority in the order of the configs (first has highest priority). """ config_dir = None log_dir = None data_dir = None key_dir = None policy_dir ...
Determines if the system should be put in genesis mode
def requires_genesis(self): """ Determines if the system should be put in genesis mode Returns: bool: return whether or not a genesis block is required to be generated. Raises: InvalidGenesisStateError: raises this error if there is invalid ...
Starts the genesis block creation process. Will call the given on_done callback on successful completion.
def start(self, on_done): """ Starts the genesis block creation process. Will call the given `on_done` callback on successful completion. Args: on_done (function): a function called on completion Raises: InvalidGenesisStateError: raises this error if a ...
Returns the block publisher based on the consensus module set by the sawtooth_settings transaction family.
def _get_block_publisher(self, state_hash): """Returns the block publisher based on the consensus module set by the "sawtooth_settings" transaction family. Args: state_hash (str): The current state root hash for reading settings. Raises: InvalidGenesisStateError...
Returns a blocker wrapper with the basics of the block header in place
def _generate_genesis_block(self): """ Returns a blocker wrapper with the basics of the block header in place """ genesis_header = block_pb2.BlockHeader( block_num=0, previous_block_id=NULL_BLOCK_IDENTIFIER, signer_public_key=self._identity_signer.get_...
The block should be complete and the final signature from the publishing validator ( this validator ) needs to be added.
def _sign_block(self, block): """ The block should be complete and the final signature from the publishing validator (this validator) needs to be added. """ block_header = block.block_header header_bytes = block_header.SerializeToString() signature = self._identit...
Remove all expired entries from the cache.
def _purge_expired(self): """ Remove all expired entries from the cache. """ time_horizon = time.time() - self._keep_time new_cache = {} for (k, v) in self._cache.items(): if v.timestamp > time_horizon: new_cache[k] = v self._cache = ne...
Determines if there is a log config in the config directory and returns it. If it does not exist return None.
def _get_config(): """Determines if there is a log config in the config directory and returns it. If it does not exist, return None. Returns: log_config (dict): The dictionary to pass to logging.config.dictConfig """ conf_file = os.path.join(_get_config_dir(), 'log_config.toml') if o...
Adds argument parser for the peer command
def add_peer_parser(subparsers, parent_parser): """Adds argument parser for the peer command Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object """ parser = subparsers.add_parser( 'peer', help='Disp...
Returns a tuple of the current size of the pending batch queue and the current queue limit.
def pending_batch_info(self): """Returns a tuple of the current size of the pending batch queue and the current queue limit. """ c_length = ctypes.c_int(0) c_limit = ctypes.c_int(0) self._call( 'pending_batch_info', ctypes.byref(c_length), ...
The existing chain has been updated the current head block has changed.
def on_chain_updated(self, chain_head, committed_batches=None, uncommitted_batches=None): """ The existing chain has been updated, the current head block has changed. :param chain_head: the new head of block_chain, can be None if ...
Internal coroutine for receiving messages
def _receive_message(self): """ Internal coroutine for receiving messages """ while True: try: if self._socket.getsockopt(zmq.TYPE) == zmq.ROUTER: zmq_identity, msg_bytes = \ yield from self._socket.recv_multipart() ...
: param msg: protobuf validator_pb2. Message
def send_message(self, msg, connection_id=None): """ :param msg: protobuf validator_pb2.Message """ zmq_identity = None if connection_id is not None and self._connections is not None: if connection_id in self._connections: connection_info = self._conne...
Should be used instead of send_message when you want to close the connection once the message is sent.
def send_last_message(self, msg, connection_id=None): """ Should be used instead of send_message, when you want to close the connection once the message is sent. :param msg: protobuf validator_pb2.Message """ zmq_identity = None if connection_id is not None and s...
Setup the asyncio event loop.
def setup(self, socket_type, complete_or_error_queue): """Setup the asyncio event loop. Args: socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER complete_or_error_queue (queue.Queue): A way to propagate errors back to the calling thread. Needed since t...
Get stored public key for a connection.
def connection_id_to_public_key(self, connection_id): """ Get stored public key for a connection. """ with self._connections_lock: try: connection_info = self._connections[connection_id] return connection_info.public_key except KeyE...
Get stored connection id for a public key.
def public_key_to_connection_id(self, public_key): """ Get stored connection id for a public key. """ with self._connections_lock: for connection_id, connection_info in self._connections.items(): if connection_info.public_key == public_key: ...
Get stored public key for a connection.
def connection_id_to_endpoint(self, connection_id): """ Get stored public key for a connection. """ with self._connections_lock: try: connection_info = self._connections[connection_id] return connection_info.uri except KeyError: ...
Get status of the connection during Role enforcement.
def get_connection_status(self, connection_id): """ Get status of the connection during Role enforcement. """ with self._connections_lock: try: connection_info = self._connections[connection_id] return connection_info.status except ...
Determines if an additional incoming network connection should be permitted.
def allow_inbound_connection(self): """Determines if an additional incoming network connection should be permitted. Returns: bool """ LOGGER.debug("Determining whether inbound connection should " "be allowed. num connections: %s max %s", ...
Adds an outbound connection to the network.
def add_outbound_connection(self, uri): """Adds an outbound connection to the network. Args: uri (str): The zmq-style (e.g. tcp://hostname:port) uri to attempt to connect to. """ LOGGER.debug("Adding connection to %s", uri) conn = OutboundConnection( ...
Send ConnectionRequest to an inbound connection. This allows the validator to be authorized by the incoming connection.
def send_connect_request(self, connection_id): """ Send ConnectionRequest to an inbound connection. This allows the validator to be authorized by the incoming connection. """ connect_message = ConnectionRequest(endpoint=self._public_endpoint) self._safe_send( ...
Send a message of message_type: param connection_id: the identity for the connection to send to: param message_type: validator_pb2. Message. * enum value: param data: bytes serialized protobuf: return: future. Future
def send(self, message_type, data, connection_id, callback=None, one_way=False): """ Send a message of message_type :param connection_id: the identity for the connection to send to :param message_type: validator_pb2.Message.* enum value :param data: bytes serialized ...
Returns the connection id associated with a publically reachable endpoint or raises KeyError if the endpoint is not found.
def get_connection_id_by_endpoint(self, endpoint): """Returns the connection id associated with a publically reachable endpoint or raises KeyError if the endpoint is not found. Args: endpoint (str): A zmq-style uri which identifies a publically reachable endp...
Adds the endpoint to the connection definition. When the connection is created by the send/ receive thread we do not yet have the endpoint of the remote node. That is not known until we process the incoming ConnectRequest.
def update_connection_endpoint(self, connection_id, endpoint): """Adds the endpoint to the connection definition. When the connection is created by the send/receive thread, we do not yet have the endpoint of the remote node. That is not known until we process the incoming ConnectRequest....
Adds the public_key to the connection definition.
def update_connection_public_key(self, connection_id, public_key): """Adds the public_key to the connection definition. Args: connection_id (str): The identifier for the connection. public_key (str): The public key used to enforce permissions on connections. ...
Send a message of message_type and close the connection.: param connection_id: the identity for the connection to send to: param message_type: validator_pb2. Message. * enum value: param data: bytes serialized protobuf: return: future. Future
def send_last_message(self, message_type, data, connection_id, callback=None, one_way=False): """ Send a message of message_type and close the connection. :param connection_id: the identity for the connection to send to :param message_type: validator_pb2.Message...
Sends a message of message_type
def send(self, message_type, data, callback=None, one_way=False): """Sends a message of message_type Args: message_type (validator_pb2.Message): enum value data (bytes): serialized protobuf callback (function): a callback function to call when a respo...
Returns the header of the block
def header(self): """ Returns the header of the block """ if self._block_header is None: self._block_header = BlockHeader() self._block_header.ParseFromString(self.block.header) return self._block_header
Returns the state view for an arbitrary block.
def state_view_for_block(block_wrapper, state_view_factory): """ Returns the state view for an arbitrary block. Args: block_wrapper (BlockWrapper): The block for which a state view is to be returned state_view_factory (StateViewFactory): The state view fa...
Returns the settings view for an arbitrary block.
def settings_view_for_block(block_wrapper, settings_view_factory): """ Returns the settings view for an arbitrary block. Args: block_wrapper (BlockWrapper): The block for which a settings view is to be returned settings_view_factory (SettingsViewFactory):...
Anonymize IPv4 and IPv6: param remote_addr: to/ 24 ( zero d ) and/ 48 ( zero d ).
def anonymize(remote_addr): """ Anonymize IPv4 and IPv6 :param remote_addr: to /24 (zero'd) and /48 (zero'd). """ if not isinstance(remote_addr, text_type) and isinstance(remote_addr, str): remote_addr = remote_addr.decode('ascii', 'ignore') try: ipv4 = ipaddress.IPv4Address(rem...
Extract <h1 > title from web page. The title is * probably * the text node which is the nearest H1 node in context to an element with the isso - thread id.
def thread(data, default=u"Untitled.", id=None): """ Extract <h1> title from web page. The title is *probably* the text node, which is the nearest H1 node in context to an element with the `isso-thread` id. """ html = html5lib.parse(data, treebuilder="dom") assert html.lastChild.nodeName == "h...
Process a thread and insert its comments in the DB.
def insert(self, thread): """Process a thread and insert its comments in the DB.""" thread_id = thread['id'] title = thread['title'] self.db.threads.new(thread_id, title) comments = list(map(self._build_comment, thread['comments'])) comments.sort(key=lambda comment: comm...
Process the input file and fill the DB.
def migrate(self): """Process the input file and fill the DB.""" with io.open(self.json_file, 'rt', encoding='utf8') as fh: threads = json.load(fh) progress = Progress(len(threads)) for i, thread in enumerate(threads): progress.update(i, str(i)) self....
Add new comment to DB and return a mapping of: attribute: fields and database values.
def add(self, uri, c): """ Add new comment to DB and return a mapping of :attribute:`fields` and database values. """ if c.get("parent") is not None: ref = self.get(c["parent"]) if ref.get("parent") is not None: c["parent"] = ref["parent"]...
Turn off email notifications for replies to this comment.
def unsubscribe(self, email, id): """ Turn off email notifications for replies to this comment. """ self.db.execute([ 'UPDATE comments SET', ' notification=0', 'WHERE email=? AND (id=? OR parent=?);'], (email, id, id))
Update comment: param: id with values from: param: data and return updated comment.
def update(self, id, data): """ Update comment :param:`id` with values from :param:`data` and return updated comment. """ self.db.execute([ 'UPDATE comments SET', ','.join(key + '=' + '?' for key in data), 'WHERE id=?;'], list(data....
Search for comment: param: id and return a mapping of: attr: fields and values.
def get(self, id): """ Search for comment :param:`id` and return a mapping of :attr:`fields` and values. """ rv = self.db.execute( 'SELECT * FROM comments WHERE id=?', (id, )).fetchone() if rv: return dict(zip(Comments.fields, rv)) return ...
Return comments for admin with: param: mode.
def fetchall(self, mode=5, after=0, parent='any', order_by='id', limit=100, page=0, asc=1): """ Return comments for admin with :param:`mode`. """ fields_comments = ['tid', 'id', 'parent', 'created', 'modified', 'mode', 'remote_addr', 'text', 'a...
Return comments for: param: uri with: param: mode.
def fetch(self, uri, mode=5, after=0, parent='any', order_by='id', asc=1, limit=None): """ Return comments for :param:`uri` with :param:`mode`. """ sql = ['SELECT comments.* FROM comments INNER JOIN threads ON', ' threads.uri=? AND comments.tid=threads.id ...
Delete a comment. There are two distinctions: a comment is referenced by another valid comment s parent attribute or stand - a - lone. In this case the comment can t be removed without losing depending comments. Hence delete removes all visible data such as text author email website sets the mode field to 4.
def delete(self, id): """ Delete a comment. There are two distinctions: a comment is referenced by another valid comment's parent attribute or stand-a-lone. In this case the comment can't be removed without losing depending comments. Hence, delete removes all visible data such as...
+ 1 a given comment. Returns the new like count ( may not change because the creater can t vote on his/ her own comment and multiple votes from the same ip address are ignored as well ).
def vote(self, upvote, id, remote_addr): """+1 a given comment. Returns the new like count (may not change because the creater can't vote on his/her own comment and multiple votes from the same ip address are ignored as well).""" rv = self.db.execute( 'SELECT likes, dislikes...
Return comment count for main thread and all reply threads for one url.
def reply_count(self, url, mode=5, after=0): """ Return comment count for main thread and all reply threads for one url. """ sql = ['SELECT comments.parent,count(*)', 'FROM comments INNER JOIN threads ON', ' threads.uri=? AND comments.tid=threads.id AND',...
Return comment count for one ore more urls..
def count(self, *urls): """ Return comment count for one ore more urls.. """ threads = dict(self.db.execute([ 'SELECT threads.uri, COUNT(comments.id) FROM comments', 'LEFT OUTER JOIN threads ON threads.id = tid AND comments.mode = 1', 'GROUP BY thread...
Remove comments older than: param: delta.
def purge(self, delta): """ Remove comments older than :param:`delta`. """ self.db.execute([ 'DELETE FROM comments WHERE mode = 2 AND ? - created > ?;' ], (time.time(), delta)) self._remove_stale()
Parse: param string: into: class: datetime. timedelta you can use any ( logical ) combination of Nw Nd Nh and Nm e. g. 1h30m for 1 hour 30 minutes or 3w for 3 weeks.
def timedelta(string): """ Parse :param string: into :class:`datetime.timedelta`, you can use any (logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30 minutes or `3w` for 3 weeks. Raises a ValueError if the input is invalid/unparseable. >>> print(timedelta("3w")) 21 days...
Factory to create hash functions from configuration section. If an algorithm takes custom parameters you can separate them by a colon like this: pbkdf2: arg1: arg2: arg3.
def new(conf): """Factory to create hash functions from configuration section. If an algorithm takes custom parameters, you can separate them by a colon like this: pbkdf2:arg1:arg2:arg3.""" algorithm = conf.get("algorithm") salt = conf.get("salt").encode("utf-8") if algorithm == "none": ...
Calculate hash from value ( must be bytes ).
def hash(self, val): """Calculate hash from value (must be bytes).""" if not isinstance(val, bytes): raise _TypeError("val", "bytes", val) rv = self.compute(val) if not isinstance(val, bytes): raise _TypeError("val", "bytes", rv) return rv
Calculate hash from unicode value and return hex value as unicode
def uhash(self, val): """Calculate hash from unicode value and return hex value as unicode""" if not isinstance(val, string_types): raise _TypeError("val", "str", val) return codecs.encode(self.hash(val.encode("utf-8")), "hex_codec").decode("utf-8")
A decorator to check for CSRF on POST/ PUT/ DELETE using a <form > element and JS to execute automatically ( see #40 for a proof - of - concept ).
def xhr(func): """A decorator to check for CSRF on POST/PUT/DELETE using a <form> element and JS to execute automatically (see #40 for a proof-of-concept). When an attacker uses a <form> to downvote a comment, the browser *should* add a `Content-Type: ...` header with three possible values: * appl...
@api { get }/ get comments @apiGroup Thread @apiDescription Queries the comments of a thread.
def moderate(self, environ, request, id, action, key): try: id = self.isso.unsign(key, max_age=2**32) except (BadSignature, SignatureExpired): raise Forbidden item = self.comments.get(id) thread = self.threads.get(item['tid']) link = local("origin") + thr...
Decorator to execute each: param func: call in a separate thread.
def threaded(func): """ Decorator to execute each :param func: call in a separate thread. """ def dec(self, *args, **kwargs): thread.start_new_thread(func, (self, ) + args, kwargs) return dec
Reconstruct host from environment. A modified version of http:// www. python. org/ dev/ peps/ pep - 0333/ #url - reconstruction
def host(environ): # pragma: no cover """ Reconstruct host from environment. A modified version of http://www.python.org/dev/peps/pep-0333/#url-reconstruction """ url = environ['wsgi.url_scheme'] + '://' if environ.get('HTTP_HOST'): url += environ['HTTP_HOST'] else: url +=...
Parse: param: name into ( netloc port ssl )
def urlsplit(name): """ Parse :param:`name` into (netloc, port, ssl) """ if not (isinstance(name, string_types)): name = str(name) if not name.startswith(('http://', 'https://')): name = 'http://' + name rv = urlparse(name) if rv.scheme == 'https' and rv.port is None: ...
Basically the counter - part of: func: urlsplit.
def urljoin(netloc, port, ssl): """ Basically the counter-part of :func:`urlsplit`. """ rv = ("https" if ssl else "http") + "://" + netloc if ssl and port != 443 or not ssl and port != 80: rv += ":%i" % port return rv
Return a function that returns a valid HTTP Origin or localhost if none found.
def origin(hosts): """ Return a function that returns a valid HTTP Origin or localhost if none found. """ hosts = [urlsplit(h) for h in hosts] def func(environ): if 'ISSO_CORS_ORIGIN' in environ: return environ['ISSO_CORS_ORIGIN'] if not hosts: return "...
Same as urllib2. urlopen or urllib. request. urlopen the only difference is that it links to the internal opener.
def urlopen(self, url, data=None, *args, **kwargs): """ Same as urllib2.urlopen or urllib.request.urlopen, the only difference is that it links to the internal opener. """ logger.info('opening: \'%s\'', url) if data is None: return self.opener.open(url) ...
Similar to urllib. urlretrieve or urllib. request. urlretrieve only that * filname * is required.
def urlretrieve(self, url, filename, data=None): """ Similar to urllib.urlretrieve or urllib.request.urlretrieve only that *filname* is required. :param url: URL to download. :param filename: Filename to save the content to. :param data: Valid URL-encoded data. :...
parse url and the result is tuple of ( hostname port resource path and the flag of secure mode )
def parse_url(url): """ parse url and the result is tuple of (hostname, port, resource path and the flag of secure mode) url: url string. """ if ":" not in url: raise ValueError("url is invalid") scheme, url = url.split(":", 1) parsed = urlparse(url, scheme="ws") if parsed...
try to retrieve proxy host and port from environment if not provided in options. result is ( proxy_host proxy_port proxy_auth ). proxy_auth is tuple of username and password of proxy authentication information.
def get_proxy_info( hostname, is_secure, proxy_host=None, proxy_port=0, proxy_auth=None, no_proxy=None, proxy_type='http'): """ try to retrieve proxy host and port from environment if not provided in options. result is (proxy_host, proxy_port, proxy_auth). proxy_auth is tuple of user...
connect to url and return websocket object.
def create_connection(url, timeout=None, class_=WebSocket, **options): """ connect to url and return websocket object. Connect to url and return the WebSocket object. Passing optional timeout parameter will set the timeout on the socket. If no timeout is supplied, the global default timeout set...
Set the timeout to the websocket.
def settimeout(self, timeout): """ Set the timeout to the websocket. timeout: timeout time(second). """ self.sock_opt.timeout = timeout if self.sock: self.sock.settimeout(timeout)
Connect to url. url is websocket url scheme. ie. ws:// host: port/ resource You can customize using options. If you set header list object you can set your own custom header.
def connect(self, url, **options): """ Connect to url. url is websocket url scheme. ie. ws://host:port/resource You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> ws = WebSocket() >>> ws.connect("ws://echo....
Send the data as string.
def send(self, payload, opcode=ABNF.OPCODE_TEXT): """ Send the data as string. payload: Payload must be utf-8 string or unicode, if the opcode is OPCODE_TEXT. Otherwise, it must be string(byte array) opcode: operation code to send. Please see OPCODE_...
Send the data frame.
def send_frame(self, frame): """ Send the data frame. frame: frame data created by ABNF.create_frame >>> ws = create_connection("ws://echo.websocket.org/") >>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT) >>> ws.send_frame(frame) >>> cont_frame = ABNF.c...
send ping data.
def ping(self, payload=""): """ send ping data. payload: data payload to send server. """ if isinstance(payload, six.text_type): payload = payload.encode("utf-8") self.send(payload, ABNF.OPCODE_PING)
send pong data.
def pong(self, payload): """ send pong data. payload: data payload to send server. """ if isinstance(payload, six.text_type): payload = payload.encode("utf-8") self.send(payload, ABNF.OPCODE_PONG)
Receive string data ( byte array ) from the server.
def recv(self): """ Receive string data(byte array) from the server. return value: string(byte array) value. """ with self.readlock: opcode, data = self.recv_data() if six.PY3 and opcode == ABNF.OPCODE_TEXT: return data.decode("utf-8") eli...
Receive data with operation code.
def recv_data(self, control_frame=False): """ Receive data with operation code. control_frame: a boolean flag indicating whether to return control frame data, defaults to False return value: tuple of operation code and string(byte array) value. """ opcode, fram...
Receive data with operation code.
def recv_data_frame(self, control_frame=False): """ Receive data with operation code. control_frame: a boolean flag indicating whether to return control frame data, defaults to False return value: tuple of operation code and string(byte array) value. """ while ...
send close data to the server.
def send_close(self, status=STATUS_NORMAL, reason=six.b("")): """ send close data to the server. status: status code to send. see STATUS_XXX. reason: the reason to close. This must be string or bytes. """ if status < 0 or status >= ABNF.LENGTH_16: raise Valu...
Close Websocket object
def close(self, status=STATUS_NORMAL, reason=six.b(""), timeout=3): """ Close Websocket object status: status code to send. see STATUS_XXX. reason: the reason to close. This must be string. timeout: timeout until receive a close frame. If None, it will wait forever...