INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Seek to the most recent available offset for partitions.
def seek_to_end(self, *partitions): """Seek to the most recent available offset for partitions. Arguments: *partitions: Optionally provide specific TopicPartitions, otherwise default to all assigned partitions. Raises: AssertionError: If any partition is...
Subscribe to a list of topics or a topic regex pattern.
def subscribe(self, topics=(), pattern=None, listener=None): """Subscribe to a list of topics, or a topic regex pattern. Partitions will be dynamically assigned via a group coordinator. Topic subscriptions are not incremental: this list will replace the current assignment (if there is o...
Unsubscribe from all topics and clear all assigned partitions.
def unsubscribe(self): """Unsubscribe from all topics and clear all assigned partitions.""" self._subscription.unsubscribe() self._coordinator.close() self._client.cluster.need_all_topic_metadata = False self._client.set_topics([]) log.debug("Unsubscribed all topics or pa...
Look up the offsets for the given partitions by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition.
def offsets_for_times(self, timestamps): """Look up the offsets for the given partitions by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition. This is a blocking...
Get the first offset for the given partitions.
def beginning_offsets(self, partitions): """Get the first offset for the given partitions. This method does not change the current consumer position of the partitions. Note: This method may block indefinitely if the partition does not exist. Arguments: ...
Get the last offset for the given partitions. The last offset of a partition is the offset of the upcoming message i. e. the offset of the last available message + 1.
def end_offsets(self, partitions): """Get the last offset for the given partitions. The last offset of a partition is the offset of the upcoming message, i.e. the offset of the last available message + 1. This method does not change the current consumer position of the partition...
Return True iff this consumer can/ should join a broker - coordinated group.
def _use_consumer_group(self): """Return True iff this consumer can/should join a broker-coordinated group.""" if self.config['api_version'] < (0, 9): return False elif self.config['group_id'] is None: return False elif not self._subscription.partitions_auto_assig...
Set the fetch position to the committed position ( if there is one ) or reset it using the offset reset policy the user has configured.
def _update_fetch_positions(self, partitions): """Set the fetch position to the committed position (if there is one) or reset it using the offset reset policy the user has configured. Arguments: partitions (List[TopicPartition]): The partitions that need updating fet...
Return a nested dictionary snapshot of all metrics and their values at this time. Example: { category: { metric1_name: 42. 0 metric2_name: foo } }
def snapshot(self): """ Return a nested dictionary snapshot of all metrics and their values at this time. Example: { 'category': { 'metric1_name': 42.0, 'metric2_name': 'foo' } } """ return dict((category, di...
Return a string category for the metric.
def get_category(self, metric): """ Return a string category for the metric. The category is made up of this reporter's prefix and the metric's group and tags. Examples: prefix = 'foo', group = 'bar', tags = {'a': 1, 'b': 2} returns: 'foo.bar.a=1,b=2' ...
Queues a node for asynchronous connection during the next. poll ()
def maybe_connect(self, node_id, wakeup=True): """Queues a node for asynchronous connection during the next .poll()""" if self._can_connect(node_id): self._connecting.add(node_id) # Wakeup signal is useful in case another thread is # blocked waiting for incoming netwo...
Idempotent non - blocking connection attempt to the given node id.
def _maybe_connect(self, node_id): """Idempotent non-blocking connection attempt to the given node id.""" with self._lock: conn = self._conns.get(node_id) if conn is None: broker = self.cluster.broker_metadata(node_id) assert broker, 'Broker id %s...
Check whether a node is connected and ok to send more requests.
def ready(self, node_id, metadata_priority=True): """Check whether a node is connected and ok to send more requests. Arguments: node_id (int): the id of the node to check metadata_priority (bool): Mark node as not-ready if a metadata refresh is required. Default:...
Return True iff the node_id is connected.
def connected(self, node_id): """Return True iff the node_id is connected.""" conn = self._conns.get(node_id) if conn is None: return False return conn.connected()
Close one or all broker connections.
def close(self, node_id=None): """Close one or all broker connections. Arguments: node_id (int, optional): the id of the node to close """ with self._lock: if node_id is None: self._close() conns = list(self._conns.values()) ...
Check whether the node connection has been disconnected or failed.
def is_disconnected(self, node_id): """Check whether the node connection has been disconnected or failed. A disconnected node has either been closed or has failed. Connection failures are usually transient and can be resumed in the next ready() call, but there are cases where transient ...
Return the number of milliseconds to wait based on the connection state before attempting to send data. When disconnected this respects the reconnect backoff time. When connecting returns 0 to allow non - blocking connect to finish. When connected returns a very large number to handle slow/ stalled connections.
def connection_delay(self, node_id): """ Return the number of milliseconds to wait, based on the connection state, before attempting to send data. When disconnected, this respects the reconnect backoff time. When connecting, returns 0 to allow non-blocking connect to finish. When...
Check whether a node is ready to send more requests.
def is_ready(self, node_id, metadata_priority=True): """Check whether a node is ready to send more requests. In addition to connection-level checks, this method also is used to block additional requests from being sent during a metadata refresh. Arguments: node_id (int): id...
Send a request to a specific node. Bytes are placed on an internal per - connection send - queue. Actual network I/ O will be triggered in a subsequent call to. poll ()
def send(self, node_id, request, wakeup=True): """Send a request to a specific node. Bytes are placed on an internal per-connection send-queue. Actual network I/O will be triggered in a subsequent call to .poll() Arguments: node_id (int): destination node request...
Try to read and write to sockets.
def poll(self, timeout_ms=None, future=None): """Try to read and write to sockets. This method will also attempt to complete node connections, refresh stale metadata, and run previously-scheduled tasks. Arguments: timeout_ms (int, optional): maximum amount of time to wait (...
Get the number of in - flight requests for a node or all nodes.
def in_flight_request_count(self, node_id=None): """Get the number of in-flight requests for a node or all nodes. Arguments: node_id (int, optional): a specific node to check. If unspecified, return the total for all nodes Returns: int: pending in-flight...
Choose the node with fewest outstanding requests with fallbacks.
def least_loaded_node(self): """Choose the node with fewest outstanding requests, with fallbacks. This method will prefer a node with an existing connection and no in-flight-requests. If no such node is found, a node will be chosen randomly from disconnected nodes that are not "blacked ...
Set specific topics to track for metadata.
def set_topics(self, topics): """Set specific topics to track for metadata. Arguments: topics (list of str): topics to check for metadata Returns: Future: resolves after metadata request/response """ if set(topics).difference(self._topics): f...
Add a topic to the list of topics tracked via metadata.
def add_topic(self, topic): """Add a topic to the list of topics tracked via metadata. Arguments: topic (str): topic to track Returns: Future: resolves after metadata request/response """ if topic in self._topics: return Future().success(set(...
Send a metadata request if needed.
def _maybe_refresh_metadata(self, wakeup=False): """Send a metadata request if needed. Returns: int: milliseconds until next refresh """ ttl = self.cluster.ttl() wait_for_in_progress_ms = self.config['request_timeout_ms'] if self._metadata_refresh_in_progress else 0 ...
Attempt to guess the version of a Kafka broker.
def check_version(self, node_id=None, timeout=2, strict=False): """Attempt to guess the version of a Kafka broker. Note: It is possible that this method blocks longer than the specified timeout. This can happen if the entire cluster is down and the client enters a bootstrap back...
Here we check the total amount of time elapsed since the oldest non - obsolete window. This give the total window_size of the batch which is the time used for Rate computation. However there is an issue if we do not have sufficient data for e. g. if only 1 second has elapsed in a 30 second window the measured rate will...
def window_size(self, config, now): # purge old samples before we compute the window size self._stat.purge_obsolete_samples(config, now) """ Here we check the total amount of time elapsed since the oldest non-obsolete window. This give the total window_size of the batch ...
Helper method to send produce requests.
def send_messages(self, topic, partition, *msg): """Helper method to send produce requests. Note that msg type *must* be encoded to bytes by user. Passing unicode message will not work, for example you should encode before calling send_messages via something like `unicode_message.encode...
Stop the producer ( async mode ). Blocks until async thread completes.
def stop(self, timeout=None): """ Stop the producer (async mode). Blocks until async thread completes. """ if timeout is not None: log.warning('timeout argument to stop() is deprecated - ' 'it will be removed in future release') if not self.as...
Append message to batch.
def append(self, offset, timestamp, key, value, headers=None): """ Append message to batch. """ assert not headers, "Headers not supported in v0/v1" # Check types if type(offset) != int: raise TypeError(offset) if self._magic == 0: timestamp = self...
Encode msg data into the msg_buffer which should be allocated to at least the size of this message.
def _encode_msg(self, start_pos, offset, timestamp, key, value, attributes=0): """ Encode msg data into the `msg_buffer`, which should be allocated to at least the size of this message. """ magic = self._magic buf = self._buffer pos = start_pos ...
Actual size of message to add
def size_in_bytes(self, offset, timestamp, key, value, headers=None): """ Actual size of message to add """ assert not headers, "Headers not supported in v0/v1" magic = self._magic return self.LOG_OVERHEAD + self.record_size(magic, key, value)
Upper bound estimate of record size.
def estimate_size_in_bytes(cls, magic, compression_type, key, value): """ Upper bound estimate of record size. """ assert magic in [0, 1], "Not supported magic" # In case of compression we may need another overhead for inner msg if compression_type: return ( ...
Allocate a buffer of the given size. This method blocks if there is not enough memory and the buffer pool is configured with blocking mode.
def allocate(self, size, max_time_to_block_ms): """ Allocate a buffer of the given size. This method blocks if there is not enough memory and the buffer pool is configured with blocking mode. Arguments: size (int): The buffer size to allocate in bytes [ignored] m...
Return buffers to the pool. If they are of the poolable size add them to the free list otherwise just mark the memory as free.
def deallocate(self, buf): """ Return buffers to the pool. If they are of the poolable size add them to the free list, otherwise just mark the memory as free. Arguments: buffer_ (io.BytesIO): The buffer to return """ with self._lock: # BytesIO.tru...
Compressed messages should pass in bytes_to_read ( via message size ) otherwise we decode from data as Int32
def decode(cls, data, bytes_to_read=None): """Compressed messages should pass in bytes_to_read (via message size) otherwise, we decode from data as Int32 """ if isinstance(data, bytes): data = io.BytesIO(data) if bytes_to_read is None: bytes_to_read = Int3...
Encode an integer to a varint presentation. See https:// developers. google. com/ protocol - buffers/ docs/ encoding?csw = 1#varints on how those can be produced.
def encode_varint(value, write): """ Encode an integer to a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: value (int): Value to encode write (function): Called per byte that needs ...
Number of bytes needed to encode an integer in variable - length format.
def size_of_varint(value): """ Number of bytes needed to encode an integer in variable-length format. """ value = (value << 1) ^ (value >> 63) if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return ...
Decode an integer from a varint presentation. See https:// developers. google. com/ protocol - buffers/ docs/ encoding?csw = 1#varints on how those can be produced.
def decode_varint(buffer, pos=0): """ Decode an integer from a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: buffer (bytearry): buffer to read from. pos (int): optional position to...
Encode and queue a kafka api request for sending.
def send_request(self, request, correlation_id=None): """Encode and queue a kafka api request for sending. Arguments: request (object): An un-encoded kafka request. correlation_id (int, optional): Optionally specify an ID to correlate requests with responses. If ...
Retrieve all pending bytes to send on the network
def send_bytes(self): """Retrieve all pending bytes to send on the network""" data = b''.join(self.bytes_to_send) self.bytes_to_send = [] return data
Process bytes received from the network.
def receive_bytes(self, data): """Process bytes received from the network. Arguments: data (bytes): any length bytes received from a network connection to a kafka broker. Returns: responses (list of (correlation_id, response)): any/all completed ...
Get or create a connection to a broker using host and port
def _get_conn(self, host, port, afi): """Get or create a connection to a broker using host and port""" host_key = (host, port) if host_key not in self._conns: self._conns[host_key] = BrokerConnection( host, port, afi, request_timeout_ms=self.timeout * ...
Returns the leader for a partition or None if the partition exists but has no leader.
def _get_leader_for_partition(self, topic, partition): """ Returns the leader for a partition or None if the partition exists but has no leader. Raises: UnknownTopicOrPartitionError: If the topic or partition is not part of the metadata. LeaderNot...
Returns the coordinator broker for a consumer group.
def _get_coordinator_for_group(self, group): """ Returns the coordinator broker for a consumer group. GroupCoordinatorNotAvailableError will be raised if the coordinator does not currently exist for the group. GroupLoadInProgressError is raised if the coordinator is available ...
Attempt to send a broker - agnostic request to one of the available brokers. Keep trying until you succeed.
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn): """ Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed. """ hosts = set() for broker in self.brokers.values(): host, port, afi = get...
Group a list of request payloads by topic + partition and send them to the leader broker for that partition using the supplied encode/ decode functions
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn): """ Group a list of request payloads by topic+partition and send them to the leader broker for that partition using the supplied encode/decode functions Arguments: payloads: list of object-like enti...
Send a list of requests to the consumer coordinator for the group specified using the supplied encode/ decode functions. As the payloads that use consumer - aware requests do not contain the group ( e. g. OffsetFetchRequest ) all payloads must be for a single group.
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn): """ Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. ...
Create an inactive copy of the client object suitable for passing to a separate thread.
def copy(self): """ Create an inactive copy of the client object, suitable for passing to a separate thread. Note that the copied connections are not initialized, so :meth:`.reinit` must be called on the returned copy. """ _conns = self._conns self._conns...
Fetch broker and topic - partition metadata from the server.
def load_metadata_for_topics(self, *topics, **kwargs): """Fetch broker and topic-partition metadata from the server. Updates internal data: broker list, topic/partition list, and topic/partition -> broker map. This method should be called after receiving any error. Note: Except...
Encode and send some ProduceRequests
def send_produce_request(self, payloads=(), acks=1, timeout=1000, fail_on_error=True, callback=None): """ Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of respo...
Encode and send a FetchRequest
def send_fetch_request(self, payloads=(), fail_on_error=True, callback=None, max_wait_time=100, min_bytes=4096): """ Encode and send a FetchRequest Payloads are grouped by topic and partition so they can be pipelined to the same brokers. """ e...
Performs additional validation steps which were not performed when this token was decoded. This method is part of the public API to indicate the intention that it may be overridden in subclasses.
def verify(self): """ Performs additional validation steps which were not performed when this token was decoded. This method is part of the "public" API to indicate the intention that it may be overridden in subclasses. """ # According to RFC 7519, the "exp" claim is OPT...
Ensures that the token type claim is present and has the correct value.
def verify_token_type(self): """ Ensures that the token type claim is present and has the correct value. """ try: token_type = self.payload[api_settings.TOKEN_TYPE_CLAIM] except KeyError: raise TokenError(_('Token has no type')) if self.token_type...
Updates the expiration time of a token.
def set_exp(self, claim='exp', from_time=None, lifetime=None): """ Updates the expiration time of a token. """ if from_time is None: from_time = self.current_time if lifetime is None: lifetime = self.lifetime self.payload[claim] = datetime_to_epo...
Checks whether a timestamp value in the given claim has passed ( since the given datetime value in current_time ). Raises a TokenError with a user - facing error message if so.
def check_exp(self, claim='exp', current_time=None): """ Checks whether a timestamp value in the given claim has passed (since the given datetime value in `current_time`). Raises a TokenError with a user-facing error message if so. """ if current_time is None: ...
Returns an authorization token for the given user that will be provided after authenticating the user s credentials.
def for_user(cls, user): """ Returns an authorization token for the given user that will be provided after authenticating the user's credentials. """ user_id = getattr(user, api_settings.USER_ID_FIELD) if not isinstance(user_id, int): user_id = str(user_id) ...
Returns an access token created from this refresh token. Copies all claims present in this refresh token to the new access token except those claims listed in the no_copy_claims attribute.
def access_token(self): """ Returns an access token created from this refresh token. Copies all claims present in this refresh token to the new access token except those claims listed in the `no_copy_claims` attribute. """ access = AccessToken() # Use instantiat...
Returns an encoded token for the given payload dictionary.
def encode(self, payload): """ Returns an encoded token for the given payload dictionary. """ token = jwt.encode(payload, self.signing_key, algorithm=self.algorithm) return token.decode('utf-8')
Performs a validation of the given token and returns its payload dictionary.
def decode(self, token, verify=True): """ Performs a validation of the given token and returns its payload dictionary. Raises a `TokenBackendError` if the token is malformed, if its signature check fails, or if its 'exp' claim indicates it has expired. """ try: ...
Extracts the header containing the JSON web token from the given request.
def get_header(self, request): """ Extracts the header containing the JSON web token from the given request. """ header = request.META.get('HTTP_AUTHORIZATION') if isinstance(header, str): # Work around django test client oddness header = header.e...
Extracts an unvalidated JSON web token from the given Authorization header value.
def get_raw_token(self, header): """ Extracts an unvalidated JSON web token from the given "Authorization" header value. """ parts = header.split() if len(parts) == 0: # Empty AUTHORIZATION header sent return None if parts[0] not in AUTH_...
Validates an encoded JSON web token and returns a validated token wrapper object.
def get_validated_token(self, raw_token): """ Validates an encoded JSON web token and returns a validated token wrapper object. """ messages = [] for AuthToken in api_settings.AUTH_TOKEN_CLASSES: try: return AuthToken(raw_token) exc...
Attempts to find and return a user using the given validated token.
def get_user(self, validated_token): """ Attempts to find and return a user using the given validated token. """ try: user_id = validated_token[api_settings.USER_ID_CLAIM] except KeyError: raise InvalidToken(_('Token contained no recognizable user identifi...
Returns a stateless user object which is backed by the given validated token.
def get_user(self, validated_token): """ Returns a stateless user object which is backed by the given validated token. """ if api_settings.USER_ID_CLAIM not in validated_token: # The TokenUser class assumes tokens will have a recognizable user # identifier...
Native width of this image calculated from its width in pixels and horizontal dots per inch ( dpi ).
def default_cx(self): """ Native width of this image, calculated from its width in pixels and horizontal dots per inch (dpi). """ px_width = self.image.px_width horz_dpi = self.image.horz_dpi width_in_inches = px_width / horz_dpi return Inches(width_in_inc...
Native height of this image calculated from its height in pixels and vertical dots per inch ( dpi ).
def default_cy(self): """ Native height of this image, calculated from its height in pixels and vertical dots per inch (dpi). """ px_height = self.image.px_height horz_dpi = self.image.horz_dpi height_in_emu = 914400 * px_height / horz_dpi return Emu(heigh...
Filename from which this image part was originally created. A generic name e. g. image. png is substituted if no name is available for example when the image was loaded from an unnamed stream. In that case a default extension is applied based on the detected MIME type of the image.
def filename(self): """ Filename from which this image part was originally created. A generic name, e.g. 'image.png', is substituted if no name is available, for example when the image was loaded from an unnamed stream. In that case a default extension is applied based on the det...
Return an |ImagePart| instance newly created from * image * and assigned * partname *.
def from_image(cls, image, partname): """ Return an |ImagePart| instance newly created from *image* and assigned *partname*. """ return ImagePart(partname, image.content_type, image.blob, image)
Called by docx. opc. package. PartFactory to load an image part from a package being opened by Document (... ) call.
def load(cls, partname, content_type, blob, package): """ Called by ``docx.opc.package.PartFactory`` to load an image part from a package being opened by ``Document(...)`` call. """ return cls(partname, content_type, blob)
Add a new tab stop at * position * a |Length| object specifying the location of the tab stop relative to the paragraph edge. A negative * position * value is valid and appears in hanging indentation. Tab alignment defaults to left but may be specified by passing a member of the: ref: WdTabAlignment enumeration as * ali...
def add_tab_stop(self, position, alignment=WD_TAB_ALIGNMENT.LEFT, leader=WD_TAB_LEADER.SPACES): """ Add a new tab stop at *position*, a |Length| object specifying the location of the tab stop relative to the paragraph edge. A negative *position* value is valid and ap...
Set val attribute of <w: rStyle > child element to * style * adding a new element if necessary. If * style * is |None| remove the <w: rStyle > element if present.
def style(self, style): """ Set val attribute of <w:rStyle> child element to *style*, adding a new element if necessary. If *style* is |None|, remove the <w:rStyle> element if present. """ if style is None: self._remove_rStyle() elif self.rStyle is Non...
|True| if w: vertAlign/
def subscript(self): """ |True| if `w:vertAlign/@w:val` is 'subscript'. |False| if `w:vertAlign/@w:val` contains any other value. |None| if `w:vertAlign` is not present. """ vertAlign = self.vertAlign if vertAlign is None: return None if vertAl...
|True| if w: vertAlign/
def superscript(self): """ |True| if `w:vertAlign/@w:val` is 'superscript'. |False| if `w:vertAlign/@w:val` contains any other value. |None| if `w:vertAlign` is not present. """ vertAlign = self.vertAlign if vertAlign is None: return None if ve...
Return the value of the boolean child element having * name * e. g. b i and smallCaps.
def _get_bool_val(self, name): """ Return the value of the boolean child element having *name*, e.g. 'b', 'i', and 'smallCaps'. """ element = getattr(self, name) if element is None: return None return element.val
The underline type corresponding to the w: val attribute value.
def val(self): """ The underline type corresponding to the ``w:val`` attribute value. """ val = self.get(qn('w:val')) underline = WD_UNDERLINE.from_xml(val) if underline == WD_UNDERLINE.SINGLE: return True if underline == WD_UNDERLINE.NONE: ...
Return newly created footer part.
def new(cls, package): """Return newly created footer part.""" partname = package.next_partname("/word/footer%d.xml") content_type = CT.WML_FOOTER element = parse_xml(cls._default_footer_xml()) return cls(partname, content_type, element, package)
Return newly created header part.
def new(cls, package): """Return newly created header part.""" partname = package.next_partname("/word/header%d.xml") content_type = CT.WML_HEADER element = parse_xml(cls._default_header_xml()) return cls(partname, content_type, element, package)
Return a newly created styles part containing a default set of elements.
def default(cls, package): """ Return a newly created styles part, containing a default set of elements. """ partname = PackURI('/word/styles.xml') content_type = CT.WML_STYLES element = parse_xml(cls._default_styles_xml()) return cls(partname, content_typ...
Return a bytestream containing XML for a default styles part.
def _default_styles_xml(cls): """ Return a bytestream containing XML for a default styles part. """ path = os.path.join( os.path.split(__file__)[0], '..', 'templates', 'default-styles.xml' ) with open(path, 'rb') as f: xml_bytes = f.rea...
Return newly added CT_HdrFtrRef element of * type_ * with * rId *.
def add_footerReference(self, type_, rId): """Return newly added CT_HdrFtrRef element of *type_* with *rId*. The element tag is `w:footerReference`. """ footerReference = self._add_footerReference() footerReference.type_ = type_ footerReference.rId = rId return f...
Return newly added CT_HdrFtrRef element of * type_ * with * rId *.
def add_headerReference(self, type_, rId): """Return newly added CT_HdrFtrRef element of *type_* with *rId*. The element tag is `w:headerReference`. """ headerReference = self._add_headerReference() headerReference.type_ = type_ headerReference.rId = rId return h...
Return footerReference element of * type_ * or None if not present.
def get_footerReference(self, type_): """Return footerReference element of *type_* or None if not present.""" path = "./w:footerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_) footerReferences = self.xpath(path) if not footerReferences: return None return fo...
Return headerReference element of * type_ * or None if not present.
def get_headerReference(self, type_): """Return headerReference element of *type_* or None if not present.""" matching_headerReferences = self.xpath( "./w:headerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_) ) if len(matching_headerReferences) == 0: ret...
The member of the WD_ORIENTATION enumeration corresponding to the value of the orient attribute of the <w: pgSz > child element or WD_ORIENTATION. PORTRAIT if not present.
def orientation(self): """ The member of the ``WD_ORIENTATION`` enumeration corresponding to the value of the ``orient`` attribute of the ``<w:pgSz>`` child element, or ``WD_ORIENTATION.PORTRAIT`` if not present. """ pgSz = self.pgSz if pgSz is None: r...
Return rId of w: footerReference child of * type_ * after removing it.
def remove_footerReference(self, type_): """Return rId of w:footerReference child of *type_* after removing it.""" footerReference = self.get_footerReference(type_) rId = footerReference.rId self.remove(footerReference) return rId
Return rId of w: headerReference child of * type_ * after removing it.
def remove_headerReference(self, type_): """Return rId of w:headerReference child of *type_* after removing it.""" headerReference = self.get_headerReference(type_) rId = headerReference.rId self.remove(headerReference) return rId
The member of the WD_SECTION_START enumeration corresponding to the value of the val attribute of the <w: type > child element or WD_SECTION_START. NEW_PAGE if not present.
def start_type(self): """ The member of the ``WD_SECTION_START`` enumeration corresponding to the value of the ``val`` attribute of the ``<w:type>`` child element, or ``WD_SECTION_START.NEW_PAGE`` if not present. """ type = self.type if type is None or type.val is...
Return the boolean value of the attribute having * attr_name * or |False| if not present.
def bool_prop(self, attr_name): """ Return the boolean value of the attribute having *attr_name*, or |False| if not present. """ value = getattr(self, attr_name) if value is None: return False return value
Sibling CT_Style element this style is based on or |None| if no base style or base style not found.
def base_style(self): """ Sibling CT_Style element this style is based on or |None| if no base style or base style not found. """ basedOn = self.basedOn if basedOn is None: return None styles = self.getparent() base_style = styles.get_by_id(bas...
Sibling CT_Style element identified by the value of w: name/
def next_style(self): """ Sibling CT_Style element identified by the value of `w:name/@w:val` or |None| if no value is present or no style with that style id is found. """ next = self.next if next is None: return None styles = self.getparent() ...
Return a newly added w: style element having * name * and * style_type *. w: style/
def add_style_of_type(self, name, style_type, builtin): """ Return a newly added `w:style` element having *name* and *style_type*. `w:style/@customStyle` is set based on the value of *builtin*. """ style = self.add_style() style.type = style_type style.cus...
Return w: style [
def default_for(self, style_type): """ Return `w:style[@w:type="*{style_type}*][-1]` or |None| if not found. """ default_styles_for_type = [ s for s in self._iter_styles() if s.type == style_type and s.default ] if not default_styles_for_type: ...
Add a break element of * break_type * to this run. * break_type * can take the values WD_BREAK. LINE WD_BREAK. PAGE and WD_BREAK. COLUMN where WD_BREAK is imported from docx. enum. text. * break_type * defaults to WD_BREAK. LINE.
def add_break(self, break_type=WD_BREAK.LINE): """ Add a break element of *break_type* to this run. *break_type* can take the values `WD_BREAK.LINE`, `WD_BREAK.PAGE`, and `WD_BREAK.COLUMN` where `WD_BREAK` is imported from `docx.enum.text`. *break_type* defaults to `WD_BREAK.LINE...
Return an |InlineShape| instance containing the image identified by * image_path_or_stream * added to the end of this run. * image_path_or_stream * can be a path ( a string ) or a file - like object containing a binary image. If neither width nor height is specified the picture appears at its native size. If only one i...
def add_picture(self, image_path_or_stream, width=None, height=None): """ Return an |InlineShape| instance containing the image identified by *image_path_or_stream*, added to the end of this run. *image_path_or_stream* can be a path (a string) or a file-like object containing a b...
Returns a newly appended |_Text| object ( corresponding to a new <w: t > child element ) to the run containing * text *. Compare with the possibly more friendly approach of assigning text to the: attr: Run. text property.
def add_text(self, text): """ Returns a newly appended |_Text| object (corresponding to a new ``<w:t>`` child element) to the run, containing *text*. Compare with the possibly more friendly approach of assigning text to the :attr:`Run.text` property. """ t = self....
Read/ write. A |_CharacterStyle| object representing the character style applied to this run. The default character style for the document ( often Default Character Font ) is returned if the run has no directly - applied character style. Setting this property to |None| removes any directly - applied character style.
def style(self): """ Read/write. A |_CharacterStyle| object representing the character style applied to this run. The default character style for the document (often `Default Character Font`) is returned if the run has no directly-applied character style. Setting this property to...
A |Length| value calculated from the values of w: ind/
def first_line_indent(self): """ A |Length| value calculated from the values of `w:ind/@w:firstLine` and `w:ind/@w:hanging`. Returns |None| if the `w:ind` child is not present. """ ind = self.ind if ind is None: return None hanging = ind.hangin...
The value of w: spacing/
def spacing_lineRule(self): """ The value of `w:spacing/@w:lineRule` as a member of the :ref:`WdLineSpacing` enumeration. Only the `MULTIPLE`, `EXACTLY`, and `AT_LEAST` members are used. It is the responsibility of the client to calculate the use of `SINGLE`, `DOUBLE`, and `MULTI...
Set val attribute of <w: pStyle > child element to * style * adding a new element if necessary. If * style * is |None| remove the <w: pStyle > element if present.
def style(self, style): """ Set val attribute of <w:pStyle> child element to *style*, adding a new element if necessary. If *style* is |None|, remove the <w:pStyle> element if present. """ if style is None: self._remove_pStyle() return pSty...