code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return self.call( 'catalog_product.info', [ product, store_view, attributes, identifierType ] )
def info(self, product, store_view=None, attributes=None, identifierType=None)
Retrieve product data :param product: ID or SKU of product :param store_view: ID or Code of store view :param attributes: List of fields required :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. ...
5.01403
6.589958
0.760859
return int(self.call( 'catalog_product.create', [product_type, attribute_set_id, sku, data] ) )
def create(self, product_type, attribute_set_id, sku, data)
Create Product and return ID :param product_type: String type of product :param attribute_set_id: ID of attribute set :param sku: SKU of the product :param data: Dictionary of data :return: INT id of product created
4.639174
5.674157
0.817597
return bool(self.call( 'catalog_product.update', [product, data, store_view, identifierType] ))
def update(self, product, data, store_view=None, identifierType=None)
Update product Information :param product: ID or SKU of product :param data: Dictionary of attributes to update :param store_view: ID or Code of store view :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter...
6.054215
6.2582
0.967405
return bool(self.call( 'catalog_product.setSpecialPrice', [ product, special_price, from_date, to_date, store_view, identifierType ] ))
def setSpecialPrice(self, product, special_price=None, from_date=None, to_date=None, store_view=None, identifierType=None)
Update product's special price :param product: ID or SKU of product :param special_price: Special Price :param from_date: From date :param to_date: To Date :param store_view: ID or Code of Store View :param identifierType: Defines whether the product or SKU value is ...
3.465627
3.820776
0.907048
return self.call( 'catalog_product.getSpecialPrice', [ product, store_view, identifierType ] )
def getSpecialPrice(self, product, store_view=None, identifierType=None)
Get product special price data :param product: ID or SKU of product :param store_view: ID or Code of Store view :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: Dictionary
5.28761
7.609836
0.694839
return self.call('catalog_product_attribute_media.list', [product, store_view, identifierType])
def list(self, product, store_view=None, identifierType=None)
Retrieve product image list :param product: ID or SKU of product :param store_view: Code or ID of store view :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: `list` of `dict`
10.999932
13.860537
0.793615
return self.call('catalog_product_attribute_media.info', [product, image_file, store_view, identifierType])
def info(self, product, image_file, store_view=None, identifierType=None)
Retrieve product image data :param product: ID or SKU of product :param store_view: ID or Code of store view :param attributes: List of fields required :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. ...
7.796736
10.452019
0.745955
return self.call('catalog_product_attribute_media.create', [product, data, store_view, identifierType])
def create(self, product, data, store_view=None, identifierType=None)
Upload a new product image. :param product: ID or SKU of product :param data: `dict` of image data (label, position, exclude, types) Example: { 'label': 'description of photo', 'position': '1', 'exclude': '0', 'types': ['image', 'small_image', 'thumbnail']} ...
9.33395
10.356341
0.901279
return self.call('catalog_product_attribute_media.update', [product, img_file_name, data, store_view, identifierType])
def update(self, product, img_file_name, data, store_view=None, identifierType=None)
Update a product image. :param product: ID or SKU of product :param img_file_name: The image file name Example: '/m/y/my_image_thumb.jpg' :param data: `dict` of image data (label, position, exclude, types) Example: { 'label': 'description of photo', 'posi...
6.377679
7.252177
0.879416
return self.call('catalog_product_attribute_media.remove', [product, img_file_name, identifierType])
def remove(self, product, img_file_name, identifierType=None)
Remove a product image. :param product: ID or SKU of product :param img_file_name: The image file name Example: '/m/y/my_image_thumb.jpg' :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :re...
9.393627
10.609179
0.885424
return self.call('catalog_product_link.list', [link_type, product, identifierType])
def list(self, link_type, product, identifierType=None)
Retrieve list of linked products :param link_type: type of link, one of 'cross_sell', 'up_sell', 'related' or 'grouped' :param product: ID or SKU of product :param identifierType: Defines whether the product or SKU value is passed in the "product" ...
7.133588
10.573378
0.674675
return bool(self.call('catalog_product_link.assign', [link_type, product, linked_product, data, identifierType]))
def assign(self, link_type, product, linked_product, data=None, identifierType=None)
Assign a product link :param link_type: type of link, one of 'cross_sell', 'up_sell', 'related' or 'grouped' :param product: ID or SKU of product :param linked_product: ID or SKU of linked product :param data: dictionary of link data, (position, qty, etc.) ...
5.608674
5.996219
0.935368
return bool(self.call('catalog_product_link.remove', [link_type, product, linked_product, identifierType]))
def remove(self, link_type, product, linked_product, identifierType=None)
Remove a product link :param link_type: type of link, one of 'cross_sell', 'up_sell', 'related' or 'grouped' :param product: ID or SKU of product :param linked_product: ID or SKU of linked product to unlink :param identifierType: Defines whether the product or SKU value ...
6.107521
6.518836
0.936903
return bool(self.call('ol_catalog_product_link.assign', [product, linked_products, attributes]))
def update(self, product, linked_products, attributes)
Configurable Update product :param product: ID or SKU of product :param linked_products: List ID or SKU of linked product to link :param attributes: dicc :return: True/False
18.547085
19.862375
0.93378
return self.call('cart.order', [quote_id, store_view, license_id])
def order(self, quote_id, store_view=None, license_id=None)
Allows you to create an order from a shopping cart (quote). Before placing the order, you need to add the customer, customer address, shipping and payment methods. :param quote_id: Shopping cart ID (quote ID) :param store_view: Store view ID or code :param license_id: Website li...
5.077804
5.104737
0.994724
return bool( self.call('cart_coupon.add', [quote_id, coupon_code, store_view]) )
def add(self, quote_id, coupon_code, store_view=None)
Add a coupon code to a quote. :param quote_id: Shopping cart ID (quote ID) :param coupon_code, string, Coupon code :param store_view: Store view ID or code :return: boolean, True if the coupon code is added
6.15167
5.850275
1.051518
return bool( self.call('cart_customer.addresses', [quote_id, address_data, store_view]) )
def addresses(self, quote_id, address_data, store_view=None)
Add customer information into a shopping cart :param quote_id: Shopping cart ID (quote ID) :param address_data, list of dicts of address details, example [ { 'mode': 'billing', 'address_id': 'customer_address_id' }, ...
10.441124
8.326093
1.254024
return bool( self.call('cart_customer.set', [quote_id, customer_data, store_view]) )
def set(self, quote_id, customer_data, store_view=None)
Add customer information into a shopping cart :param quote_id: Shopping cart ID (quote ID) :param customer_data, dict of customer details, example { 'firstname': 'testFirstname', 'lastname': 'testLastName', 'email': 'testEmail', ...
7.378323
7.4726
0.987384
return bool( self.call('cart_payment.method', [quote_id, payment_data, store_view]) )
def method(self, quote_id, payment_data, store_view=None)
Allows you to set a payment method for a shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param payment_data, dict of payment details, example { 'po_number': '', 'method': 'checkmo', 'cc_cid': '', 'cc_owner'...
7.357656
5.893164
1.248507
return bool( self.call('cart_product.add', [quote_id, product_data, store_view]) )
def add(self, quote_id, product_data, store_view=None)
Allows you to add one or more products to the shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, example [ { 'product_id': 1, 'qty': 2, 'option...
6.685844
5.538695
1.207115
return bool( self.call('cart_product.moveToCustomerQuote', [quote_id, product_data, store_view]) )
def move_to_customer_quote(self, quote_id, product_data, store_view=None)
Allows you to move products from the current quote to a customer quote. :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, example [ { 'product_id': 1, 'qty': 2, 'opt...
7.473075
6.770743
1.10373
return bool( self.call('cart_product.remove', [quote_id, product_data, store_view]) )
def remove(self, quote_id, product_data, store_view=None)
Allows you to remove one or several products from a shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, see def add() :param store_view: Store view ID or code :return: boolean, True if the product is removed
7.596895
6.954369
1.092392
return bool( self.call('cart_product.update', [quote_id, product_data, store_view]) )
def update(self, quote_id, product_data, store_view=None)
Allows you to update one or several products in the shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, see def add() :param store_view: Store view ID or code :return: boolean, True if the product is updated ...
7.892707
6.304112
1.251993
return bool( self.call('cart_shipping.method', [quote_id, shipping_method, store_view]) )
def method(self, quote_id, shipping_method, store_view=None)
Allows you to set a shipping method for a shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param shipping_method, string, shipping method code :param store_view: Store view ID or code :return: boolean, True if the shipping method is set
7.158611
6.610461
1.082922
OUTPUT_DIR.mkdir(parents=True, exist_ok=True) with ROOT.joinpath('Pipfile.lock').open() as f: lockfile = plette.Lockfile.load(f) libdir = OUTPUT_DIR.joinpath('lib') paths = {'purelib': libdir, 'platlib': libdir} sources = lockfile.meta.sources._data maker = distlib.scripts.ScriptM...
def pack(ctx, remove_lib=True)
Build a isolated runnable package.
4.308303
4.208794
1.023643
unprebump(ctx) if bump_release(ctx, type_=type_): return this_version = _read_version() ctx.run('towncrier') ctx.run(f'git commit -am "Release {this_version}"') ctx.run(f'git tag -fa {this_version} -m "Version {this_version}"') if repo: if upload(ctx, repo=repo): ...
def release(ctx, type_, repo=None, prebump_to=PREBUMP)
Make a new release.
4.017614
3.845199
1.044839
multiprocess_on = 'prometheus_multiproc_dir' in os.environ get_endpoint = endpoint.fn_by_type(endpoint_type, get_endpoint_fn) memcollect_enabled = mmc_period_sec is not None @app.listener('before_server_start') def before_start(app, loop): metrics.init( latency_buckets, mul...
def monitor(app, endpoint_type='url:1', get_endpoint_fn=None, latency_buckets=None, mmc_period_sec=30, multiprocess_mode='all')
Regiesters a bunch of metrics for Sanic server (request latency, count, etc) and exposes /metrics endpoint to allow Prometheus to scrape them out. :param app: an instance of sanic.app :param endpoint_type: All request related metrics have a label called 'endpoint'. It can be fe...
2.489657
2.562647
0.971517
@self._app.route('/metrics', methods=['GET']) async def expose_metrics(request): return raw(self._get_metrics_data(), content_type=CONTENT_TYPE_LATEST)
def expose_endpoint(self)
Expose /metrics endpoint on the same Sanic server. This may be useful if Sanic is launched from a container and you do not want to expose more than one port for some reason.
5.511608
4.176765
1.319588
if self._multiprocess_on: raise SanicPrometheusError( "start_server can not be used when multiprocessing " + "is turned on") start_http_server(addr=addr, port=port)
def start_server(self, addr='', port=8000)
Expose /metrics endpoint on a new server that will be launched on `<addr>:<port>`. This may be useful if you want to restrict access to metrics data with firewall rules. NOTE: can not be used in multiprocessing mode
8.635295
7.224128
1.195341
config = default_config() if config is None else config config = remove_node_attributes(config, "converters") feed = load_feed(inpath, view, config) return write_feed_dangerously(feed, outpath)
def extract_feed( inpath: str, outpath: str, view: View, config: nx.DiGraph = None ) -> str
Extract a subset of a GTFS zip into a new file
6.977171
6.248333
1.116645
nodes = DEFAULT_NODES if nodes is None else nodes try: tmpdir = tempfile.mkdtemp() def write_node(node): df = feed.get(node) if not df.empty: path = os.path.join(tmpdir, node) df.to_csv(path, index=False) pool = ThreadPool(le...
def write_feed_dangerously( feed: Feed, outpath: str, nodes: Optional[Collection[str]] = None ) -> str
Naively write a feed to a zipfile This function provides no sanity checks. Use it at your own risk.
2.326432
2.260763
1.029047
feed = load_raw_feed(path) return _busiest_date(feed)
def read_busiest_date(path: str) -> Tuple[datetime.date, FrozenSet[str]]
Find the earliest date with the most trips
9.780842
7.658723
1.277085
feed = load_raw_feed(path) return _busiest_week(feed)
def read_busiest_week(path: str) -> Dict[datetime.date, FrozenSet[str]]
Find the earliest week with the most trips
8.935615
7.520372
1.188188
feed = load_raw_feed(path) return _service_ids_by_date(feed)
def read_service_ids_by_date(path: str) -> Dict[datetime.date, FrozenSet[str]]
Find all service identifiers by date
6.740478
5.482598
1.229431
feed = load_raw_feed(path) return _dates_by_service_ids(feed)
def read_dates_by_service_ids( path: str ) -> Dict[FrozenSet[str], FrozenSet[datetime.date]]
Find dates with identical service
6.806304
6.581982
1.034081
feed = load_raw_feed(path) return _trip_counts_by_date(feed)
def read_trip_counts_by_date(path: str) -> Dict[datetime.date, int]
A useful proxy for busyness
6.230083
5.327878
1.169337
config_ = remove_node_attributes(config, ["converters", "transformations"]) feed_ = Feed(path, view={}, config=config_) for filename, column_filters in view.items(): config_ = reroot_graph(config_, filename) view_ = {filename: column_filters} feed_ = Feed(feed_, view=view_, conf...
def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed
Multi-file feed filtering
7.533021
6.753348
1.11545
view = self._view.get(filename) if view is None: return df for col, values in view.items(): # If applicable, filter this dataframe by the given set of values if col in df.columns: df = df[df[col].isin(setwrap(values))] return...
def _filter(self, filename: str, df: pd.DataFrame) -> pd.DataFrame
Apply view filters
5.971697
4.800539
1.243964
dependencies = [] for _, depf, data in self._config.out_edges(filename, data=True): deps = data.get("dependencies") if deps is None: msg = f"Edge missing `dependencies` attribute: {filename}->{depf}" raise ValueError(msg) depen...
def _prune(self, filename: str, df: pd.DataFrame) -> pd.DataFrame
Depth-first search through the dependency graph and prune dependent DataFrames along the way.
5.991687
5.572057
1.07531
if df.empty: return converters = self._config.nodes.get(filename, {}).get("converters", {}) for col, converter in converters.items(): if col in df.columns: df[col] = converter(df[col])
def _convert_types(self, filename: str, df: pd.DataFrame) -> None
Apply type conversions
3.571562
3.106177
1.149826
G = G.copy() for n, successors in list(nx.bfs_successors(G, source=node)): for s in successors: G.add_edge(s, n, **G.edges[n, s]) G.remove_edge(n, s) return G
def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph
Return a copy of the graph rooted at the given node
2.705387
2.320364
1.165932
return set(map(str, set(flatten([value]))))
def setwrap(value: Any) -> Set[str]
Returns a flattened and stringified set from the given object or iterable. For use in public functions which accept argmuents or kwargs that can be one object or a list of objects.
11.028666
12.661938
0.871009
G = G.copy() for _, data in G.nodes(data=True): for attribute in setwrap(attributes): if attribute in data: del data[attribute] return G
def remove_node_attributes(G: nx.DiGraph, attributes: Union[str, Iterable[str]])
Return a copy of the graph with the given attributes deleted from all nodes.
4.561601
3.894457
1.171306
if not isinstance(topic, string_types): raise TypeError('topic={!r} must be text'.format(topic)) if not isinstance(topic, text_type): topic = topic.decode('ascii') if len(topic) < 1: raise ValueError('invalid empty topic name') if len(topic) > 249: raise ValueError('...
def _coerce_topic(topic)
Ensure that the topic name is text string of a valid length. :param topic: Kafka topic name. Valid characters are in the set ``[a-zA-Z0-9._-]``. :raises ValueError: when the topic name exceeds 249 bytes :raises TypeError: when the topic is not :class:`unicode` or :class:`str`
2.620664
2.483082
1.055408
if not isinstance(consumer_group, string_types): raise TypeError('consumer_group={!r} must be text'.format(consumer_group)) if not isinstance(consumer_group, text_type): consumer_group = consumer_group.decode('utf-8') return consumer_group
def _coerce_consumer_group(consumer_group)
Ensure that the consumer group is a text string. :param consumer_group: :class:`bytes` or :class:`str` instance :raises TypeError: when `consumer_group` is not :class:`bytes` or :class:`str`
2.61937
2.421584
1.081677
if isinstance(client_id, type(u'')): client_id = client_id.encode('utf-8') if not isinstance(client_id, bytes): raise TypeError('{!r} is not a valid consumer group (must be' ' str or bytes)'.format(client_id)) return client_id
def _coerce_client_id(client_id)
Ensure the provided client ID is a byte string. If a text string is provided, it is encoded as UTF-8 bytes. :param client_id: :class:`bytes` or :class:`str` instance
3.194491
3.5425
0.901762
if s is None: return _NULL_SHORT_STRING if not isinstance(s, string_types): raise TypeError('{!r} is not text'.format(s)) return write_short_bytes(s.encode('ascii'))
def write_short_ascii(s)
Encode a Kafka short string which represents text. :param str s: Text string (`str` on Python 3, `str` or `unicode` on Python 2) or ``None``. The string will be ASCII-encoded. :returns: length-prefixed `bytes` :raises: `struct.error` for strings longer than 32767 characters
3.930104
3.967361
0.990609
if b is None: return _NULL_SHORT_STRING if not isinstance(b, bytes): raise TypeError('{!r} is not bytes'.format(b)) elif len(b) > 32767: raise struct.error(len(b)) else: return struct.pack('>h', len(b)) + b
def write_short_bytes(b)
Encode a Kafka short string which contains arbitrary bytes. A short string is limited to 32767 bytes in length by the signed 16-bit length prefix. A length prefix of -1 indicates ``null``, represented as ``None`` in Python. :param bytes b: No more than 32767 bytes, or ``None`` for the null enco...
3.038251
2.379396
1.2769
stripped = line.strip() if stripped and stripped.startswith('#') is False: rexres = self.rex.search(stripped) if rexres: return ' '.join(rexres.group(1).split()) return None
def parse_cron_line(self, line)
Parses crontab line and returns only starting time string Args: line: crontab line Returns: Time part of cron line
4.6601
5.017983
0.92868
if self.node_id != new.node_id: raise ValueError("Broker metadata {!r} doesn't match node_id={}".format(new, self.node_id)) self.node_id = new.node_id self.host = new.host self.port = new.port
def updateMetadata(self, new)
Update the metadata stored for this broker. Future connections made to the broker will use the host and port defined in the new metadata. Any existing connection is not dropped, however. :param new: :clas:`afkak.common.BrokerMetadata` with the same node ID as the ...
3.569987
2.81047
1.270246
if requestId in self.requests: # Id is duplicate to 'in-flight' request. Reject it, as we # won't be able to properly deliver the response(s) # Note that this won't protect against a client calling us # twice with the same ID, but first with expectRespons...
def makeRequest(self, requestId, request, expectResponse=True)
Send a request to our broker via our self.proto KafkaProtocol object. Return a deferred which will fire when the reply matching the requestId comes back from the server, or, if expectResponse is False, then return None instead. If we are not currently connected, then we buffer the reque...
8.27387
7.875789
1.050545
if self.proto: log.debug('%r Disconnecting from %r', self, self.proto.transport.getPeer()) self.proto.transport.loseConnection()
def disconnect(self)
Disconnect from the Kafka broker. This is used to implement disconnection on timeout as a workaround for Kafka connections occasionally getting stuck on the server side under load. Requests are not cancelled, so they will be retried.
4.199959
5.74446
0.731132
log.debug('%r: close() proto=%r connector=%r', self, self.proto, self.connector) assert self._dDown is None self._dDown = Deferred() if self.proto is not None: self.proto.transport.loseConnection() elif self.connector is not None: def connectingF...
def close(self)
Permanently dispose of the broker client. This terminates any outstanding connection and cancels any pending requests.
5.288684
4.984903
1.06094
log.info('%r: Connection closed: %r', self, reason) # Reset our proto so we don't try to send to a down connection self.proto = None # Mark any in-flight requests as unsent. for tReq in self.requests.values(): tReq.sent = False if self._dDown: ...
def _connectionLost(self, reason)
Called when the protocol connection is lost - Log the disconnection. - Mark any outstanding requests as unsent so they will be sent when a new connection is made. - If closing the broker client, mark completion of that process. :param reason: Failure that indicate...
6.821727
6.074126
1.12308
requestId = KafkaCodec.get_response_correlation_id(response) # Protect against responses coming back we didn't expect tReq = self.requests.pop(requestId, None) if tReq is None: # This could happen if we've sent it, are waiting on the response # when it's ...
def handleResponse(self, response)
Handle the response string received by KafkaProtocol. Ok, we've received the response from the broker. Find the requestId in the message, lookup & fire the deferred with the response.
8.154657
7.422463
1.098646
try: tReq.sent = True self.proto.sendString(tReq.data) except Exception as e: log.exception('%r: Failed to send request %r', self, tReq) del self.requests[tReq.id] tReq.d.errback(e) else: if not tReq.expect: ...
def _sendRequest(self, tReq)
Send a single request over our protocol to the Kafka broker.
3.906689
3.83409
1.018935
for tReq in list(self.requests.values()): # must copy, may del if not tReq.sent: self._sendRequest(tReq)
def _sendQueued(self)
Connection just came up, send the unsent requests.
9.075659
6.806087
1.333462
if reason is None: reason = CancelledError() tReq = self.requests.pop(requestId) tReq.d.errback(reason)
def cancelRequest(self, requestId, reason=None, _=None)
Cancel a request: remove it from requests, & errback the deferred. NOTE: Attempts to cancel a request which is no longer tracked (expectResponse == False and already sent, or response already received) will raise KeyError
4.16959
4.042596
1.031414
def tryConnect(): self.connector = d = maybeDeferred(connect) d.addCallback(cbConnect) d.addErrback(ebConnect) def connect(): endpoint = self._endpointFactory(self._reactor, self.host, self.port) log.debug('%r: connecting with %s', se...
def _connect(self)
Connect to the Kafka Broker This routine will repeatedly try to connect to the broker (with backoff according to the retry policy) until it succeeds.
3.755755
3.719113
1.009852
# Initialize all elements of parsed array to empty strings parsed = ['', '', '', '', '', '', ''] if self._expression is None or len(self._expression) == 0: raise MissingFieldException("ExpressionDescriptor.expression") else: expression_parts_temp = self....
def parse(self)
Parses the cron expression string Returns: A 7 part string array, one part for each component of the cron expression (seconds, minutes, etc.) Raises: MissingFieldException: if _expression is empty or None FormatException: if _expression has wrong format
3.059285
2.666146
1.147456
# convert ? to * only for DOM and DOW expression_parts[3] = expression_parts[3].replace("?", "*") expression_parts[5] = expression_parts[5].replace("?", "*") # convert 0/, 1/ to */ if expression_parts[0].startswith("0/"): expression_parts[0] = expression_par...
def normalize_expression(self, expression_parts)
Converts cron expression components into consistent, predictable formats. Args: expression_parts: A 7 part string array, one part for each component of the cron expression Returns: None
2.591894
2.473533
1.047851
groups = {} for env in envlist: envpy, category = env.split('-')[0:2] if category == 'lint': category = 'unit' try: groups[envpy, category].append(env) except KeyError: groups[envpy, category] = [env] return sorted((envpy, category,...
def group_envs(envlist)
Group Tox environments for Travis CI builds Separate by Python version so that they can go in different Travis jobs: >>> group_envs('py37-int-snappy', 'py36-int') [('py36', 'int', ['py36-int']), ('py37', 'int', ['py37-int-snappy'])] Group unit tests and linting together: >>> group_envs(['py27-un...
3.404204
3.193506
1.065977
assert payload is None or isinstance(payload, bytes), 'payload={!r} should be bytes or None'.format(payload) assert key is None or isinstance(key, bytes), 'key={!r} should be bytes or None'.format(key) return Message(0, 0, key, payload)
def create_message(payload, key=None)
Construct a :class:`Message` :param payload: The payload to send to Kafka. :type payload: :class:`bytes` or ``None`` :param key: A key used to route the message when partitioning and to determine message identity on a compacted topic. :type key: :class:`bytes` or ``None``
2.641251
2.614716
1.010148
encoded_message_set = KafkaCodec._encode_message_set(message_set) gzipped = gzip_encode(encoded_message_set) return Message(0, CODEC_GZIP, None, gzipped)
def create_gzip_message(message_set)
Construct a gzip-compressed message containing multiple messages The given messages will be encoded, compressed, and sent as a single atomic message to Kafka. :param list message_set: a list of :class:`Message` instances
5.856966
7.939695
0.737681
encoded_message_set = KafkaCodec._encode_message_set(message_set) snapped = snappy_encode(encoded_message_set) return Message(0, CODEC_SNAPPY, None, snapped)
def create_snappy_message(message_set)
Construct a Snappy-compressed message containing multiple messages The given messages will be encoded, compressed, and sent as a single atomic message to Kafka. :param list message_set: a list of :class:`Message` instances
5.748192
7.731673
0.74346
msglist = [] for req in requests: msglist.extend([create_message(m, key=req.key) for m in req.messages]) if codec == CODEC_NONE: return msglist elif codec == CODEC_GZIP: return [create_gzip_message(msglist)] elif codec == CODEC_SNAPPY: return [create_snappy_mess...
def create_message_set(requests, codec=CODEC_NONE)
Create a message set from a list of requests. Each request can have a list of messages and its own key. If codec is :data:`CODEC_NONE`, return a list of raw Kafka messages. Otherwise, return a list containing a single codec-encoded message. :param codec: The encoding for the message set, one ...
2.776436
2.511333
1.105563
return (struct.pack('>hhih', request_key, # ApiKey api_version, # ApiVersion correlation_id, # CorrelationId len(client_id)) + # ClientId size clie...
def _encode_message_header(cls, client_id, correlation_id, request_key, api_version=0)
Encode the common request envelope
4.293044
4.468029
0.960836
message_set = [] incr = 1 if offset is None: incr = 0 offset = 0 for message in messages: encoded_message = KafkaCodec._encode_message(message) message_set.append(struct.pack('>qi', offset, len(encoded_message))) messag...
def _encode_message_set(cls, messages, offset=None)
Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed. Format:: MessageSet => [Offset MessageSize Message] Offset => int64 MessageSize => int32
2.584138
2.637895
0.979621
if message.magic == 0: msg = struct.pack('>BB', message.magic, message.attributes) msg += write_int_string(message.key) msg += write_int_string(message.value) crc = zlib.crc32(msg) & 0xffffffff # Ensure unsigned msg = struct.pack('>I', crc) +...
def _encode_message(cls, message)
Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero. Format:: Message => Crc MagicByte Attributes Key Value Crc => int32 MagicByte => int8 Attributes => int8 ...
3.566777
2.890489
1.23397
if not isinstance(client_id, bytes): raise TypeError('client_id={!r} should be bytes'.format(client_id)) payloads = [] if payloads is None else payloads grouped_payloads = group_by_topic_and_partition(payloads) message = cls._encode_message_header(client_id, correla...
def encode_produce_request(cls, client_id, correlation_id, payloads=None, acks=1, timeout=DEFAULT_REPLICAS_ACK_TIMEOUT_MSECS)
Encode some ProduceRequest structs :param bytes client_id: :param int correlation_id: :param list payloads: list of ProduceRequest :param int acks: How "acky" you want the request to be: 0: immediate response 1: written to disk by the leader ...
2.569501
2.662502
0.96507
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _i in range(num_topics): topic, cur = read_short_ascii(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _i in range(num_partitions): ((partiti...
def decode_produce_response(cls, data)
Decode bytes to a ProduceResponse :param bytes data: bytes to decode :returns: iterable of `afkak.common.ProduceResponse`
4.672907
5.769955
0.809869
payloads = [] if payloads is None else payloads grouped_payloads = group_by_topic_and_partition(payloads) message = cls._encode_message_header(client_id, correlation_id, KafkaCodec.FETCH_KEY) assert isinstance(max_wait_time, int) ...
def encode_fetch_request(cls, client_id, correlation_id, payloads=None, max_wait_time=100, min_bytes=4096)
Encodes some FetchRequest structs :param bytes client_id: :param int correlation_id: :param list payloads: list of :class:`FetchRequest` :param int max_wait_time: how long to block waiting on min_bytes of data :param int min_bytes: the minimum number of bytes to accu...
2.793742
3.033584
0.920938
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _i in range(num_topics): (topic, cur) = read_short_ascii(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _i in range(num_partitions): ((part...
def decode_fetch_response(cls, data)
Decode bytes to a FetchResponse :param bytes data: bytes to decode
4.35095
4.813543
0.903898
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _i in range(num_topics): (topic, cur) = read_short_ascii(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _i in range(num_partitions): ((part...
def decode_offset_response(cls, data)
Decode bytes to an :class:`OffsetResponse` :param bytes data: bytes to decode
3.412886
3.826957
0.891801
topics = [] if topics is None else topics message = [ cls._encode_message_header(client_id, correlation_id, KafkaCodec.METADATA_KEY), struct.pack('>i', len(topics)), ] for topic in topics: message.append(...
def encode_metadata_request(cls, client_id, correlation_id, topics=None)
Encode a MetadataRequest :param bytes client_id: string :param int correlation_id: int :param list topics: list of text
3.474553
4.326398
0.803105
((correlation_id, numbrokers), cur) = relative_unpack('>ii', data, 0) # In testing, I saw this routine swap my machine to death when # passed bad data. So, some checks are in order... if numbrokers > MAX_BROKERS: raise InvalidMessageError( "Brokers:{...
def decode_metadata_response(cls, data)
Decode bytes to a MetadataResponse :param bytes data: bytes to decode
3.12097
3.249887
0.960332
message = cls._encode_message_header(client_id, correlation_id, KafkaCodec.CONSUMER_METADATA_KEY) message += write_short_ascii(consumer_group) return message
def encode_consumermetadata_request(cls, client_id, correlation_id, consumer_group)
Encode a ConsumerMetadataRequest :param bytes client_id: string :param int correlation_id: int :param str consumer_group: string
4.773335
5.930751
0.804845
(correlation_id, error_code, node_id), cur = \ relative_unpack('>ihi', data, 0) host, cur = read_short_ascii(data, cur) (port,), cur = relative_unpack('>i', data, cur) return ConsumerMetadataResponse( error_code, node_id, nativeString(host), port)
def decode_consumermetadata_response(cls, data)
Decode bytes to a ConsumerMetadataResponse :param bytes data: bytes to decode
8.340233
9.361812
0.890878
grouped_payloads = group_by_topic_and_partition(payloads) message = cls._encode_message_header( client_id, correlation_id, KafkaCodec.OFFSET_COMMIT_KEY, api_version=1, ) message += write_short_ascii(group) message += struct.pack('>i', group_gene...
def encode_offset_commit_request(cls, client_id, correlation_id, group, group_generation_id, consumer_id, payloads)
Encode some OffsetCommitRequest structs (v1) :param bytes client_id: string :param int correlation_id: int :param str group: the consumer group to which you are committing offsets :param int group_generation_id: int32, generation ID of the group :param str consumer_id: string, I...
2.283389
2.377011
0.960613
((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _i in range(num_topics): (topic, cur) = read_short_ascii(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for...
def decode_offset_commit_response(cls, data)
Decode bytes to an OffsetCommitResponse :param bytes data: bytes to decode
3.733146
3.811596
0.979418
grouped_payloads = group_by_topic_and_partition(payloads) message = cls._encode_message_header( client_id, correlation_id, KafkaCodec.OFFSET_FETCH_KEY, api_version=1) message += write_short_ascii(group) message += struct.pack('>i', len(grouped_payloads))...
def encode_offset_fetch_request(cls, client_id, correlation_id, group, payloads)
Encode some OffsetFetchRequest structs :param bytes client_id: string :param int correlation_id: int :param bytes group: string, the consumer group you are fetching offsets for :param list payloads: list of :class:`OffsetFetchRequest`
2.613826
2.8535
0.916007
((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _i in range(num_topics): (topic, cur) = read_short_ascii(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) fo...
def decode_offset_fetch_response(cls, data)
Decode bytes to an OffsetFetchResponse :param bytes data: bytes to decode
3.033295
3.096428
0.979611
correlation_id = response[0:4] try: d = self._pending.pop(correlation_id) except KeyError: self._log.warn(( "Response has unknown correlation ID {correlation_id!r}." " Dropping connection to {peer}." ), correlation_id=c...
def stringReceived(self, response)
Handle a response from the broker.
3.91937
3.744676
1.046651
self._failed = reason pending, self._pending = self._pending, None for d in pending.values(): d.errback(reason)
def connectionLost(self, reason=connectionDone)
Mark the protocol as failed and fail all pending operations.
4.260079
3.438394
1.238974
if self._failed is not None: return fail(self._failed) correlation_id = request[4:8] assert correlation_id not in self._pending d = Deferred() self.sendString(request) self._pending[correlation_id] = d return d
def request(self, request)
Send a request to the Kafka broker. :param bytes request: The bytes of a Kafka `RequestMessage`_ structure. It must have a unique (to this connection) correlation ID. :returns: `Deferred` which will: - Succeed with the bytes of a Kafka `ResponseMessag...
5.526374
5.155136
1.072013
try: topic = _coerce_topic(topic) if key is not None and not isinstance(key, bytes): raise TypeError('key={!r} must be bytes or None'.format(key)) if not msgs: raise ValueError("msgs must be a non-empty sequence") msg_cnt...
def send_messages(self, topic, key=None, msgs=())
Given a topic, and optional key (for partitioning) and a list of messages, send them to Kafka, either immediately, or when a batch is ready, depending on the Producer's batch settings. :param str topic: Kafka topic to send the messages to :param str key: Message key used to...
3.775472
3.593455
1.050652
self.stopping = True # Cancel any outstanding request to our client if self._batch_send_d: self._batch_send_d.cancel() # Do we have to worry about our looping call? if self.batch_every_t is not None: # Stop our looping call, and wait for the defer...
def stop(self)
Terminate any outstanding requests. :returns: :class:``Deferred` which fires when fully stopped.
9.628692
8.969017
1.07355
log.warning('_send_timer_failed:%r: %s', fail, fail.getBriefTraceback()) self._sendLooperD = self._sendLooper.start( self.batch_every_t, now=False)
def _send_timer_failed(self, fail)
Our _send_batch() function called by the LoopingCall failed. Some error probably came back from Kafka and _check_error() raised the exception For now, just log the failure and restart the loop
15.795243
10.96596
1.440389
if self._sendLooper is not lCall: log.warning('commitTimerStopped with wrong timer:%s not:%s', lCall, self._sendLooper) else: self._sendLooper = None self._sendLooperD = None
def _send_timer_stopped(self, lCall)
We're shutting down, clean up our looping call...
7.921056
7.369102
1.074901
# check if the client has metadata for the topic while self.client.metadata_error_for_topic(topic): # client doesn't have good metadata for topic. ask to fetch... # check if we have request attempts left if self._req_attempts >= self._max_attempts: ...
def _next_partition(self, topic, key=None)
get the next partition to which to publish Check with our client for the latest partitions for the topic, then ask our partitioner for the next partition to which we should publish for the give key. If needed, create a new partitioner for the topic.
4.661417
4.387506
1.06243
# We use these dictionaries to be able to combine all the messages # destined to the same topic/partition into one request # the messages & deferreds, both by topic+partition reqsByTopicPart = defaultdict(list) payloadsByTopicPart = defaultdict(list) deferredsByT...
def _send_requests(self, parts_results, requests)
Send the requests We've determined the partition for each message group in the batch, or got errors for them.
5.585799
5.348899
1.044289
self._batch_send_d = None self._req_attempts = 0 self._retry_interval = self._init_retry_interval if isinstance(resp, Failure) and not resp.check(tid_CancelledError, CancelledError): log.error("Failure detected ...
def _complete_batch_send(self, resp)
Complete the processing of our batch send operation Clear the deferred tracking our current batch processing and reset our retry count and retry interval Return none to eat any errors coming from up the deferred chain
5.995172
4.612844
1.299669
if ( (self.batch_every_n and self.batch_every_n <= self._waitingMsgCount) or (self.batch_every_b and self.batch_every_b <= self._waitingByteCount) ): self._send_batch() return result
def _check_send_batch(self, result=None)
Check if we have enough messages/bytes to send Since this can be called from the callback chain, we pass through our first (non-self) arg
5.027057
4.589657
1.095301
# We can be triggered by the LoopingCall, and have nothing to send... # Or, we've got SendRequest(s) to send, but are still processing the # previous batch... if (not self._batch_reqs) or self._batch_send_d: return # Save a local copy, and clear the global l...
def _send_batch(self)
Send the waiting messages, if there are any, and we can... This is called by our LoopingCall every send_every_t interval, and from send_messages everytime we have enough messages to send. This is also called from py:method:`send_messages` via py:method:`_check_send_batch` if there are e...
7.48166
7.010306
1.067237
# Is the request in question in an unsent batch? for req in self._batch_reqs: if req.deferred == d: # Found the request, remove it and return. msgs = req.messages self._waitingMsgCount -= len(msgs) for m in (_m for _m i...
def _cancel_send_messages(self, d)
Cancel a `send_messages` request First check if the request is in a waiting batch, of so, great, remove it from the batch. If it's not found, we errback() the deferred and the downstream processing steps take care of aborting further processing. We check if there's a current _bat...
8.075363
6.66129
1.212282
for d in list(self._outstanding): d.addErrback(lambda _: None) # Eat any uncaught errors d.cancel()
def _cancel_outstanding(self)
Cancel all of our outstanding requests
6.724239
5.560425
1.209303
if isinstance(hosts, bytes): hosts = hosts.split(b',') elif isinstance(hosts, _unicode): hosts = hosts.split(u',') result = set() for host_port in hosts: # FIXME This won't handle IPv6 addresses res = nativeString(host_port).split(':') host = res[0].strip() ...
def _normalize_hosts(hosts)
Canonicalize the *hosts* parameter. >>> _normalize_hosts("host,127.0.0.2:2909") [('127.0.0.2', 2909), ('host', 9092)] :param hosts: A list or comma-separated string of hostnames which may also include port numbers. All of the following are valid:: b'host' u'host' ...
3.543647
3.366346
1.052669
groups = tuple(_coerce_consumer_group(g) for g in groups) for group in groups: if group in self.consumer_group_to_brokers: del self.consumer_group_to_brokers[group]
def reset_consumer_group_metadata(self, *groups)
Reset cache of what broker manages the offset for specified groups Remove the cache of what Kafka broker should be contacted when fetching or updating the committed offsets for a given consumer group or groups. NOTE: Does not cancel any outstanding requests for updates to the c...
3.168483
3.736048
0.848084
self.topics_to_brokers.clear() self.topic_partitions.clear() self.topic_errors.clear() self.consumer_group_to_brokers.clear()
def reset_all_metadata(self)
Clear all cached metadata Metadata will be re-fetched as required to satisfy requests.
4.64501
4.692133
0.989957
topic = _coerce_topic(topic) if topic not in self.topic_partitions: return False if not self.topic_partitions[topic]: # Don't consider an empty partition list 'fully replicated' return False return all( self.partition_fully_replica...
def topic_fully_replicated(self, topic)
Determine if the given topic is fully replicated according to the currently known cluster metadata. .. note:: This relies on cached cluster metadata. You may call :meth:`load_metadata_for_topics()` first to refresh this cache. :param str topic: Topic name :ret...
3.579759
4.001128
0.894687