repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
alorence/django-modern-rpc
modernrpc/handlers/base.py
RPCHandler.execute_procedure
def execute_procedure(self, name, args=None, kwargs=None): """ Call the concrete python function corresponding to given RPC Method `name` and return the result. Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class. """ _method = registry.get_method(name, self.entry_point, self.protocol) if not _method: raise RPCUnknownMethod(name) logger.debug('Check authentication / permissions for method {} and user {}' .format(name, self.request.user)) if not _method.check_permissions(self.request): raise AuthenticationFailed(name) logger.debug('RPC method {} will be executed'.format(name)) # Replace default None value with empty instance of corresponding type args = args or [] kwargs = kwargs or {} # If the RPC method needs to access some internals, update kwargs dict if _method.accept_kwargs: kwargs.update({ REQUEST_KEY: self.request, ENTRY_POINT_KEY: self.entry_point, PROTOCOL_KEY: self.protocol, HANDLER_KEY: self, }) if six.PY2: method_std, encoding = _method.str_standardization, _method.str_std_encoding args = modernrpc.compat.standardize_strings(args, strtype=method_std, encoding=encoding) kwargs = modernrpc.compat.standardize_strings(kwargs, strtype=method_std, encoding=encoding) logger.debug('Params: args = {} - kwargs = {}'.format(args, kwargs)) try: # Call the rpc method, as standard python function return _method.function(*args, **kwargs) except TypeError as e: # If given arguments cannot be transmitted properly to python function, # raise an Invalid Params exceptions raise RPCInvalidParams(str(e))
python
def execute_procedure(self, name, args=None, kwargs=None): """ Call the concrete python function corresponding to given RPC Method `name` and return the result. Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class. """ _method = registry.get_method(name, self.entry_point, self.protocol) if not _method: raise RPCUnknownMethod(name) logger.debug('Check authentication / permissions for method {} and user {}' .format(name, self.request.user)) if not _method.check_permissions(self.request): raise AuthenticationFailed(name) logger.debug('RPC method {} will be executed'.format(name)) # Replace default None value with empty instance of corresponding type args = args or [] kwargs = kwargs or {} # If the RPC method needs to access some internals, update kwargs dict if _method.accept_kwargs: kwargs.update({ REQUEST_KEY: self.request, ENTRY_POINT_KEY: self.entry_point, PROTOCOL_KEY: self.protocol, HANDLER_KEY: self, }) if six.PY2: method_std, encoding = _method.str_standardization, _method.str_std_encoding args = modernrpc.compat.standardize_strings(args, strtype=method_std, encoding=encoding) kwargs = modernrpc.compat.standardize_strings(kwargs, strtype=method_std, encoding=encoding) logger.debug('Params: args = {} - kwargs = {}'.format(args, kwargs)) try: # Call the rpc method, as standard python function return _method.function(*args, **kwargs) except TypeError as e: # If given arguments cannot be transmitted properly to python function, # raise an Invalid Params exceptions raise RPCInvalidParams(str(e))
Call the concrete python function corresponding to given RPC Method `name` and return the result. Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class.
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/handlers/base.py#L63-L110
alorence/django-modern-rpc
modernrpc/system_methods.py
__system_listMethods
def __system_listMethods(**kwargs): """Returns a list of all methods available in the current entry point""" entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) return registry.get_all_method_names(entry_point, protocol, sort_methods=True)
python
def __system_listMethods(**kwargs): """Returns a list of all methods available in the current entry point""" entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) return registry.get_all_method_names(entry_point, protocol, sort_methods=True)
Returns a list of all methods available in the current entry point
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/system_methods.py#L7-L12
alorence/django-modern-rpc
modernrpc/system_methods.py
__system_methodSignature
def __system_methodSignature(method_name, **kwargs): """ Returns an array describing the signature of the given method name. The result is an array with: - Return type as first elements - Types of method arguments from element 1 to N :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: An array describing types of return values and method arguments """ entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) method = registry.get_method(method_name, entry_point, protocol) if method is None: raise RPCInvalidParams('Unknown method {}. Unable to retrieve signature.'.format(method_name)) return method.signature
python
def __system_methodSignature(method_name, **kwargs): """ Returns an array describing the signature of the given method name. The result is an array with: - Return type as first elements - Types of method arguments from element 1 to N :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: An array describing types of return values and method arguments """ entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) method = registry.get_method(method_name, entry_point, protocol) if method is None: raise RPCInvalidParams('Unknown method {}. Unable to retrieve signature.'.format(method_name)) return method.signature
Returns an array describing the signature of the given method name. The result is an array with: - Return type as first elements - Types of method arguments from element 1 to N :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: An array describing types of return values and method arguments
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/system_methods.py#L16-L33
alorence/django-modern-rpc
modernrpc/system_methods.py
__system_methodHelp
def __system_methodHelp(method_name, **kwargs): """ Returns the documentation of the given method name. :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: Documentation text for the RPC method """ entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) method = registry.get_method(method_name, entry_point, protocol) if method is None: raise RPCInvalidParams('Unknown method {}. Unable to retrieve its documentation.'.format(method_name)) return method.html_doc
python
def __system_methodHelp(method_name, **kwargs): """ Returns the documentation of the given method name. :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: Documentation text for the RPC method """ entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) method = registry.get_method(method_name, entry_point, protocol) if method is None: raise RPCInvalidParams('Unknown method {}. Unable to retrieve its documentation.'.format(method_name)) return method.html_doc
Returns the documentation of the given method name. :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: Documentation text for the RPC method
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/system_methods.py#L37-L51
alorence/django-modern-rpc
modernrpc/system_methods.py
__system_multiCall
def __system_multiCall(calls, **kwargs): """ Call multiple RPC methods at once. :param calls: An array of struct like {"methodName": string, "params": array } :param kwargs: Internal data :type calls: list :type kwargs: dict :return: """ if not isinstance(calls, list): raise RPCInvalidParams('system.multicall first argument should be a list, {} given.'.format(type(calls))) handler = kwargs.get(HANDLER_KEY) results = [] for call in calls: try: result = handler.execute_procedure(call['methodName'], args=call.get('params')) # From https://mirrors.talideon.com/articles/multicall.html: # "Notice that regular return values are always nested inside a one-element array. This allows you to # return structs from functions without confusing them with faults." results.append([result]) except RPCException as e: results.append({ 'faultCode': e.code, 'faultString': e.message, }) except Exception as e: results.append({ 'faultCode': RPC_INTERNAL_ERROR, 'faultString': str(e), }) return results
python
def __system_multiCall(calls, **kwargs): """ Call multiple RPC methods at once. :param calls: An array of struct like {"methodName": string, "params": array } :param kwargs: Internal data :type calls: list :type kwargs: dict :return: """ if not isinstance(calls, list): raise RPCInvalidParams('system.multicall first argument should be a list, {} given.'.format(type(calls))) handler = kwargs.get(HANDLER_KEY) results = [] for call in calls: try: result = handler.execute_procedure(call['methodName'], args=call.get('params')) # From https://mirrors.talideon.com/articles/multicall.html: # "Notice that regular return values are always nested inside a one-element array. This allows you to # return structs from functions without confusing them with faults." results.append([result]) except RPCException as e: results.append({ 'faultCode': e.code, 'faultString': e.message, }) except Exception as e: results.append({ 'faultCode': RPC_INTERNAL_ERROR, 'faultString': str(e), }) return results
Call multiple RPC methods at once. :param calls: An array of struct like {"methodName": string, "params": array } :param kwargs: Internal data :type calls: list :type kwargs: dict :return:
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/system_methods.py#L55-L92
dcoker/awsmfa
awsmfa/__main__.py
acquire_code
def acquire_code(args, session, session3): """returns the user's token serial number, MFA token code, and an error code.""" serial_number = find_mfa_for_user(args.serial_number, session, session3) if not serial_number: print("There are no MFA devices associated with this user.", file=sys.stderr) return None, None, USER_RECOVERABLE_ERROR token_code = args.token_code if token_code is None: while token_code is None or len(token_code) != 6: token_code = getpass.getpass("MFA Token Code: ") return serial_number, token_code, OK
python
def acquire_code(args, session, session3): """returns the user's token serial number, MFA token code, and an error code.""" serial_number = find_mfa_for_user(args.serial_number, session, session3) if not serial_number: print("There are no MFA devices associated with this user.", file=sys.stderr) return None, None, USER_RECOVERABLE_ERROR token_code = args.token_code if token_code is None: while token_code is None or len(token_code) != 6: token_code = getpass.getpass("MFA Token Code: ") return serial_number, token_code, OK
returns the user's token serial number, MFA token code, and an error code.
https://github.com/dcoker/awsmfa/blob/18a8216bfd3184c78b4067edf5198250f66e003d/awsmfa/__main__.py#L157-L170
dcoker/awsmfa
awsmfa/__main__.py
rotate
def rotate(args, credentials): """rotate the identity profile's AWS access key pair.""" current_access_key_id = credentials.get( args.identity_profile, 'aws_access_key_id') # create new sessions using the MFA credentials session, session3, err = make_session(args.target_profile) if err: return err iam = session3.resource('iam') # find the AccessKey corresponding to the identity profile and delete it. current_access_key = next((key for key in iam.CurrentUser().access_keys.all() if key.access_key_id == current_access_key_id)) current_access_key.delete() # create the new access key pair iam_service = session3.client('iam') new_access_key_pair = iam_service.create_access_key()["AccessKey"] print("Rotating from %s to %s." % (current_access_key.access_key_id, new_access_key_pair['AccessKeyId']), file=sys.stderr) update_credentials_file(args.aws_credentials, args.identity_profile, args.identity_profile, credentials, new_access_key_pair) print("%s profile updated." % args.identity_profile, file=sys.stderr) return OK
python
def rotate(args, credentials): """rotate the identity profile's AWS access key pair.""" current_access_key_id = credentials.get( args.identity_profile, 'aws_access_key_id') # create new sessions using the MFA credentials session, session3, err = make_session(args.target_profile) if err: return err iam = session3.resource('iam') # find the AccessKey corresponding to the identity profile and delete it. current_access_key = next((key for key in iam.CurrentUser().access_keys.all() if key.access_key_id == current_access_key_id)) current_access_key.delete() # create the new access key pair iam_service = session3.client('iam') new_access_key_pair = iam_service.create_access_key()["AccessKey"] print("Rotating from %s to %s." % (current_access_key.access_key_id, new_access_key_pair['AccessKeyId']), file=sys.stderr) update_credentials_file(args.aws_credentials, args.identity_profile, args.identity_profile, credentials, new_access_key_pair) print("%s profile updated." % args.identity_profile, file=sys.stderr) return OK
rotate the identity profile's AWS access key pair.
https://github.com/dcoker/awsmfa/blob/18a8216bfd3184c78b4067edf5198250f66e003d/awsmfa/__main__.py#L180-L211
matiasb/demiurge
demiurge/demiurge.py
BaseField.coerce
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) return value
python
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) return value
Coerce a cleaned value.
https://github.com/matiasb/demiurge/blob/4cfbb24f0519ab99b9bf36fa4c20283ae6e7b9fe/demiurge/demiurge.py#L37-L41
matiasb/demiurge
demiurge/demiurge.py
Item.all_from
def all_from(cls, *args, **kwargs): """Query for items passing PyQuery args explicitly.""" pq_items = cls._get_items(*args, **kwargs) return [cls(item=i) for i in pq_items.items()]
python
def all_from(cls, *args, **kwargs): """Query for items passing PyQuery args explicitly.""" pq_items = cls._get_items(*args, **kwargs) return [cls(item=i) for i in pq_items.items()]
Query for items passing PyQuery args explicitly.
https://github.com/matiasb/demiurge/blob/4cfbb24f0519ab99b9bf36fa4c20283ae6e7b9fe/demiurge/demiurge.py#L234-L237
matiasb/demiurge
demiurge/demiurge.py
Item.one
def one(cls, path='', index=0): """Return ocurrence (the first one, unless specified) of the item.""" url = urljoin(cls._meta.base_url, path) pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs) item = pq_items.eq(index) if not item: raise ItemDoesNotExist("%s not found" % cls.__name__) return cls(item=item)
python
def one(cls, path='', index=0): """Return ocurrence (the first one, unless specified) of the item.""" url = urljoin(cls._meta.base_url, path) pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs) item = pq_items.eq(index) if not item: raise ItemDoesNotExist("%s not found" % cls.__name__) return cls(item=item)
Return ocurrence (the first one, unless specified) of the item.
https://github.com/matiasb/demiurge/blob/4cfbb24f0519ab99b9bf36fa4c20283ae6e7b9fe/demiurge/demiurge.py#L240-L247
matiasb/demiurge
demiurge/demiurge.py
Item.all
def all(cls, path=''): """Return all ocurrences of the item.""" url = urljoin(cls._meta.base_url, path) pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs) return [cls(item=i) for i in pq_items.items()]
python
def all(cls, path=''): """Return all ocurrences of the item.""" url = urljoin(cls._meta.base_url, path) pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs) return [cls(item=i) for i in pq_items.items()]
Return all ocurrences of the item.
https://github.com/matiasb/demiurge/blob/4cfbb24f0519ab99b9bf36fa4c20283ae6e7b9fe/demiurge/demiurge.py#L250-L254
fulfilio/python-magento
magento/customer.py
Customer.info
def info(self, id, attributes=None): """ Retrieve customer data :param id: ID of customer :param attributes: `List` of attributes needed """ if attributes: return self.call('customer.info', [id, attributes]) else: return self.call('customer.info', [id])
python
def info(self, id, attributes=None): """ Retrieve customer data :param id: ID of customer :param attributes: `List` of attributes needed """ if attributes: return self.call('customer.info', [id, attributes]) else: return self.call('customer.info', [id])
Retrieve customer data :param id: ID of customer :param attributes: `List` of attributes needed
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/customer.py#L48-L58
fulfilio/python-magento
magento/sales.py
Order.search
def search(self, filters=None, fields=None, limit=None, page=1): """ Retrieve order list by options using search api. Using this result can be paginated :param options: Dictionary of options. :param filters: `{<attribute>:{<operator>:<value>}}` :param fields: [<String: magento field names>, ...] :param limit: `page limit` :param page: `current page` :return: `list` of `dict` """ options = { 'imported': False, 'filters': filters or {}, 'fields': fields or [], 'limit': limit or 1000, 'page': page, } return self.call('sales_order.search', [options])
python
def search(self, filters=None, fields=None, limit=None, page=1): """ Retrieve order list by options using search api. Using this result can be paginated :param options: Dictionary of options. :param filters: `{<attribute>:{<operator>:<value>}}` :param fields: [<String: magento field names>, ...] :param limit: `page limit` :param page: `current page` :return: `list` of `dict` """ options = { 'imported': False, 'filters': filters or {}, 'fields': fields or [], 'limit': limit or 1000, 'page': page, } return self.call('sales_order.search', [options])
Retrieve order list by options using search api. Using this result can be paginated :param options: Dictionary of options. :param filters: `{<attribute>:{<operator>:<value>}}` :param fields: [<String: magento field names>, ...] :param limit: `page limit` :param page: `current page` :return: `list` of `dict`
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L34-L55
fulfilio/python-magento
magento/sales.py
Order.addcomment
def addcomment(self, order_increment_id, status, comment=None, notify=False): """ Add comment to order or change its state :param order_increment_id: Order ID TODO: Identify possible values for status """ if comment is None: comment = "" return bool(self.call( 'sales_order.addComment', [order_increment_id, status, comment, notify] ) )
python
def addcomment(self, order_increment_id, status, comment=None, notify=False): """ Add comment to order or change its state :param order_increment_id: Order ID TODO: Identify possible values for status """ if comment is None: comment = "" return bool(self.call( 'sales_order.addComment', [order_increment_id, status, comment, notify] ) )
Add comment to order or change its state :param order_increment_id: Order ID TODO: Identify possible values for status
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L78-L92
fulfilio/python-magento
magento/sales.py
CreditMemo.create
def create( self, order_increment_id, creditmemo_data=None, comment=None, email=False, include_comment=False, refund_to_store_credit_amount=None): """ Create new credit_memo for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param creditmemo_data: Sales order credit memo data (optional) :type creditmemo_data: associative array as dict { 'qtys': [ { 'order_item_id': str, # Order item ID to be refunded 'qty': int # Items quantity to be refunded }, ... ], 'shipping_amount': float # refund shipping amount (optional) 'adjustment_positive': float # adjustment refund amount (optional) 'adjustment_negative': float # adjustment fee amount (optional) } :param comment: Credit memo Comment :type comment: str :param email: send e-mail flag (optional) :type email: bool :param include_comment: include comment in e-mail flag (optional) :type include_comment: bool :param refund_to_store_credit_amount: amount to refund to store credit :type refund_to_store_credit_amount: float :return str, increment id of credit memo created """ if comment is None: comment = '' return self.call( 'sales_order_creditmemo.create', [ order_increment_id, creditmemo_data, comment, email, include_comment, refund_to_store_credit_amount ] )
python
def create( self, order_increment_id, creditmemo_data=None, comment=None, email=False, include_comment=False, refund_to_store_credit_amount=None): """ Create new credit_memo for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param creditmemo_data: Sales order credit memo data (optional) :type creditmemo_data: associative array as dict { 'qtys': [ { 'order_item_id': str, # Order item ID to be refunded 'qty': int # Items quantity to be refunded }, ... ], 'shipping_amount': float # refund shipping amount (optional) 'adjustment_positive': float # adjustment refund amount (optional) 'adjustment_negative': float # adjustment fee amount (optional) } :param comment: Credit memo Comment :type comment: str :param email: send e-mail flag (optional) :type email: bool :param include_comment: include comment in e-mail flag (optional) :type include_comment: bool :param refund_to_store_credit_amount: amount to refund to store credit :type refund_to_store_credit_amount: float :return str, increment id of credit memo created """ if comment is None: comment = '' return self.call( 'sales_order_creditmemo.create', [ order_increment_id, creditmemo_data, comment, email, include_comment, refund_to_store_credit_amount ] )
Create new credit_memo for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param creditmemo_data: Sales order credit memo data (optional) :type creditmemo_data: associative array as dict { 'qtys': [ { 'order_item_id': str, # Order item ID to be refunded 'qty': int # Items quantity to be refunded }, ... ], 'shipping_amount': float # refund shipping amount (optional) 'adjustment_positive': float # adjustment refund amount (optional) 'adjustment_negative': float # adjustment fee amount (optional) } :param comment: Credit memo Comment :type comment: str :param email: send e-mail flag (optional) :type email: bool :param include_comment: include comment in e-mail flag (optional) :type include_comment: bool :param refund_to_store_credit_amount: amount to refund to store credit :type refund_to_store_credit_amount: float :return str, increment id of credit memo created
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L153-L199
fulfilio/python-magento
magento/sales.py
CreditMemo.addcomment
def addcomment(self, creditmemo_increment_id, comment, email=True, include_in_email=False): """ Add new comment to credit memo :param creditmemo_increment_id: Credit memo increment ID :return: bool """ return bool( self.call( 'sales_order_creditmemo.addComment', [creditmemo_increment_id, comment, email, include_in_email] ) )
python
def addcomment(self, creditmemo_increment_id, comment, email=True, include_in_email=False): """ Add new comment to credit memo :param creditmemo_increment_id: Credit memo increment ID :return: bool """ return bool( self.call( 'sales_order_creditmemo.addComment', [creditmemo_increment_id, comment, email, include_in_email] ) )
Add new comment to credit memo :param creditmemo_increment_id: Credit memo increment ID :return: bool
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L201-L215
fulfilio/python-magento
magento/sales.py
Shipment.create
def create(self, order_increment_id, items_qty, comment=None, email=True, include_comment=False): """ Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty: associative array (order_item_id ⇒ qty) as dict :param comment: Shipment Comment :type comment: str :param email: send e-mail flag (optional) :type email: bool :param include_comment: include comment in e-mail flag (optional) :type include_comment: bool """ if comment is None: comment = '' return self.call( 'sales_order_shipment.create', [ order_increment_id, items_qty, comment, email, include_comment ] )
python
def create(self, order_increment_id, items_qty, comment=None, email=True, include_comment=False): """ Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty: associative array (order_item_id ⇒ qty) as dict :param comment: Shipment Comment :type comment: str :param email: send e-mail flag (optional) :type email: bool :param include_comment: include comment in e-mail flag (optional) :type include_comment: bool """ if comment is None: comment = '' return self.call( 'sales_order_shipment.create', [ order_increment_id, items_qty, comment, email, include_comment ] )
Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty: associative array (order_item_id ⇒ qty) as dict :param comment: Shipment Comment :type comment: str :param email: send e-mail flag (optional) :type email: bool :param include_comment: include comment in e-mail flag (optional) :type include_comment: bool
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L262-L284
fulfilio/python-magento
magento/sales.py
Shipment.addtrack
def addtrack(self, shipment_increment_id, carrier, title, track_number): """ Add new tracking number :param shipment_increment_id: Shipment ID :param carrier: Carrier Code :param title: Tracking title :param track_number: Tracking Number """ return self.call( 'sales_order_shipment.addTrack', [shipment_increment_id, carrier, title, track_number] )
python
def addtrack(self, shipment_increment_id, carrier, title, track_number): """ Add new tracking number :param shipment_increment_id: Shipment ID :param carrier: Carrier Code :param title: Tracking title :param track_number: Tracking Number """ return self.call( 'sales_order_shipment.addTrack', [shipment_increment_id, carrier, title, track_number] )
Add new tracking number :param shipment_increment_id: Shipment ID :param carrier: Carrier Code :param title: Tracking title :param track_number: Tracking Number
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L303-L315
fulfilio/python-magento
magento/sales.py
Invoice.addcomment
def addcomment(self, invoice_increment_id, comment=None, email=False, include_comment=False): """ Add comment to invoice or change its state :param invoice_increment_id: Invoice ID """ if comment is None: comment = "" return bool( self.call( 'sales_order_invoice.addComment', [invoice_increment_id, comment, email, include_comment] ) )
python
def addcomment(self, invoice_increment_id, comment=None, email=False, include_comment=False): """ Add comment to invoice or change its state :param invoice_increment_id: Invoice ID """ if comment is None: comment = "" return bool( self.call( 'sales_order_invoice.addComment', [invoice_increment_id, comment, email, include_comment] ) )
Add comment to invoice or change its state :param invoice_increment_id: Invoice ID
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/sales.py#L418-L432
fulfilio/python-magento
magento/utils.py
expand_url
def expand_url(url, protocol): """ Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap' """ if protocol == 'soap': ws_part = 'api/?wsdl' elif protocol == 'xmlrpc': ws_part = 'index.php/api/xmlrpc' else: ws_part = 'index.php/rest/V1' return url.endswith('/') and url + ws_part or url + '/' + ws_part
python
def expand_url(url, protocol): """ Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap' """ if protocol == 'soap': ws_part = 'api/?wsdl' elif protocol == 'xmlrpc': ws_part = 'index.php/api/xmlrpc' else: ws_part = 'index.php/rest/V1' return url.endswith('/') and url + ws_part or url + '/' + ws_part
Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap'
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/utils.py#L12-L26
fulfilio/python-magento
magento/utils.py
camel_2_snake
def camel_2_snake(name): "Converts CamelCase to camel_case" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
python
def camel_2_snake(name): "Converts CamelCase to camel_case" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Converts CamelCase to camel_case
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/utils.py#L29-L32
fulfilio/python-magento
magento/catalog.py
Category.level
def level(self, website=None, store_view=None, parent_category=None): """ Retrieve one level of categories by website/store view/parent category :param website: Website code or ID :param store_view: storeview code or ID :param parent_category: Parent Category ID :return: Dictionary """ return self.call( 'catalog_category.level', [website, store_view, parent_category] )
python
def level(self, website=None, store_view=None, parent_category=None): """ Retrieve one level of categories by website/store view/parent category :param website: Website code or ID :param store_view: storeview code or ID :param parent_category: Parent Category ID :return: Dictionary """ return self.call( 'catalog_category.level', [website, store_view, parent_category] )
Retrieve one level of categories by website/store view/parent category :param website: Website code or ID :param store_view: storeview code or ID :param parent_category: Parent Category ID :return: Dictionary
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L41-L52
fulfilio/python-magento
magento/catalog.py
Category.info
def info(self, category_id, store_view=None, attributes=None): """ Retrieve Category details :param category_id: ID of category to retrieve :param store_view: Store view ID or code :param attributes: Return the fields specified :return: Dictionary of data """ return self.call( 'catalog_category.info', [category_id, store_view, attributes] )
python
def info(self, category_id, store_view=None, attributes=None): """ Retrieve Category details :param category_id: ID of category to retrieve :param store_view: Store view ID or code :param attributes: Return the fields specified :return: Dictionary of data """ return self.call( 'catalog_category.info', [category_id, store_view, attributes] )
Retrieve Category details :param category_id: ID of category to retrieve :param store_view: Store view ID or code :param attributes: Return the fields specified :return: Dictionary of data
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L54-L65
fulfilio/python-magento
magento/catalog.py
Category.create
def create(self, parent_id, data, store_view=None): """ Create new category and return its ID :param parent_id: ID of parent :param data: Data for category :param store_view: Store view ID or Code :return: Integer ID """ return int(self.call( 'catalog_category.create', [parent_id, data, store_view]) )
python
def create(self, parent_id, data, store_view=None): """ Create new category and return its ID :param parent_id: ID of parent :param data: Data for category :param store_view: Store view ID or Code :return: Integer ID """ return int(self.call( 'catalog_category.create', [parent_id, data, store_view]) )
Create new category and return its ID :param parent_id: ID of parent :param data: Data for category :param store_view: Store view ID or Code :return: Integer ID
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L67-L78
fulfilio/python-magento
magento/catalog.py
Category.update
def update(self, category_id, data, store_view=None): """ Update Category :param category_id: ID of category :param data: Category Data :param store_view: Store view ID or code :return: Boolean """ return bool( self.call( 'catalog_category.update', [category_id, data, store_view] ) )
python
def update(self, category_id, data, store_view=None): """ Update Category :param category_id: ID of category :param data: Category Data :param store_view: Store view ID or code :return: Boolean """ return bool( self.call( 'catalog_category.update', [category_id, data, store_view] ) )
Update Category :param category_id: ID of category :param data: Category Data :param store_view: Store view ID or code :return: Boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L80-L93
fulfilio/python-magento
magento/catalog.py
Category.move
def move(self, category_id, parent_id, after_id=None): """ Move category in tree :param category_id: ID of category to move :param parent_id: New parent of the category :param after_id: Category ID after what position it will be moved :return: Boolean """ return bool(self.call( 'catalog_category.move', [category_id, parent_id, after_id]) )
python
def move(self, category_id, parent_id, after_id=None): """ Move category in tree :param category_id: ID of category to move :param parent_id: New parent of the category :param after_id: Category ID after what position it will be moved :return: Boolean """ return bool(self.call( 'catalog_category.move', [category_id, parent_id, after_id]) )
Move category in tree :param category_id: ID of category to move :param parent_id: New parent of the category :param after_id: Category ID after what position it will be moved :return: Boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L95-L106
fulfilio/python-magento
magento/catalog.py
Category.assignproduct
def assignproduct(self, category_id, product, position=None): """ Assign product to a category :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean """ return bool(self.call( 'catalog_category.assignProduct', [category_id, product, position]) )
python
def assignproduct(self, category_id, product, position=None): """ Assign product to a category :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean """ return bool(self.call( 'catalog_category.assignProduct', [category_id, product, position]) )
Assign product to a category :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L133-L145
fulfilio/python-magento
magento/catalog.py
Category.updateproduct
def updateproduct(self, category_id, product, position=None): """ Update assigned product :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean """ return bool(self.call( 'catalog_category.updateProduct', [category_id, product, position]) )
python
def updateproduct(self, category_id, product, position=None): """ Update assigned product :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean """ return bool(self.call( 'catalog_category.updateProduct', [category_id, product, position]) )
Update assigned product :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L150-L162
fulfilio/python-magento
magento/catalog.py
CategoryAttribute.currentStore
def currentStore(self, store_view=None): """ Set/Get current store view :param store_view: Store view ID or Code :return: int """ args = [store_view] if store_view else [] return int(self.call('catalog_category_attribute.currentStore', args))
python
def currentStore(self, store_view=None): """ Set/Get current store view :param store_view: Store view ID or Code :return: int """ args = [store_view] if store_view else [] return int(self.call('catalog_category_attribute.currentStore', args))
Set/Get current store view :param store_view: Store view ID or Code :return: int
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L191-L199
fulfilio/python-magento
magento/catalog.py
Product.info
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. :return: `dict` of values """ return self.call( 'catalog_product.info', [ product, store_view, attributes, identifierType ] )
python
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. :return: `dict` of values """ return self.call( 'catalog_product.info', [ product, store_view, attributes, identifierType ] )
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. :return: `dict` of values
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L253-L270
fulfilio/python-magento
magento/catalog.py
Product.create
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 """ return int(self.call( 'catalog_product.create', [product_type, attribute_set_id, sku, data] ) )
python
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 """ return int(self.call( 'catalog_product.create', [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
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L272-L286
fulfilio/python-magento
magento/catalog.py
Product.update
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. :return: Boolean """ return bool(self.call( 'catalog_product.update', [product, data, store_view, identifierType] ))
python
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. :return: Boolean """ return bool(self.call( 'catalog_product.update', [product, data, store_view, identifierType] ))
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. :return: Boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L288-L303
fulfilio/python-magento
magento/catalog.py
Product.setSpecialPrice
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 passed in the "product" parameter. :return: Boolean """ return bool(self.call( 'catalog_product.setSpecialPrice', [ product, special_price, from_date, to_date, store_view, identifierType ] ))
python
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 passed in the "product" parameter. :return: Boolean """ return bool(self.call( 'catalog_product.setSpecialPrice', [ product, special_price, from_date, to_date, store_view, identifierType ] ))
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 passed in the "product" parameter. :return: Boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L305-L326
fulfilio/python-magento
magento/catalog.py
Product.getSpecialPrice
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 """ return self.call( 'catalog_product.getSpecialPrice', [ product, store_view, identifierType ] )
python
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 """ return self.call( 'catalog_product.getSpecialPrice', [ product, store_view, identifierType ] )
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
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L328-L343
fulfilio/python-magento
magento/catalog.py
ProductImages.list
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` """ return self.call('catalog_product_attribute_media.list', [product, store_view, identifierType])
python
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` """ return self.call('catalog_product_attribute_media.list', [product, store_view, identifierType])
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`
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L539-L551
fulfilio/python-magento
magento/catalog.py
ProductImages.info
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. :return: `list` of `dict` """ return self.call('catalog_product_attribute_media.info', [product, image_file, store_view, identifierType])
python
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. :return: `list` of `dict` """ return self.call('catalog_product_attribute_media.info', [product, image_file, store_view, identifierType])
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. :return: `list` of `dict`
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L553-L566
fulfilio/python-magento
magento/catalog.py
ProductImages.create
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']} :param store_view: Store view ID or Code :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: string - image file name """ return self.call('catalog_product_attribute_media.create', [product, data, store_view, identifierType])
python
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']} :param store_view: Store view ID or Code :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: string - image file name """ return self.call('catalog_product_attribute_media.create', [product, data, store_view, identifierType])
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']} :param store_view: Store view ID or Code :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: string - image file name
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L578-L594
fulfilio/python-magento
magento/catalog.py
ProductImages.update
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', 'position': '1', 'exclude': '0', 'types': ['image', 'small_image', 'thumbnail']} :param store_view: Store view ID or Code :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: string - image file name """ return self.call('catalog_product_attribute_media.update', [product, img_file_name, data, store_view, identifierType])
python
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', 'position': '1', 'exclude': '0', 'types': ['image', 'small_image', 'thumbnail']} :param store_view: Store view ID or Code :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: string - image file name """ return self.call('catalog_product_attribute_media.update', [product, img_file_name, data, store_view, identifierType])
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', 'position': '1', 'exclude': '0', 'types': ['image', 'small_image', 'thumbnail']} :param store_view: Store view ID or Code :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: string - image file name
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L596-L615
fulfilio/python-magento
magento/catalog.py
ProductImages.remove
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. :return: boolean """ return self.call('catalog_product_attribute_media.remove', [product, img_file_name, identifierType])
python
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. :return: boolean """ return self.call('catalog_product_attribute_media.remove', [product, img_file_name, identifierType])
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. :return: boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L617-L630
fulfilio/python-magento
magento/catalog.py
ProductLinks.list
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" parameter. :return: `list` of `dict` """ return self.call('catalog_product_link.list', [link_type, product, identifierType])
python
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" parameter. :return: `list` of `dict` """ return self.call('catalog_product_link.list', [link_type, product, identifierType])
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" parameter. :return: `list` of `dict`
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L687-L700
fulfilio/python-magento
magento/catalog.py
ProductLinks.assign
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.) Example: { 'position': '0', 'qty': 1} :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: boolean """ return bool(self.call('catalog_product_link.assign', [link_type, product, linked_product, data, identifierType]))
python
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.) Example: { 'position': '0', 'qty': 1} :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: boolean """ return bool(self.call('catalog_product_link.assign', [link_type, product, linked_product, data, identifierType]))
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.) Example: { 'position': '0', 'qty': 1} :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L702-L719
fulfilio/python-magento
magento/catalog.py
ProductLinks.remove
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 is passed in the "product" parameter. :return: boolean """ return bool(self.call('catalog_product_link.remove', [link_type, product, linked_product, identifierType]))
python
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 is passed in the "product" parameter. :return: boolean """ return bool(self.call('catalog_product_link.remove', [link_type, product, linked_product, identifierType]))
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 is passed in the "product" parameter. :return: boolean
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L740-L754
fulfilio/python-magento
magento/catalog.py
ProductConfigurable.update
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 """ return bool(self.call('ol_catalog_product_link.assign', [product, linked_products, attributes]))
python
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 """ return bool(self.call('ol_catalog_product_link.assign', [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
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L819-L829
fulfilio/python-magento
magento/checkout.py
Cart.order
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 license ID :return: string, result of creating order """ return self.call('cart.order', [quote_id, store_view, license_id])
python
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 license ID :return: string, result of creating order """ return self.call('cart.order', [quote_id, store_view, license_id])
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 license ID :return: string, result of creating order
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L51-L62
fulfilio/python-magento
magento/checkout.py
CartCoupon.add
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 """ return bool( self.call('cart_coupon.add', [quote_id, coupon_code, store_view]) )
python
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 """ return bool( self.call('cart_coupon.add', [quote_id, coupon_code, store_view]) )
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
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L81-L92
fulfilio/python-magento
magento/checkout.py
CartCustomer.addresses
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' }, { 'mode': 'shipping', 'firstname': 'testFirstname', 'lastname': 'testLastname', 'company': 'testCompany', 'street': 'testStreet', 'city': 'testCity', 'region': 'testRegion', 'region_id': 'testRegionId', 'postcode': 'testPostcode', 'country_id': 'id', 'telephone': '0123456789', 'fax': '0123456789', 'is_default_shipping': 0, 'is_default_billing': 0 }, ] :param store_view: Store view ID or code :return: boolean, True if the address is set """ return bool( self.call('cart_customer.addresses', [quote_id, address_data, store_view]) )
python
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' }, { 'mode': 'shipping', 'firstname': 'testFirstname', 'lastname': 'testLastname', 'company': 'testCompany', 'street': 'testStreet', 'city': 'testCity', 'region': 'testRegion', 'region_id': 'testRegionId', 'postcode': 'testPostcode', 'country_id': 'id', 'telephone': '0123456789', 'fax': '0123456789', 'is_default_shipping': 0, 'is_default_billing': 0 }, ] :param store_view: Store view ID or code :return: boolean, True if the address is set """ return bool( self.call('cart_customer.addresses', [quote_id, address_data, store_view]) )
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' }, { 'mode': 'shipping', 'firstname': 'testFirstname', 'lastname': 'testLastname', 'company': 'testCompany', 'street': 'testStreet', 'city': 'testCity', 'region': 'testRegion', 'region_id': 'testRegionId', 'postcode': 'testPostcode', 'country_id': 'id', 'telephone': '0123456789', 'fax': '0123456789', 'is_default_shipping': 0, 'is_default_billing': 0 }, ] :param store_view: Store view ID or code :return: boolean, True if the address is set
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L113-L147
fulfilio/python-magento
magento/checkout.py
CartCustomer.set
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', 'website_id': '0', 'store_id': '0', 'mode': 'guest' } :param store_view: Store view ID or code :return: boolean, True if information added """ return bool( self.call('cart_customer.set', [quote_id, customer_data, store_view]) )
python
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', 'website_id': '0', 'store_id': '0', 'mode': 'guest' } :param store_view: Store view ID or code :return: boolean, True if information added """ return bool( self.call('cart_customer.set', [quote_id, customer_data, store_view]) )
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', 'website_id': '0', 'store_id': '0', 'mode': 'guest' } :param store_view: Store view ID or code :return: boolean, True if information added
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L149-L169
fulfilio/python-magento
magento/checkout.py
CartPayment.method
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': '', 'cc_number': '', 'cc_type': '', 'cc_exp_year': '', 'cc_exp_month': '' } :param store_view: Store view ID or code :return: boolean, True on success """ return bool( self.call('cart_payment.method', [quote_id, payment_data, store_view]) )
python
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': '', 'cc_number': '', 'cc_type': '', 'cc_exp_year': '', 'cc_exp_month': '' } :param store_view: Store view ID or code :return: boolean, True on success """ return bool( self.call('cart_payment.method', [quote_id, payment_data, store_view]) )
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': '', 'cc_number': '', 'cc_type': '', 'cc_exp_year': '', 'cc_exp_month': '' } :param store_view: Store view ID or code :return: boolean, True on success
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L194-L216
fulfilio/python-magento
magento/checkout.py
CartProduct.add
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, 'options': { 'option_1': 'value_1', 'option_2': 'value_2', ... }, 'bundle_option': {}, 'bundle_option_qty': {}, 'links': [], }, { 'sku': 'S0012345', 'qty': 4, }, ] :param store_view: Store view ID or code :return: boolean, True on success (if the product is added to the shopping cart) """ return bool( self.call('cart_product.add', [quote_id, product_data, store_view]) )
python
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, 'options': { 'option_1': 'value_1', 'option_2': 'value_2', ... }, 'bundle_option': {}, 'bundle_option_qty': {}, 'links': [], }, { 'sku': 'S0012345', 'qty': 4, }, ] :param store_view: Store view ID or code :return: boolean, True on success (if the product is added to the shopping cart) """ return bool( self.call('cart_product.add', [quote_id, product_data, store_view]) )
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, 'options': { 'option_1': 'value_1', 'option_2': 'value_2', ... }, 'bundle_option': {}, 'bundle_option_qty': {}, 'links': [], }, { 'sku': 'S0012345', 'qty': 4, }, ] :param store_view: Store view ID or code :return: boolean, True on success (if the product is added to the shopping cart)
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L225-L255
fulfilio/python-magento
magento/checkout.py
CartProduct.move_to_customer_quote
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, 'options': { 'option_1': 'value_1', 'option_2': 'value_2', ... }, 'bundle_option': {}, 'bundle_option_qty': {}, 'links': [], }, { 'sku': 'S0012345', 'qty': 4, }, ] :param store_view: Store view ID or code :return: boolean, True if the product is moved to customer quote """ return bool( self.call('cart_product.moveToCustomerQuote', [quote_id, product_data, store_view]) )
python
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, 'options': { 'option_1': 'value_1', 'option_2': 'value_2', ... }, 'bundle_option': {}, 'bundle_option_qty': {}, 'links': [], }, { 'sku': 'S0012345', 'qty': 4, }, ] :param store_view: Store view ID or code :return: boolean, True if the product is moved to customer quote """ return bool( self.call('cart_product.moveToCustomerQuote', [quote_id, product_data, store_view]) )
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, 'options': { 'option_1': 'value_1', 'option_2': 'value_2', ... }, 'bundle_option': {}, 'bundle_option_qty': {}, 'links': [], }, { 'sku': 'S0012345', 'qty': 4, }, ] :param store_view: Store view ID or code :return: boolean, True if the product is moved to customer quote
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L277-L307
fulfilio/python-magento
magento/checkout.py
CartProduct.remove
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 """ return bool( self.call('cart_product.remove', [quote_id, product_data, store_view]) )
python
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 """ return bool( self.call('cart_product.remove', [quote_id, product_data, store_view]) )
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
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L312-L325
fulfilio/python-magento
magento/checkout.py
CartProduct.update
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 . """ return bool( self.call('cart_product.update', [quote_id, product_data, store_view]) )
python
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 . """ return bool( self.call('cart_product.update', [quote_id, product_data, store_view]) )
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 .
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L327-L340
fulfilio/python-magento
magento/checkout.py
CartShipping.method
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 """ return bool( self.call('cart_shipping.method', [quote_id, shipping_method, store_view]) )
python
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 """ return bool( self.call('cart_shipping.method', [quote_id, shipping_method, store_view]) )
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
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L360-L372
sarugaku/passa
tasks/package.py
pack
def pack(ctx, remove_lib=True): """Build a isolated runnable package. """ 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.ScriptMaker(None, None) # Install packages from Pipfile.lock. for name, package in lockfile.default._data.items(): if name in DONT_PACKAGE: continue print(f'[pack] Installing {name}') package.pop('editable', None) # Don't install things as editable. package.pop('markers', None) # Always install everything. r = requirementslib.Requirement.from_pipfile(name, package) wheel = passa.internals._pip.build_wheel( r.as_ireq(), sources, r.hashes or None, ) wheel.install(paths, maker, lib_only=True) for pattern in IGNORE_LIB_PATTERNS: for path in libdir.rglob(pattern): print(f'[pack] Removing {path}') path.unlink() # Pack everything into ZIP. zipname = OUTPUT_DIR.joinpath('passa.zip') with zipfile.ZipFile(zipname, 'w') as zf: _recursive_write_to_zip(zf, OUTPUT_DIR) _recursive_write_to_zip(zf, STUBFILES_DIR) print(f'[pack] Written archive {zipname}') if remove_lib and libdir.exists(): print(f'[pack] Removing {libdir}') shutil.rmtree(str(libdir))
python
def pack(ctx, remove_lib=True): """Build a isolated runnable package. """ 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.ScriptMaker(None, None) # Install packages from Pipfile.lock. for name, package in lockfile.default._data.items(): if name in DONT_PACKAGE: continue print(f'[pack] Installing {name}') package.pop('editable', None) # Don't install things as editable. package.pop('markers', None) # Always install everything. r = requirementslib.Requirement.from_pipfile(name, package) wheel = passa.internals._pip.build_wheel( r.as_ireq(), sources, r.hashes or None, ) wheel.install(paths, maker, lib_only=True) for pattern in IGNORE_LIB_PATTERNS: for path in libdir.rglob(pattern): print(f'[pack] Removing {path}') path.unlink() # Pack everything into ZIP. zipname = OUTPUT_DIR.joinpath('passa.zip') with zipfile.ZipFile(zipname, 'w') as zf: _recursive_write_to_zip(zf, OUTPUT_DIR) _recursive_write_to_zip(zf, STUBFILES_DIR) print(f'[pack] Written archive {zipname}') if remove_lib and libdir.exists(): print(f'[pack] Removing {libdir}') shutil.rmtree(str(libdir))
Build a isolated runnable package.
https://github.com/sarugaku/passa/blob/a2ba0b30c86339cae5ef3a03046fc9c583452c40/tasks/package.py#L57-L97
sarugaku/passa
tasks/admin.py
release
def release(ctx, type_, repo=None, prebump_to=PREBUMP): """Make a new release. """ 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): return else: print('[release] Missing --repo, skip uploading') prebump(ctx, type_=prebump_to) next_version = _read_version() ctx.run(f'git commit -am "Prebump to {next_version}"')
python
def release(ctx, type_, repo=None, prebump_to=PREBUMP): """Make a new release. """ 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): return else: print('[release] Missing --repo, skip uploading') prebump(ctx, type_=prebump_to) next_version = _read_version() ctx.run(f'git commit -am "Prebump to {next_version}"')
Make a new release.
https://github.com/sarugaku/passa/blob/a2ba0b30c86339cae5ef3a03046fc9c583452c40/tasks/admin.py#L123-L144
dkruchinin/sanic-prometheus
sanic_prometheus/__init__.py
monitor
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 fetched from Sanic `request` object using different strategies specified by `endpoint_type`: url - full relative path of a request URL (i.e. for http://something/a/b/c?f=x you end up having `/a/b/c` as the endpoint) url:n - like URL but with at most `n` path elements in the endpoint (i.e. with `url:1` http://something/a/b/c becomes `/a`). custom - custom endpoint fetching funciton that should be specified by `get_endpoint_fn` :param get_endpoint_fn: a custom endpoint fetching function that is ignored until `endpoint_type='custom'`. get_endpoint_fn = lambda r: ... where `r` is Sanic request object :param latency_buckets: an optional list of bucket sizes for latency histogram (see prometheus `Histogram` metric) :param mmc_period_sec: set a period (in seconds) of how frequently memory usage related metrics are collected. Setting it to None will disable memory metrics collection. NOTE: memory usage is not collected when when multiprocessing is enabled """ 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, multiprocess_mode, memcollect_enabled=memcollect_enabled ) @app.middleware('request') async def before_request(request): if request.path != '/metrics': metrics.before_request_handler(request) @app.middleware('response') async def before_response(request, response): if request.path != '/metrics': metrics.after_request_handler(request, response, get_endpoint) if multiprocess_on: @app.listener('after_server_stop') def after_stop(app, loop): multiprocess.mark_process_dead(os.getpid()) elif memcollect_enabled: @app.listener('before_server_start') async def start_memcollect_task(app, loop): app.memcollect_task = loop.create_task( metrics.periodic_memcollect_task( mmc_period_sec, loop ) ) @app.listener('after_server_stop') async def stop_memcollect_task(app, loop): app.memcollect_task.cancel() return MonitorSetup(app, multiprocess_on)
python
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 fetched from Sanic `request` object using different strategies specified by `endpoint_type`: url - full relative path of a request URL (i.e. for http://something/a/b/c?f=x you end up having `/a/b/c` as the endpoint) url:n - like URL but with at most `n` path elements in the endpoint (i.e. with `url:1` http://something/a/b/c becomes `/a`). custom - custom endpoint fetching funciton that should be specified by `get_endpoint_fn` :param get_endpoint_fn: a custom endpoint fetching function that is ignored until `endpoint_type='custom'`. get_endpoint_fn = lambda r: ... where `r` is Sanic request object :param latency_buckets: an optional list of bucket sizes for latency histogram (see prometheus `Histogram` metric) :param mmc_period_sec: set a period (in seconds) of how frequently memory usage related metrics are collected. Setting it to None will disable memory metrics collection. NOTE: memory usage is not collected when when multiprocessing is enabled """ 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, multiprocess_mode, memcollect_enabled=memcollect_enabled ) @app.middleware('request') async def before_request(request): if request.path != '/metrics': metrics.before_request_handler(request) @app.middleware('response') async def before_response(request, response): if request.path != '/metrics': metrics.after_request_handler(request, response, get_endpoint) if multiprocess_on: @app.listener('after_server_stop') def after_stop(app, loop): multiprocess.mark_process_dead(os.getpid()) elif memcollect_enabled: @app.listener('before_server_start') async def start_memcollect_task(app, loop): app.memcollect_task = loop.create_task( metrics.periodic_memcollect_task( mmc_period_sec, loop ) ) @app.listener('after_server_stop') async def stop_memcollect_task(app, loop): app.memcollect_task.cancel() return MonitorSetup(app, multiprocess_on)
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 fetched from Sanic `request` object using different strategies specified by `endpoint_type`: url - full relative path of a request URL (i.e. for http://something/a/b/c?f=x you end up having `/a/b/c` as the endpoint) url:n - like URL but with at most `n` path elements in the endpoint (i.e. with `url:1` http://something/a/b/c becomes `/a`). custom - custom endpoint fetching funciton that should be specified by `get_endpoint_fn` :param get_endpoint_fn: a custom endpoint fetching function that is ignored until `endpoint_type='custom'`. get_endpoint_fn = lambda r: ... where `r` is Sanic request object :param latency_buckets: an optional list of bucket sizes for latency histogram (see prometheus `Histogram` metric) :param mmc_period_sec: set a period (in seconds) of how frequently memory usage related metrics are collected. Setting it to None will disable memory metrics collection. NOTE: memory usage is not collected when when multiprocessing is enabled
https://github.com/dkruchinin/sanic-prometheus/blob/fc0c2d337e8fc5e57960f152d06d5eb824678fd0/sanic_prometheus/__init__.py#L59-L134
dkruchinin/sanic-prometheus
sanic_prometheus/__init__.py
MonitorSetup.expose_endpoint
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. """ @self._app.route('/metrics', methods=['GET']) async def expose_metrics(request): return raw(self._get_metrics_data(), content_type=CONTENT_TYPE_LATEST)
python
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. """ @self._app.route('/metrics', methods=['GET']) async def expose_metrics(request): return raw(self._get_metrics_data(), content_type=CONTENT_TYPE_LATEST)
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.
https://github.com/dkruchinin/sanic-prometheus/blob/fc0c2d337e8fc5e57960f152d06d5eb824678fd0/sanic_prometheus/__init__.py#L20-L31
dkruchinin/sanic-prometheus
sanic_prometheus/__init__.py
MonitorSetup.start_server
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 """ if self._multiprocess_on: raise SanicPrometheusError( "start_server can not be used when multiprocessing " + "is turned on") start_http_server(addr=addr, port=port)
python
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 """ if self._multiprocess_on: raise SanicPrometheusError( "start_server can not be used when multiprocessing " + "is turned on") start_http_server(addr=addr, port=port)
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
https://github.com/dkruchinin/sanic-prometheus/blob/fc0c2d337e8fc5e57960f152d06d5eb824678fd0/sanic_prometheus/__init__.py#L33-L46
remix/partridge
partridge/writers.py
extract_feed
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""" 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)
python
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""" 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)
Extract a subset of a GTFS zip into a new file
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/writers.py#L19-L26
remix/partridge
partridge/writers.py
write_feed_dangerously
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. """ 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(len(nodes)) try: pool.map(write_node, nodes) finally: pool.terminate() if outpath.endswith(".zip"): outpath, _ = os.path.splitext(outpath) outpath = shutil.make_archive(outpath, "zip", tmpdir) finally: shutil.rmtree(tmpdir) return outpath
python
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. """ 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(len(nodes)) try: pool.map(write_node, nodes) finally: pool.terminate() if outpath.endswith(".zip"): outpath, _ = os.path.splitext(outpath) outpath = shutil.make_archive(outpath, "zip", tmpdir) finally: shutil.rmtree(tmpdir) return outpath
Naively write a feed to a zipfile This function provides no sanity checks. Use it at your own risk.
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/writers.py#L29-L60
remix/partridge
partridge/readers.py
read_busiest_date
def read_busiest_date(path: str) -> Tuple[datetime.date, FrozenSet[str]]: """Find the earliest date with the most trips""" feed = load_raw_feed(path) return _busiest_date(feed)
python
def read_busiest_date(path: str) -> Tuple[datetime.date, FrozenSet[str]]: """Find the earliest date with the most trips""" feed = load_raw_feed(path) return _busiest_date(feed)
Find the earliest date with the most trips
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/readers.py#L57-L60
remix/partridge
partridge/readers.py
read_busiest_week
def read_busiest_week(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find the earliest week with the most trips""" feed = load_raw_feed(path) return _busiest_week(feed)
python
def read_busiest_week(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find the earliest week with the most trips""" feed = load_raw_feed(path) return _busiest_week(feed)
Find the earliest week with the most trips
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/readers.py#L63-L66
remix/partridge
partridge/readers.py
read_service_ids_by_date
def read_service_ids_by_date(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find all service identifiers by date""" feed = load_raw_feed(path) return _service_ids_by_date(feed)
python
def read_service_ids_by_date(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find all service identifiers by date""" feed = load_raw_feed(path) return _service_ids_by_date(feed)
Find all service identifiers by date
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/readers.py#L69-L72
remix/partridge
partridge/readers.py
read_dates_by_service_ids
def read_dates_by_service_ids( path: str ) -> Dict[FrozenSet[str], FrozenSet[datetime.date]]: """Find dates with identical service""" feed = load_raw_feed(path) return _dates_by_service_ids(feed)
python
def read_dates_by_service_ids( path: str ) -> Dict[FrozenSet[str], FrozenSet[datetime.date]]: """Find dates with identical service""" feed = load_raw_feed(path) return _dates_by_service_ids(feed)
Find dates with identical service
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/readers.py#L75-L80
remix/partridge
partridge/readers.py
read_trip_counts_by_date
def read_trip_counts_by_date(path: str) -> Dict[datetime.date, int]: """A useful proxy for busyness""" feed = load_raw_feed(path) return _trip_counts_by_date(feed)
python
def read_trip_counts_by_date(path: str) -> Dict[datetime.date, int]: """A useful proxy for busyness""" feed = load_raw_feed(path) return _trip_counts_by_date(feed)
A useful proxy for busyness
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/readers.py#L83-L86
remix/partridge
partridge/readers.py
_load_feed
def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed: """Multi-file feed filtering""" 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_, config=config_) return Feed(feed_, config=config)
python
def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed: """Multi-file feed filtering""" 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_, config=config_) return Feed(feed_, config=config)
Multi-file feed filtering
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/readers.py#L106-L114
remix/partridge
partridge/gtfs.py
Feed._filter
def _filter(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Apply view filters""" 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 df
python
def _filter(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Apply view filters""" 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 df
Apply view filters
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/gtfs.py#L114-L125
remix/partridge
partridge/gtfs.py
Feed._prune
def _prune(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Depth-first search through the dependency graph and prune dependent DataFrames along the way. """ 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) dependencies.append((depf, deps)) if not dependencies: return df for depfile, column_pairs in dependencies: # Read the filtered, cached file dependency depdf = self.get(depfile) for deps in column_pairs: col = deps[filename] depcol = deps[depfile] # If applicable, prune this dataframe by the other if col in df.columns and depcol in depdf.columns: df = df[df[col].isin(depdf[depcol])] return df
python
def _prune(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Depth-first search through the dependency graph and prune dependent DataFrames along the way. """ 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) dependencies.append((depf, deps)) if not dependencies: return df for depfile, column_pairs in dependencies: # Read the filtered, cached file dependency depdf = self.get(depfile) for deps in column_pairs: col = deps[filename] depcol = deps[depfile] # If applicable, prune this dataframe by the other if col in df.columns and depcol in depdf.columns: df = df[df[col].isin(depdf[depcol])] return df
Depth-first search through the dependency graph and prune dependent DataFrames along the way.
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/gtfs.py#L127-L152
remix/partridge
partridge/gtfs.py
Feed._convert_types
def _convert_types(self, filename: str, df: pd.DataFrame) -> None: """ Apply type conversions """ 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])
python
def _convert_types(self, filename: str, df: pd.DataFrame) -> None: """ Apply type conversions """ 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])
Apply type conversions
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/gtfs.py#L154-L164
remix/partridge
partridge/config.py
reroot_graph
def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph: """Return a copy of the graph rooted at the given node""" 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
python
def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph: """Return a copy of the graph rooted at the given node""" 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
Return a copy of the graph rooted at the given node
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/config.py#L339-L346
remix/partridge
partridge/utilities.py
setwrap
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. """ return set(map(str, set(flatten([value]))))
python
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. """ return set(map(str, set(flatten([value]))))
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.
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/utilities.py#L10-L17
remix/partridge
partridge/utilities.py
remove_node_attributes
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. """ G = G.copy() for _, data in G.nodes(data=True): for attribute in setwrap(attributes): if attribute in data: del data[attribute] return G
python
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. """ G = G.copy() for _, data in G.nodes(data=True): for attribute in setwrap(attributes): if attribute in data: del data[attribute] return G
Return a copy of the graph with the given attributes deleted from all nodes.
https://github.com/remix/partridge/blob/0ba80fa30035e5e09fd8d7a7bdf1f28b93d53d03/partridge/utilities.py#L20-L30
ciena/afkak
afkak/_util.py
_coerce_topic
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` """ 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('topic={!r} name is too long: {} > 249'.format( topic, len(topic))) return topic
python
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` """ 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('topic={!r} name is too long: {} > 249'.format( topic, len(topic))) return 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`
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_util.py#L27-L44
ciena/afkak
afkak/_util.py
_coerce_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` """ 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
python
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` """ 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
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`
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_util.py#L47-L59
ciena/afkak
afkak/_util.py
_coerce_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 """ 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
python
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 """ 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
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
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_util.py#L62-L74
ciena/afkak
afkak/_util.py
write_short_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 """ 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'))
python
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 """ 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'))
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
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_util.py#L83-L99
ciena/afkak
afkak/_util.py
write_short_bytes
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 encoding. :return: length-prefixed `bytes` :raises: `struct.error` for strings longer than 32767 characters """ 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
python
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 encoding. :return: length-prefixed `bytes` :raises: `struct.error` for strings longer than 32767 characters """ 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
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 encoding. :return: length-prefixed `bytes` :raises: `struct.error` for strings longer than 32767 characters
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_util.py#L102-L122
Salamek/cron-descriptor
examples/crontabReader.py
CrontabReader.parse_cron_line
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 """ 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
python
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 """ 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
Parses crontab line and returns only starting time string Args: line: crontab line Returns: Time part of cron line
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/examples/crontabReader.py#L58-L73
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient.updateMetadata
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 current metadata. """ 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
python
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 current metadata. """ 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
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 current metadata.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L130-L147
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient.makeRequest
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 request to send when the connection comes back up. """ 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 expectResponse=False # But that's pathological, and the only defense is to track # all requestIds sent regardless of whether we expect to see # a response, which is effectively a memory leak... raise DuplicateRequestError( 'Reuse of requestId:{}'.format(requestId)) # If we've been told to shutdown (close() called) then fail request if self._dDown: return fail(ClientError('makeRequest() called after close()')) # Ok, we are going to save/send it, create a _Request object to track canceller = partial( self.cancelRequest, requestId, CancelledError(message="Request correlationId={} was cancelled".format(requestId))) tReq = _Request(requestId, request, expectResponse, canceller) # add it to our requests dict self.requests[requestId] = tReq # Add an errback to the tReq.d to remove it from our requests dict # if something goes wrong... tReq.d.addErrback(self._handleRequestFailure, requestId) # Do we have a connection over which to send the request? if self.proto: # Send the request self._sendRequest(tReq) # Have we not even started trying to connect yet? Do so now elif not self.connector: self._connect() return tReq.d
python
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 request to send when the connection comes back up. """ 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 expectResponse=False # But that's pathological, and the only defense is to track # all requestIds sent regardless of whether we expect to see # a response, which is effectively a memory leak... raise DuplicateRequestError( 'Reuse of requestId:{}'.format(requestId)) # If we've been told to shutdown (close() called) then fail request if self._dDown: return fail(ClientError('makeRequest() called after close()')) # Ok, we are going to save/send it, create a _Request object to track canceller = partial( self.cancelRequest, requestId, CancelledError(message="Request correlationId={} was cancelled".format(requestId))) tReq = _Request(requestId, request, expectResponse, canceller) # add it to our requests dict self.requests[requestId] = tReq # Add an errback to the tReq.d to remove it from our requests dict # if something goes wrong... tReq.d.addErrback(self._handleRequestFailure, requestId) # Do we have a connection over which to send the request? if self.proto: # Send the request self._sendRequest(tReq) # Have we not even started trying to connect yet? Do so now elif not self.connector: self._connect() return tReq.d
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 request to send when the connection comes back up.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L149-L194
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient.disconnect
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. """ if self.proto: log.debug('%r Disconnecting from %r', self, self.proto.transport.getPeer()) self.proto.transport.loseConnection()
python
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. """ if self.proto: log.debug('%r Disconnecting from %r', self, self.proto.transport.getPeer()) self.proto.transport.loseConnection()
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.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L196-L206
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient.close
def close(self): """Permanently dispose of the broker client. This terminates any outstanding connection and cancels any pending requests. """ 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 connectingFailed(reason): """ Handle the failure resulting from cancellation. :reason: a `Failure`, most likely a cancellation error (but that's not guaranteed). :returns: `None` to handle the failure """ log.debug('%r: connection attempt has been cancelled: %r', self, reason) self._dDown.callback(None) self.connector.addErrback(connectingFailed) self.connector.cancel() else: # Fake a cleanly closing connection self._dDown.callback(None) try: raise CancelledError(message="Broker client for node_id={} {}:{} was closed".format( self.node_id, self.host, self.port)) except Exception: reason = Failure() # Cancel any requests for correlation_id in list(self.requests.keys()): # must copy, may del self.cancelRequest(correlation_id, reason) return self._dDown
python
def close(self): """Permanently dispose of the broker client. This terminates any outstanding connection and cancels any pending requests. """ 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 connectingFailed(reason): """ Handle the failure resulting from cancellation. :reason: a `Failure`, most likely a cancellation error (but that's not guaranteed). :returns: `None` to handle the failure """ log.debug('%r: connection attempt has been cancelled: %r', self, reason) self._dDown.callback(None) self.connector.addErrback(connectingFailed) self.connector.cancel() else: # Fake a cleanly closing connection self._dDown.callback(None) try: raise CancelledError(message="Broker client for node_id={} {}:{} was closed".format( self.node_id, self.host, self.port)) except Exception: reason = Failure() # Cancel any requests for correlation_id in list(self.requests.keys()): # must copy, may del self.cancelRequest(correlation_id, reason) return self._dDown
Permanently dispose of the broker client. This terminates any outstanding connection and cancels any pending requests.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L208-L246
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient._connectionLost
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 indicates the reason for disconnection. """ 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: self._dDown.callback(None) elif self.requests: self._connect()
python
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 indicates the reason for disconnection. """ 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: self._dDown.callback(None) elif self.requests: self._connect()
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 indicates the reason for disconnection.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L252-L275
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient.handleResponse
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. """ 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 cancelled, causing us to remove it from self.requests log.warning('Unexpected response with correlationId=%d: %r', requestId, reprlib.repr(response)) else: tReq.d.callback(response)
python
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. """ 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 cancelled, causing us to remove it from self.requests log.warning('Unexpected response with correlationId=%d: %r', requestId, reprlib.repr(response)) else: tReq.d.callback(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.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L277-L292
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient._sendRequest
def _sendRequest(self, tReq): """Send a single request over our protocol to the Kafka broker.""" 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: # Once we've sent a request for which we don't expect a reply, # we're done, remove it from requests, and fire the deferred # with 'None', since there is no reply to be expected del self.requests[tReq.id] tReq.d.callback(None)
python
def _sendRequest(self, tReq): """Send a single request over our protocol to the Kafka broker.""" 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: # Once we've sent a request for which we don't expect a reply, # we're done, remove it from requests, and fire the deferred # with 'None', since there is no reply to be expected del self.requests[tReq.id] tReq.d.callback(None)
Send a single request over our protocol to the Kafka broker.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L296-L311
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient._sendQueued
def _sendQueued(self): """Connection just came up, send the unsent requests.""" for tReq in list(self.requests.values()): # must copy, may del if not tReq.sent: self._sendRequest(tReq)
python
def _sendQueued(self): """Connection just came up, send the unsent requests.""" for tReq in list(self.requests.values()): # must copy, may del if not tReq.sent: self._sendRequest(tReq)
Connection just came up, send the unsent requests.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L313-L317
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient.cancelRequest
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 """ if reason is None: reason = CancelledError() tReq = self.requests.pop(requestId) tReq.d.errback(reason)
python
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 """ if reason is None: reason = CancelledError() tReq = self.requests.pop(requestId) tReq.d.errback(reason)
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
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L322-L332
ciena/afkak
afkak/brokerclient.py
_KafkaBrokerClient._connect
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. """ 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', self, endpoint) return endpoint.connect(self) def cbConnect(proto): log.debug('%r: connected to %r', self, proto.transport.getPeer()) self._failures = 0 self.connector = None self.proto = proto if self._dDown: proto.transport.loseConnection() else: self._sendQueued() def ebConnect(fail): if self._dDown: log.debug('%r: breaking connect loop due to %r after close()', self, fail) return fail self._failures += 1 delay = self._retryPolicy(self._failures) log.debug('%r: failure %d to connect -> %s; retry in %.2f seconds.', self, self._failures, fail.value, delay) self.connector = d = deferLater(self._reactor, delay, lambda: None) d.addCallback(cbDelayed) def cbDelayed(result): tryConnect() self._failures = 0 tryConnect()
python
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. """ 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', self, endpoint) return endpoint.connect(self) def cbConnect(proto): log.debug('%r: connected to %r', self, proto.transport.getPeer()) self._failures = 0 self.connector = None self.proto = proto if self._dDown: proto.transport.loseConnection() else: self._sendQueued() def ebConnect(fail): if self._dDown: log.debug('%r: breaking connect loop due to %r after close()', self, fail) return fail self._failures += 1 delay = self._retryPolicy(self._failures) log.debug('%r: failure %d to connect -> %s; retry in %.2f seconds.', self, self._failures, fail.value, delay) self.connector = d = deferLater(self._reactor, delay, lambda: None) d.addCallback(cbDelayed) def cbDelayed(result): tryConnect() self._failures = 0 tryConnect()
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.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L342-L384
Salamek/cron-descriptor
cron_descriptor/ExpressionParser.py
ExpressionParser.parse
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 """ # 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._expression.split() expression_parts_temp_length = len(expression_parts_temp) if expression_parts_temp_length < 5: raise FormatException( "Error: Expression only has {0} parts. At least 5 part are required.".format( expression_parts_temp_length)) elif expression_parts_temp_length == 5: # 5 part cron so shift array past seconds element for i, expression_part_temp in enumerate(expression_parts_temp): parsed[i + 1] = expression_part_temp elif expression_parts_temp_length == 6: # If last element ends with 4 digits, a year element has been # supplied and no seconds element year_regex = re.compile(r"\d{4}$") if year_regex.search(expression_parts_temp[5]) is not None: for i, expression_part_temp in enumerate(expression_parts_temp): parsed[i + 1] = expression_part_temp else: for i, expression_part_temp in enumerate(expression_parts_temp): parsed[i] = expression_part_temp elif expression_parts_temp_length == 7: parsed = expression_parts_temp else: raise FormatException( "Error: Expression has too many parts ({0}). Expression must not have more than 7 parts.".format( expression_parts_temp_length)) self.normalize_expression(parsed) return parsed
python
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 """ # 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._expression.split() expression_parts_temp_length = len(expression_parts_temp) if expression_parts_temp_length < 5: raise FormatException( "Error: Expression only has {0} parts. At least 5 part are required.".format( expression_parts_temp_length)) elif expression_parts_temp_length == 5: # 5 part cron so shift array past seconds element for i, expression_part_temp in enumerate(expression_parts_temp): parsed[i + 1] = expression_part_temp elif expression_parts_temp_length == 6: # If last element ends with 4 digits, a year element has been # supplied and no seconds element year_regex = re.compile(r"\d{4}$") if year_regex.search(expression_parts_temp[5]) is not None: for i, expression_part_temp in enumerate(expression_parts_temp): parsed[i + 1] = expression_part_temp else: for i, expression_part_temp in enumerate(expression_parts_temp): parsed[i] = expression_part_temp elif expression_parts_temp_length == 7: parsed = expression_parts_temp else: raise FormatException( "Error: Expression has too many parts ({0}). Expression must not have more than 7 parts.".format( expression_parts_temp_length)) self.normalize_expression(parsed) return parsed
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
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionParser.py#L72-L114
Salamek/cron-descriptor
cron_descriptor/ExpressionParser.py
ExpressionParser.normalize_expression
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 """ # 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_parts[ 0].replace("0/", "*/") # seconds if expression_parts[1].startswith("0/"): expression_parts[1] = expression_parts[ 1].replace("0/", "*/") # minutes if expression_parts[2].startswith("0/"): expression_parts[2] = expression_parts[ 2].replace("0/", "*/") # hours if expression_parts[3].startswith("1/"): expression_parts[3] = expression_parts[3].replace("1/", "*/") # DOM if expression_parts[4].startswith("1/"): expression_parts[4] = expression_parts[ 4].replace("1/", "*/") # Month if expression_parts[5].startswith("1/"): expression_parts[5] = expression_parts[5].replace("1/", "*/") # DOW if expression_parts[6].startswith("1/"): expression_parts[6] = expression_parts[6].replace("1/", "*/") # handle DayOfWeekStartIndexZero option where SUN=1 rather than SUN=0 if self._options.day_of_week_start_index_zero is False: expression_parts[5] = self.decrease_days_of_week(expression_parts[5]) if expression_parts[3] == "?": expression_parts[3] = "*" # convert SUN-SAT format to 0-6 format for day_number in self._cron_days: expression_parts[5] = expression_parts[5].upper().replace(self._cron_days[day_number], str(day_number)) # convert JAN-DEC format to 1-12 format for month_number in self._cron_months: expression_parts[4] = expression_parts[4].upper().replace( self._cron_months[month_number], str(month_number)) # convert 0 second to (empty) if expression_parts[0] == "0": expression_parts[0] = '' # Loop through all parts and apply global normalization length = len(expression_parts) for i in range(length): # convert all '*/1' to '*' if expression_parts[i] == "*/1": expression_parts[i] = "*" """ Convert Month,DOW,Year step values with a starting value (i.e. not '*') to between expressions. This allows us to reuse the between expression handling for step values. For Example: - month part '3/2' will be converted to '3-12/2' (every 2 months between March and December) - DOW part '3/2' will be converted to '3-6/2' (every 2 days between Tuesday and Saturday) """ if "/" in expression_parts[i] and any(exp in expression_parts[i] for exp in ['*', '-', ',']) is False: choices = { 4: "12", 5: "6", 6: "9999" } step_range_through = choices.get(i) if step_range_through is not None: parts = expression_parts[i].split('/') expression_parts[i] = "{0}-{1}/{2}".format(parts[0], step_range_through, parts[1])
python
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 """ # 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_parts[ 0].replace("0/", "*/") # seconds if expression_parts[1].startswith("0/"): expression_parts[1] = expression_parts[ 1].replace("0/", "*/") # minutes if expression_parts[2].startswith("0/"): expression_parts[2] = expression_parts[ 2].replace("0/", "*/") # hours if expression_parts[3].startswith("1/"): expression_parts[3] = expression_parts[3].replace("1/", "*/") # DOM if expression_parts[4].startswith("1/"): expression_parts[4] = expression_parts[ 4].replace("1/", "*/") # Month if expression_parts[5].startswith("1/"): expression_parts[5] = expression_parts[5].replace("1/", "*/") # DOW if expression_parts[6].startswith("1/"): expression_parts[6] = expression_parts[6].replace("1/", "*/") # handle DayOfWeekStartIndexZero option where SUN=1 rather than SUN=0 if self._options.day_of_week_start_index_zero is False: expression_parts[5] = self.decrease_days_of_week(expression_parts[5]) if expression_parts[3] == "?": expression_parts[3] = "*" # convert SUN-SAT format to 0-6 format for day_number in self._cron_days: expression_parts[5] = expression_parts[5].upper().replace(self._cron_days[day_number], str(day_number)) # convert JAN-DEC format to 1-12 format for month_number in self._cron_months: expression_parts[4] = expression_parts[4].upper().replace( self._cron_months[month_number], str(month_number)) # convert 0 second to (empty) if expression_parts[0] == "0": expression_parts[0] = '' # Loop through all parts and apply global normalization length = len(expression_parts) for i in range(length): # convert all '*/1' to '*' if expression_parts[i] == "*/1": expression_parts[i] = "*" """ Convert Month,DOW,Year step values with a starting value (i.e. not '*') to between expressions. This allows us to reuse the between expression handling for step values. For Example: - month part '3/2' will be converted to '3-12/2' (every 2 months between March and December) - DOW part '3/2' will be converted to '3-6/2' (every 2 days between Tuesday and Saturday) """ if "/" in expression_parts[i] and any(exp in expression_parts[i] for exp in ['*', '-', ',']) is False: choices = { 4: "12", 5: "6", 6: "9999" } step_range_through = choices.get(i) if step_range_through is not None: parts = expression_parts[i].split('/') expression_parts[i] = "{0}-{1}/{2}".format(parts[0], step_range_through, parts[1])
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
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionParser.py#L121-L206
ciena/afkak
tools/gentravis.py
group_envs
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-unit', 'py27-lint']) [('py27', 'unit', ['py27-unit', 'py27-lint'])] """ 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, envs) for (envpy, category), envs in groups.items())
python
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-unit', 'py27-lint']) [('py27', 'unit', ['py27-unit', 'py27-lint'])] """ 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, envs) for (envpy, category), envs in groups.items())
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-unit', 'py27-lint']) [('py27', 'unit', ['py27-unit', 'py27-lint'])]
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/tools/gentravis.py#L70-L95
ciena/afkak
afkak/kafkacodec.py
create_message
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`` """ 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)
python
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`` """ 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)
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``
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L580-L592
ciena/afkak
afkak/kafkacodec.py
create_gzip_message
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 """ encoded_message_set = KafkaCodec._encode_message_set(message_set) gzipped = gzip_encode(encoded_message_set) return Message(0, CODEC_GZIP, None, gzipped)
python
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 """ encoded_message_set = KafkaCodec._encode_message_set(message_set) gzipped = gzip_encode(encoded_message_set) return Message(0, CODEC_GZIP, None, gzipped)
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
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L595-L607
ciena/afkak
afkak/kafkacodec.py
create_snappy_message
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 """ encoded_message_set = KafkaCodec._encode_message_set(message_set) snapped = snappy_encode(encoded_message_set) return Message(0, CODEC_SNAPPY, None, snapped)
python
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 """ encoded_message_set = KafkaCodec._encode_message_set(message_set) snapped = snappy_encode(encoded_message_set) return Message(0, CODEC_SNAPPY, None, snapped)
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
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L610-L621
ciena/afkak
afkak/kafkacodec.py
create_message_set
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 of the constants: - `afkak.CODEC_NONE` - `afkak.CODEC_GZIP` - `afkak.CODEC_SNAPPY` :raises: :exc:`UnsupportedCodecError` for an unsupported codec """ 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_message(msglist)] else: raise UnsupportedCodecError("Codec 0x%02x unsupported" % codec)
python
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 of the constants: - `afkak.CODEC_NONE` - `afkak.CODEC_GZIP` - `afkak.CODEC_SNAPPY` :raises: :exc:`UnsupportedCodecError` for an unsupported codec """ 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_message(msglist)] else: raise UnsupportedCodecError("Codec 0x%02x unsupported" % codec)
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 of the constants: - `afkak.CODEC_NONE` - `afkak.CODEC_GZIP` - `afkak.CODEC_SNAPPY` :raises: :exc:`UnsupportedCodecError` for an unsupported codec
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L624-L652
ciena/afkak
afkak/kafkacodec.py
KafkaCodec._encode_message_header
def _encode_message_header(cls, client_id, correlation_id, request_key, api_version=0): """ Encode the common request envelope """ return (struct.pack('>hhih', request_key, # ApiKey api_version, # ApiVersion correlation_id, # CorrelationId len(client_id)) + # ClientId size client_id)
python
def _encode_message_header(cls, client_id, correlation_id, request_key, api_version=0): """ Encode the common request envelope """ return (struct.pack('>hhih', request_key, # ApiKey api_version, # ApiVersion correlation_id, # CorrelationId len(client_id)) + # ClientId size client_id)
Encode the common request envelope
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L61-L71
ciena/afkak
afkak/kafkacodec.py
KafkaCodec._encode_message_set
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 """ 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))) message_set.append(encoded_message) offset += incr return b''.join(message_set)
python
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 """ 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))) message_set.append(encoded_message) offset += incr return b''.join(message_set)
Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed. Format:: MessageSet => [Offset MessageSize Message] Offset => int64 MessageSize => int32
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L74-L93
ciena/afkak
afkak/kafkacodec.py
KafkaCodec._encode_message
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 Key => bytes Value => bytes """ 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) + msg else: raise ProtocolError("Unexpected magic number: %d" % message.magic) return msg
python
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 Key => bytes Value => bytes """ 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) + msg else: raise ProtocolError("Unexpected magic number: %d" % message.magic) return msg
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 Key => bytes Value => bytes
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L96-L118
ciena/afkak
afkak/kafkacodec.py
KafkaCodec.encode_produce_request
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+: waits for this many number of replicas to sync -1: waits for all replicas to be in sync :param int timeout: Maximum time the server will wait for acks from replicas. This is _not_ a socket timeout. """ 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, correlation_id, KafkaCodec.PRODUCE_KEY) message += struct.pack('>hii', acks, timeout, len(grouped_payloads)) for topic, topic_payloads in grouped_payloads.items(): message += write_short_ascii(topic) message += struct.pack('>i', len(topic_payloads)) for partition, payload in topic_payloads.items(): msg_set = KafkaCodec._encode_message_set(payload.messages) message += struct.pack('>ii', partition, len(msg_set)) message += msg_set return message
python
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+: waits for this many number of replicas to sync -1: waits for all replicas to be in sync :param int timeout: Maximum time the server will wait for acks from replicas. This is _not_ a socket timeout. """ 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, correlation_id, KafkaCodec.PRODUCE_KEY) message += struct.pack('>hii', acks, timeout, len(grouped_payloads)) for topic, topic_payloads in grouped_payloads.items(): message += write_short_ascii(topic) message += struct.pack('>i', len(topic_payloads)) for partition, payload in topic_payloads.items(): msg_set = KafkaCodec._encode_message_set(payload.messages) message += struct.pack('>ii', partition, len(msg_set)) message += msg_set return message
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+: waits for this many number of replicas to sync -1: waits for all replicas to be in sync :param int timeout: Maximum time the server will wait for acks from replicas. This is _not_ a socket timeout.
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L206-L247
ciena/afkak
afkak/kafkacodec.py
KafkaCodec.decode_produce_response
def decode_produce_response(cls, data): """ Decode bytes to a ProduceResponse :param bytes data: bytes to decode :returns: iterable of `afkak.common.ProduceResponse` """ ((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): ((partition, error, offset), cur) = relative_unpack('>ihq', data, cur) yield ProduceResponse(topic, partition, error, offset)
python
def decode_produce_response(cls, data): """ Decode bytes to a ProduceResponse :param bytes data: bytes to decode :returns: iterable of `afkak.common.ProduceResponse` """ ((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): ((partition, error, offset), cur) = relative_unpack('>ihq', data, cur) yield ProduceResponse(topic, partition, error, offset)
Decode bytes to a ProduceResponse :param bytes data: bytes to decode :returns: iterable of `afkak.common.ProduceResponse`
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L250-L265