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
croscon/fleaker
fleaker/marshmallow/fields/arrow.py
ArrowField._deserialize
def _deserialize(self, value, attr, data): """Deserializes a string into an Arrow object.""" if not self.context.get('convert_dates', True) or not value: return value value = super(ArrowField, self)._deserialize(value, attr, data) timezone = self.get_field_value('timezone') target = arrow.get(value) if timezone and text_type(target.to(timezone)) != text_type(target): raise ValidationError( "The provided datetime is not in the " "{} timezone.".format(timezone) ) return target
python
def _deserialize(self, value, attr, data): """Deserializes a string into an Arrow object.""" if not self.context.get('convert_dates', True) or not value: return value value = super(ArrowField, self)._deserialize(value, attr, data) timezone = self.get_field_value('timezone') target = arrow.get(value) if timezone and text_type(target.to(timezone)) != text_type(target): raise ValidationError( "The provided datetime is not in the " "{} timezone.".format(timezone) ) return target
Deserializes a string into an Arrow object.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/fields/arrow.py#L49-L64
croscon/fleaker
fleaker/peewee/fields/pendulum.py
PendulumDateTimeField.python_value
def python_value(self, value): """Return the value in the database as an Pendulum object. Returns: pendulum.Pendulum: An instance of Pendulum with the field filled in. """ value = super(PendulumDateTimeField, self).python_value(value) if isinstance(value, datetime.datetime): value = pendulum.instance(value) elif isinstance(value, datetime.date): value = pendulum.instance( datetime.datetime.combine( value, datetime.datetime.min.time() ) ) elif isinstance(value, string_types): value = pendulum.parse(value) return value
python
def python_value(self, value): """Return the value in the database as an Pendulum object. Returns: pendulum.Pendulum: An instance of Pendulum with the field filled in. """ value = super(PendulumDateTimeField, self).python_value(value) if isinstance(value, datetime.datetime): value = pendulum.instance(value) elif isinstance(value, datetime.date): value = pendulum.instance( datetime.datetime.combine( value, datetime.datetime.min.time() ) ) elif isinstance(value, string_types): value = pendulum.parse(value) return value
Return the value in the database as an Pendulum object. Returns: pendulum.Pendulum: An instance of Pendulum with the field filled in.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/fields/pendulum.py#L68-L88
croscon/fleaker
fleaker/peewee/fields/pendulum.py
PendulumDateTimeField.db_value
def db_value(self, value): """Convert the Pendulum instance to a datetime for saving in the db.""" if isinstance(value, pendulum.Pendulum): value = datetime.datetime( value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond, value.tzinfo ) return super(PendulumDateTimeField, self).db_value(value)
python
def db_value(self, value): """Convert the Pendulum instance to a datetime for saving in the db.""" if isinstance(value, pendulum.Pendulum): value = datetime.datetime( value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond, value.tzinfo ) return super(PendulumDateTimeField, self).db_value(value)
Convert the Pendulum instance to a datetime for saving in the db.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/fields/pendulum.py#L90-L98
mozilla-releng/mozapkpublisher
mozapkpublisher/check_rollout.py
check_rollout
def check_rollout(edits_service, package_name, days): """Check if package_name has a release on staged rollout for too long""" edit = edits_service.insert(body={}, packageName=package_name).execute() response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execute() releases = response['releases'] for release in releases: if release['status'] == 'inProgress': url = 'https://archive.mozilla.org/pub/mobile/releases/{}/SHA512SUMS'.format(release['name']) resp = requests.head(url) if resp.status_code != 200: if resp.status_code != 404: # 404 is expected for release candidates logger.warning("Could not check %s: %s", url, resp.status_code) continue age = time.time() - calendar.timegm(eu.parsedate(resp.headers['Last-Modified'])) if age >= days * DAY: yield release, age
python
def check_rollout(edits_service, package_name, days): """Check if package_name has a release on staged rollout for too long""" edit = edits_service.insert(body={}, packageName=package_name).execute() response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execute() releases = response['releases'] for release in releases: if release['status'] == 'inProgress': url = 'https://archive.mozilla.org/pub/mobile/releases/{}/SHA512SUMS'.format(release['name']) resp = requests.head(url) if resp.status_code != 200: if resp.status_code != 404: # 404 is expected for release candidates logger.warning("Could not check %s: %s", url, resp.status_code) continue age = time.time() - calendar.timegm(eu.parsedate(resp.headers['Last-Modified'])) if age >= days * DAY: yield release, age
Check if package_name has a release on staged rollout for too long
https://github.com/mozilla-releng/mozapkpublisher/blob/df61034220153cbb98da74c8ef6de637f9185e12/mozapkpublisher/check_rollout.py#L19-L34
croscon/fleaker
fleaker/marshmallow/json_schema.py
FleakerJSONSchema.generate_json_schema
def generate_json_schema(cls, schema, context=DEFAULT_DICT): """Generate a JSON Schema from a Marshmallow schema. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The path or pointer to the file to write this schema to. If not provided, the schema will be dumped to ``sys.stdout``. Returns: dict: The JSON schema in dictionary form. """ schema = cls._get_schema(schema) # Generate the JSON Schema return cls(context=context).dump(schema).data
python
def generate_json_schema(cls, schema, context=DEFAULT_DICT): """Generate a JSON Schema from a Marshmallow schema. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The path or pointer to the file to write this schema to. If not provided, the schema will be dumped to ``sys.stdout``. Returns: dict: The JSON schema in dictionary form. """ schema = cls._get_schema(schema) # Generate the JSON Schema return cls(context=context).dump(schema).data
Generate a JSON Schema from a Marshmallow schema. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The path or pointer to the file to write this schema to. If not provided, the schema will be dumped to ``sys.stdout``. Returns: dict: The JSON schema in dictionary form.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/json_schema.py#L96-L114
croscon/fleaker
fleaker/marshmallow/json_schema.py
FleakerJSONSchema.write_schema_to_file
def write_schema_to_file(cls, schema, file_pointer=stdout, folder=MISSING, context=DEFAULT_DICT): """Given a Marshmallow schema, create a JSON Schema for it. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The pointer to the file to write this schema to. If not provided, the schema will be dumped to ``sys.stdout``. folder (str, optional): The folder in which to save the JSON schema. The name of the schema file can be optionally controlled my the schema's ``Meta.json_schema_filename``. If that attribute is not set, the class's name will be used for the filename. If writing the schema to a specific file is desired, please pass in a ``file_pointer``. context (dict, optional): The Marshmallow context to be pushed to the schema generates the JSONSchema. Returns: dict: The JSON schema in dictionary form. """ schema = cls._get_schema(schema) json_schema = cls.generate_json_schema(schema, context=context) if folder: schema_filename = getattr( schema.Meta, 'json_schema_filename', '.'.join([schema.__class__.__name__, 'json']) ) json_path = os.path.join(folder, schema_filename) file_pointer = open(json_path, 'w') json.dump(json_schema, file_pointer, indent=2) return json_schema
python
def write_schema_to_file(cls, schema, file_pointer=stdout, folder=MISSING, context=DEFAULT_DICT): """Given a Marshmallow schema, create a JSON Schema for it. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The pointer to the file to write this schema to. If not provided, the schema will be dumped to ``sys.stdout``. folder (str, optional): The folder in which to save the JSON schema. The name of the schema file can be optionally controlled my the schema's ``Meta.json_schema_filename``. If that attribute is not set, the class's name will be used for the filename. If writing the schema to a specific file is desired, please pass in a ``file_pointer``. context (dict, optional): The Marshmallow context to be pushed to the schema generates the JSONSchema. Returns: dict: The JSON schema in dictionary form. """ schema = cls._get_schema(schema) json_schema = cls.generate_json_schema(schema, context=context) if folder: schema_filename = getattr( schema.Meta, 'json_schema_filename', '.'.join([schema.__class__.__name__, 'json']) ) json_path = os.path.join(folder, schema_filename) file_pointer = open(json_path, 'w') json.dump(json_schema, file_pointer, indent=2) return json_schema
Given a Marshmallow schema, create a JSON Schema for it. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The pointer to the file to write this schema to. If not provided, the schema will be dumped to ``sys.stdout``. folder (str, optional): The folder in which to save the JSON schema. The name of the schema file can be optionally controlled my the schema's ``Meta.json_schema_filename``. If that attribute is not set, the class's name will be used for the filename. If writing the schema to a specific file is desired, please pass in a ``file_pointer``. context (dict, optional): The Marshmallow context to be pushed to the schema generates the JSONSchema. Returns: dict: The JSON schema in dictionary form.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/json_schema.py#L117-L155
croscon/fleaker
fleaker/marshmallow/json_schema.py
FleakerJSONSchema._get_schema
def _get_schema(cls, schema): """Method that will fetch a Marshmallow schema flexibly. Args: schema (marshmallow.Schema|str): Either the schema class, an instance of a schema, or a Python path to a schema. Returns: marshmallow.Schema: The desired schema. Raises: TypeError: This is raised if the provided object isn't a Marshmallow schema. """ if isinstance(schema, string_types): schema = cls._get_object_from_python_path(schema) if isclass(schema): schema = schema() if not isinstance(schema, Schema): raise TypeError("The schema must be a path to a Marshmallow " "schema or a Marshmallow schema.") return schema
python
def _get_schema(cls, schema): """Method that will fetch a Marshmallow schema flexibly. Args: schema (marshmallow.Schema|str): Either the schema class, an instance of a schema, or a Python path to a schema. Returns: marshmallow.Schema: The desired schema. Raises: TypeError: This is raised if the provided object isn't a Marshmallow schema. """ if isinstance(schema, string_types): schema = cls._get_object_from_python_path(schema) if isclass(schema): schema = schema() if not isinstance(schema, Schema): raise TypeError("The schema must be a path to a Marshmallow " "schema or a Marshmallow schema.") return schema
Method that will fetch a Marshmallow schema flexibly. Args: schema (marshmallow.Schema|str): Either the schema class, an instance of a schema, or a Python path to a schema. Returns: marshmallow.Schema: The desired schema. Raises: TypeError: This is raised if the provided object isn't a Marshmallow schema.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/json_schema.py#L158-L182
croscon/fleaker
fleaker/marshmallow/json_schema.py
FleakerJSONSchema._get_object_from_python_path
def _get_object_from_python_path(python_path): """Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: TypeError: This is raised if the specified object isn't a Marshmallow schema. """ # Dissect the path python_path = python_path.split('.') module_path = python_path[:-1] object_class = python_path[-1] if isinstance(module_path, list): module_path = '.'.join(module_path) # Grab the object module = import_module(module_path) schema = getattr(module, object_class) if isclass(schema): schema = schema() return schema
python
def _get_object_from_python_path(python_path): """Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: TypeError: This is raised if the specified object isn't a Marshmallow schema. """ # Dissect the path python_path = python_path.split('.') module_path = python_path[:-1] object_class = python_path[-1] if isinstance(module_path, list): module_path = '.'.join(module_path) # Grab the object module = import_module(module_path) schema = getattr(module, object_class) if isclass(schema): schema = schema() return schema
Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: TypeError: This is raised if the specified object isn't a Marshmallow schema.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/json_schema.py#L185-L213
croscon/fleaker
fleaker/marshmallow/extension.py
MarshmallowAwareApp.post_create_app
def post_create_app(cls, app, **settings): """Automatically register and init the Flask Marshmallow extension. Args: app (flask.Flask): The application instance in which to initialize Flask Marshmallow upon. Kwargs: settings (dict): The settings passed to this method from the parent app. Returns: flask.Flask: The Flask application that was passed in. """ super(MarshmallowAwareApp, cls).post_create_app(app, **settings) marsh.init_app(app) return app
python
def post_create_app(cls, app, **settings): """Automatically register and init the Flask Marshmallow extension. Args: app (flask.Flask): The application instance in which to initialize Flask Marshmallow upon. Kwargs: settings (dict): The settings passed to this method from the parent app. Returns: flask.Flask: The Flask application that was passed in. """ super(MarshmallowAwareApp, cls).post_create_app(app, **settings) marsh.init_app(app) return app
Automatically register and init the Flask Marshmallow extension. Args: app (flask.Flask): The application instance in which to initialize Flask Marshmallow upon. Kwargs: settings (dict): The settings passed to this method from the parent app. Returns: flask.Flask: The Flask application that was passed in.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/extension.py#L37-L55
croscon/fleaker
fleaker/peewee/mixins/event.py
get_original_before_save
def get_original_before_save(sender, instance, created): """Event listener to get the original instance before it's saved.""" if not instance._meta.event_ready or created: return instance.get_original()
python
def get_original_before_save(sender, instance, created): """Event listener to get the original instance before it's saved.""" if not instance._meta.event_ready or created: return instance.get_original()
Event listener to get the original instance before it's saved.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L623-L628
croscon/fleaker
fleaker/peewee/mixins/event.py
post_save_event_listener
def post_save_event_listener(sender, instance, created): """Event listener to create creation and update events.""" if not instance._meta.event_ready: return if created: instance.create_creation_event() else: instance.create_update_event() # Reset the original key instance._original = None
python
def post_save_event_listener(sender, instance, created): """Event listener to create creation and update events.""" if not instance._meta.event_ready: return if created: instance.create_creation_event() else: instance.create_update_event() # Reset the original key instance._original = None
Event listener to create creation and update events.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L632-L643
croscon/fleaker
fleaker/peewee/mixins/event.py
validate_event_type
def validate_event_type(sender, event, created): """Verify that the Event's code is a valid one.""" if event.code not in sender.event_codes(): raise ValueError("The Event.code '{}' is not a valid Event " "code.".format(event.code))
python
def validate_event_type(sender, event, created): """Verify that the Event's code is a valid one.""" if event.code not in sender.event_codes(): raise ValueError("The Event.code '{}' is not a valid Event " "code.".format(event.code))
Verify that the Event's code is a valid one.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L732-L736
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.get_original
def get_original(self): """Get the original instance of this instance before it's updated. Returns: fleaker.peewee.EventMixin: The original instance of the model. """ pk_value = self._get_pk_value() if isinstance(pk_value, int) and not self._original: self._original = ( self.select().where(self.__class__.id == pk_value).get() ) return self._original
python
def get_original(self): """Get the original instance of this instance before it's updated. Returns: fleaker.peewee.EventMixin: The original instance of the model. """ pk_value = self._get_pk_value() if isinstance(pk_value, int) and not self._original: self._original = ( self.select().where(self.__class__.id == pk_value).get() ) return self._original
Get the original instance of this instance before it's updated. Returns: fleaker.peewee.EventMixin: The original instance of the model.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L398-L412
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.create_creation_event
def create_creation_event(self): """Parse the create message DSL to insert the data into the Event. Returns: fleaker.peewee.EventStorageMixin: A new Event instance with data put in it """ event = self.create_audit_event(code='AUDIT_CREATE') if self._meta.create_message: event.body = self._meta.create_message['message'] event.code = self._meta.create_message['code'] event.meta = self.parse_meta(self._meta.create_message['meta']) self.create_event_callback(event) event.save() return event
python
def create_creation_event(self): """Parse the create message DSL to insert the data into the Event. Returns: fleaker.peewee.EventStorageMixin: A new Event instance with data put in it """ event = self.create_audit_event(code='AUDIT_CREATE') if self._meta.create_message: event.body = self._meta.create_message['message'] event.code = self._meta.create_message['code'] event.meta = self.parse_meta(self._meta.create_message['meta']) self.create_event_callback(event) event.save() return event
Parse the create message DSL to insert the data into the Event. Returns: fleaker.peewee.EventStorageMixin: A new Event instance with data put in it
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L414-L432
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.create_update_event
def create_update_event(self): """Parse the update messages DSL to insert the data into the Event. Returns: list[fleaker.peewee.EventStorageMixin]: All the events that were created for the update. """ events = [] for fields, rules in iteritems(self._meta.update_messages): if not isinstance(fields, (list, tuple, set)): fields = (fields,) changed = any([ getattr(self, field) != getattr(self.get_original(), field) for field in fields ]) if changed: event = self.create_audit_event(code=rules['code']) event.body = rules['message'] event.meta = self.parse_meta(rules['meta']) events.append(event) self.update_event_callback(events) with db.database.atomic(): for event in events: event.save() return events
python
def create_update_event(self): """Parse the update messages DSL to insert the data into the Event. Returns: list[fleaker.peewee.EventStorageMixin]: All the events that were created for the update. """ events = [] for fields, rules in iteritems(self._meta.update_messages): if not isinstance(fields, (list, tuple, set)): fields = (fields,) changed = any([ getattr(self, field) != getattr(self.get_original(), field) for field in fields ]) if changed: event = self.create_audit_event(code=rules['code']) event.body = rules['message'] event.meta = self.parse_meta(rules['meta']) events.append(event) self.update_event_callback(events) with db.database.atomic(): for event in events: event.save() return events
Parse the update messages DSL to insert the data into the Event. Returns: list[fleaker.peewee.EventStorageMixin]: All the events that were created for the update.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L434-L464
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.create_deletion_event
def create_deletion_event(self): """Parse the delete message DSL to insert data into the Event. Return: Event: The Event with the relevant information put in it. """ event = self.create_audit_event(code='AUDIT_DELETE') if self._meta.delete_message: event.code = self._meta.delete_message['code'] event.body = self._meta.delete_message['message'] event.meta = self.parse_meta(self._meta.delete_message['meta']) self.delete_event_callback(event) event.save() return event
python
def create_deletion_event(self): """Parse the delete message DSL to insert data into the Event. Return: Event: The Event with the relevant information put in it. """ event = self.create_audit_event(code='AUDIT_DELETE') if self._meta.delete_message: event.code = self._meta.delete_message['code'] event.body = self._meta.delete_message['message'] event.meta = self.parse_meta(self._meta.delete_message['meta']) self.delete_event_callback(event) event.save() return event
Parse the delete message DSL to insert data into the Event. Return: Event: The Event with the relevant information put in it.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L466-L483
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.parse_meta
def parse_meta(self, meta): """Parses the meta field in the message, copies it's keys into a new dict and replaces the values, which should be attribute paths relative to the passed in object, with the current value at the end of that path. This function will run recursively when it encounters other dicts inside the meta dict. Args: meta (dict): The dictionary of mappings to pull structure of the meta from. Returns: dict: A copy of the keys from the meta dict with the values pulled from the paths. """ res = {} for key, val in meta.items(): if not val: continue elif isinstance(val, dict): res[key] = self.parse_meta(val) elif val.startswith('current_user.'): res[key] = self.get_path_attribute(current_user, val) elif val.startswith('original.'): res[key] = self.get_path_attribute(self.get_original(), val) else: res[key] = self.get_path_attribute(self, val) return res
python
def parse_meta(self, meta): """Parses the meta field in the message, copies it's keys into a new dict and replaces the values, which should be attribute paths relative to the passed in object, with the current value at the end of that path. This function will run recursively when it encounters other dicts inside the meta dict. Args: meta (dict): The dictionary of mappings to pull structure of the meta from. Returns: dict: A copy of the keys from the meta dict with the values pulled from the paths. """ res = {} for key, val in meta.items(): if not val: continue elif isinstance(val, dict): res[key] = self.parse_meta(val) elif val.startswith('current_user.'): res[key] = self.get_path_attribute(current_user, val) elif val.startswith('original.'): res[key] = self.get_path_attribute(self.get_original(), val) else: res[key] = self.get_path_attribute(self, val) return res
Parses the meta field in the message, copies it's keys into a new dict and replaces the values, which should be attribute paths relative to the passed in object, with the current value at the end of that path. This function will run recursively when it encounters other dicts inside the meta dict. Args: meta (dict): The dictionary of mappings to pull structure of the meta from. Returns: dict: A copy of the keys from the meta dict with the values pulled from the paths.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L485-L515
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.get_path_attribute
def get_path_attribute(obj, path): """Given a path like `related_record.related_record2.id`, this method will be able to pull the value of ID from that object, returning None if it doesn't exist. Args: obj (fleaker.db.Model): The object to attempt to pull the value from path (str): The path to follow to pull the value from Returns: (int|str|None): The value at the end of the path. None if it doesn't exist at any point in the path. """ # Strip out ignored keys passed in path = path.replace('original.', '').replace('current_user.', '') attr_parts = path.split('.') res = obj try: for part in attr_parts: try: res = getattr(res, part) except AttributeError: res = getattr(res.get(), part) except (peewee.DoesNotExist, AttributeError): return None return res
python
def get_path_attribute(obj, path): """Given a path like `related_record.related_record2.id`, this method will be able to pull the value of ID from that object, returning None if it doesn't exist. Args: obj (fleaker.db.Model): The object to attempt to pull the value from path (str): The path to follow to pull the value from Returns: (int|str|None): The value at the end of the path. None if it doesn't exist at any point in the path. """ # Strip out ignored keys passed in path = path.replace('original.', '').replace('current_user.', '') attr_parts = path.split('.') res = obj try: for part in attr_parts: try: res = getattr(res, part) except AttributeError: res = getattr(res.get(), part) except (peewee.DoesNotExist, AttributeError): return None return res
Given a path like `related_record.related_record2.id`, this method will be able to pull the value of ID from that object, returning None if it doesn't exist. Args: obj (fleaker.db.Model): The object to attempt to pull the value from path (str): The path to follow to pull the value from Returns: (int|str|None): The value at the end of the path. None if it doesn't exist at any point in the path.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L518-L550
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.copy_foreign_keys
def copy_foreign_keys(self, event): """Copies possible foreign key values from the object into the Event, skipping common keys like modified and created. Args: event (Event): The Event instance to copy the FKs into obj (fleaker.db.Model): The object to pull the values from """ event_keys = set(event._meta.fields.keys()) obj_keys = self._meta.fields.keys() matching_keys = event_keys.intersection(obj_keys) for key in matching_keys: # Skip created_by because that will always be the current_user # for the Event. if key == 'created_by': continue # Skip anything that isn't a FK if not isinstance(self._meta.fields[key], peewee.ForeignKeyField): continue setattr(event, key, getattr(self, key)) # Attempt to set the obj's ID in the correct FK field on Event, if it # exists. If this conflicts with desired behavior, handle this in the # respective callback. This does rely on the FK matching the lower case # version of the class name and that the event isn't trying to delete # the current record, becuase that ends badly. possible_key = self.__class__.__name__.lower() if possible_key in event_keys and event.code != 'AUDIT_DELETE': setattr(event, possible_key, self)
python
def copy_foreign_keys(self, event): """Copies possible foreign key values from the object into the Event, skipping common keys like modified and created. Args: event (Event): The Event instance to copy the FKs into obj (fleaker.db.Model): The object to pull the values from """ event_keys = set(event._meta.fields.keys()) obj_keys = self._meta.fields.keys() matching_keys = event_keys.intersection(obj_keys) for key in matching_keys: # Skip created_by because that will always be the current_user # for the Event. if key == 'created_by': continue # Skip anything that isn't a FK if not isinstance(self._meta.fields[key], peewee.ForeignKeyField): continue setattr(event, key, getattr(self, key)) # Attempt to set the obj's ID in the correct FK field on Event, if it # exists. If this conflicts with desired behavior, handle this in the # respective callback. This does rely on the FK matching the lower case # version of the class name and that the event isn't trying to delete # the current record, becuase that ends badly. possible_key = self.__class__.__name__.lower() if possible_key in event_keys and event.code != 'AUDIT_DELETE': setattr(event, possible_key, self)
Copies possible foreign key values from the object into the Event, skipping common keys like modified and created. Args: event (Event): The Event instance to copy the FKs into obj (fleaker.db.Model): The object to pull the values from
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L552-L584
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.create_audit_event
def create_audit_event(self, code='AUDIT'): """Creates a generic auditing Event logging the changes between saves and the initial data in creates. Kwargs: code (str): The code to set the new Event to. Returns: Event: A new event with relevant info inserted into it """ event = self._meta.event_model( code=code, model=self.__class__.__name__, ) # Use the logged in User, if possible if current_user: event.created_by = current_user.get_id() self.copy_foreign_keys(event) self.populate_audit_fields(event) return event
python
def create_audit_event(self, code='AUDIT'): """Creates a generic auditing Event logging the changes between saves and the initial data in creates. Kwargs: code (str): The code to set the new Event to. Returns: Event: A new event with relevant info inserted into it """ event = self._meta.event_model( code=code, model=self.__class__.__name__, ) # Use the logged in User, if possible if current_user: event.created_by = current_user.get_id() self.copy_foreign_keys(event) self.populate_audit_fields(event) return event
Creates a generic auditing Event logging the changes between saves and the initial data in creates. Kwargs: code (str): The code to set the new Event to. Returns: Event: A new event with relevant info inserted into it
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L586-L608
croscon/fleaker
fleaker/peewee/mixins/event.py
EventMixin.populate_audit_fields
def populate_audit_fields(self, event): """Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated model """ event.updated = self._data event.original = self.get_original()._data
python
def populate_audit_fields(self, event): """Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated model """ event.updated = self._data event.original = self.get_original()._data
Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated model
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L610-L619
croscon/fleaker
fleaker/peewee/mixins/event.py
EventStorageMixin.formatted_message
def formatted_message(self): """Method that will return the formatted message for the event. This formatting is done with Jinja and the template text is stored in the ``body`` attribute. The template is supplied the following variables, as well as the built in Flask ones: - ``event``: This is the event instance that this method belongs to. - ``meta``: This is a dictionary of cached values that have been stored when the event was created based upon the event's DSL. - ``original``: This is a dump of the instance before the instance was updated. - ``updated``: This is a dump of the instance after it was updated. - ``version``: This is the version of the event DSL. This property is cached because Jinja rendering is slower than raw Python string formatting. """ return render_template_string( self.body, event=self, meta=self.meta, original=self.original, updated=self.updated, version=self.version, )
python
def formatted_message(self): """Method that will return the formatted message for the event. This formatting is done with Jinja and the template text is stored in the ``body`` attribute. The template is supplied the following variables, as well as the built in Flask ones: - ``event``: This is the event instance that this method belongs to. - ``meta``: This is a dictionary of cached values that have been stored when the event was created based upon the event's DSL. - ``original``: This is a dump of the instance before the instance was updated. - ``updated``: This is a dump of the instance after it was updated. - ``version``: This is the version of the event DSL. This property is cached because Jinja rendering is slower than raw Python string formatting. """ return render_template_string( self.body, event=self, meta=self.meta, original=self.original, updated=self.updated, version=self.version, )
Method that will return the formatted message for the event. This formatting is done with Jinja and the template text is stored in the ``body`` attribute. The template is supplied the following variables, as well as the built in Flask ones: - ``event``: This is the event instance that this method belongs to. - ``meta``: This is a dictionary of cached values that have been stored when the event was created based upon the event's DSL. - ``original``: This is a dump of the instance before the instance was updated. - ``updated``: This is a dump of the instance after it was updated. - ``version``: This is the version of the event DSL. This property is cached because Jinja rendering is slower than raw Python string formatting.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/event.py#L695-L720
croscon/fleaker
fleaker/peewee/mixins/time/base.py
CreatedMixin._get_cached_time
def _get_cached_time(self): """Method that will allow for consistent modified and archived timestamps. Returns: self.Meta.datetime: This method will return a datetime that is compatible with the current class's datetime library. """ if not self._cached_time: self._cached_time = self._meta.datetime.utcnow() return self._cached_time
python
def _get_cached_time(self): """Method that will allow for consistent modified and archived timestamps. Returns: self.Meta.datetime: This method will return a datetime that is compatible with the current class's datetime library. """ if not self._cached_time: self._cached_time = self._meta.datetime.utcnow() return self._cached_time
Method that will allow for consistent modified and archived timestamps. Returns: self.Meta.datetime: This method will return a datetime that is compatible with the current class's datetime library.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/time/base.py#L77-L88
mozilla-releng/mozapkpublisher
mozapkpublisher/common/store_l10n.py
_get_list_of_completed_locales
def _get_list_of_completed_locales(product, channel): """ Get all the translated locales supported by Google play So, locale unsupported by Google play won't be downloaded Idem for not translated locale """ return utils.load_json_url(_ALL_LOCALES_URL.format(product=product, channel=channel))
python
def _get_list_of_completed_locales(product, channel): """ Get all the translated locales supported by Google play So, locale unsupported by Google play won't be downloaded Idem for not translated locale """ return utils.load_json_url(_ALL_LOCALES_URL.format(product=product, channel=channel))
Get all the translated locales supported by Google play So, locale unsupported by Google play won't be downloaded Idem for not translated locale
https://github.com/mozilla-releng/mozapkpublisher/blob/df61034220153cbb98da74c8ef6de637f9185e12/mozapkpublisher/common/store_l10n.py#L107-L112
croscon/fleaker
fleaker/marshmallow/fields/mixin.py
FleakerFieldMixin.get_field_value
def get_field_value(self, key, default=MISSING): """Method to fetch a value from either the fields metadata or the schemas context, in that order. Args: key (str): The name of the key to grab the value for. Keyword Args: default (object, optional): If the value doesn't exist in the schema's ``context`` or the field's ``metadata``, this value will be returned. By default this will be ``MISSING``. Returns: object: This will be the correct value to use given the parameters. """ meta_value = self.metadata.get(key) context_value = self.context.get(key) if context_value is not None: return context_value elif meta_value is not None: return meta_value return default
python
def get_field_value(self, key, default=MISSING): """Method to fetch a value from either the fields metadata or the schemas context, in that order. Args: key (str): The name of the key to grab the value for. Keyword Args: default (object, optional): If the value doesn't exist in the schema's ``context`` or the field's ``metadata``, this value will be returned. By default this will be ``MISSING``. Returns: object: This will be the correct value to use given the parameters. """ meta_value = self.metadata.get(key) context_value = self.context.get(key) if context_value is not None: return context_value elif meta_value is not None: return meta_value return default
Method to fetch a value from either the fields metadata or the schemas context, in that order. Args: key (str): The name of the key to grab the value for. Keyword Args: default (object, optional): If the value doesn't exist in the schema's ``context`` or the field's ``metadata``, this value will be returned. By default this will be ``MISSING``. Returns: object: This will be the correct value to use given the parameters.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/fields/mixin.py#L10-L33
croscon/fleaker
fleaker/peewee/model.py
Model.get_by_id
def get_by_id(cls, record_id, execute=True): """Return a single instance of the model queried by ID. Args: record_id (int): Integer representation of the ID to query on. Keyword Args: execute (bool, optional): Should this method execute the query or return a query object for further manipulation? Returns: cls | :py:class:`peewee.SelectQuery`: If ``execute`` is ``True``, the query is executed, otherwise a query is returned. Raises: :py:class:`peewee.DoesNotExist`: Raised if a record with that ID doesn't exist. """ query = cls.base_query().where(cls.id == record_id) if execute: return query.get() return query
python
def get_by_id(cls, record_id, execute=True): """Return a single instance of the model queried by ID. Args: record_id (int): Integer representation of the ID to query on. Keyword Args: execute (bool, optional): Should this method execute the query or return a query object for further manipulation? Returns: cls | :py:class:`peewee.SelectQuery`: If ``execute`` is ``True``, the query is executed, otherwise a query is returned. Raises: :py:class:`peewee.DoesNotExist`: Raised if a record with that ID doesn't exist. """ query = cls.base_query().where(cls.id == record_id) if execute: return query.get() return query
Return a single instance of the model queried by ID. Args: record_id (int): Integer representation of the ID to query on. Keyword Args: execute (bool, optional): Should this method execute the query or return a query object for further manipulation? Returns: cls | :py:class:`peewee.SelectQuery`: If ``execute`` is ``True``, the query is executed, otherwise a query is returned. Raises: :py:class:`peewee.DoesNotExist`: Raised if a record with that ID doesn't exist.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/model.py#L133-L158
croscon/fleaker
fleaker/peewee/model.py
Model.update_instance
def update_instance(self, data): """Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is raised if a key in the ``data`` isn't a field on the model. """ for key, val in iteritems(data): if not hasattr(self, key): raise AttributeError( "No field named {key} for model {model}".format( key=key, model=self.__class__.__name__ ) ) setattr(self, key, val) self.save() return self
python
def update_instance(self, data): """Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is raised if a key in the ``data`` isn't a field on the model. """ for key, val in iteritems(data): if not hasattr(self, key): raise AttributeError( "No field named {key} for model {model}".format( key=key, model=self.__class__.__name__ ) ) setattr(self, key, val) self.save() return self
Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is raised if a key in the ``data`` isn't a field on the model.
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/model.py#L160-L186
mardix/flask-recaptcha
flask_recaptcha.py
ReCaptcha.get_code
def get_code(self): """ Returns the new ReCaptcha code :return: """ return "" if not self.is_enabled else (""" <script src='//www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{SITE_KEY}" data-theme="{THEME}" data-type="{TYPE}" data-size="{SIZE}"\ data-tabindex="{TABINDEX}"></div> """.format(SITE_KEY=self.site_key, THEME=self.theme, TYPE=self.type, SIZE=self.size, TABINDEX=self.tabindex))
python
def get_code(self): """ Returns the new ReCaptcha code :return: """ return "" if not self.is_enabled else (""" <script src='//www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{SITE_KEY}" data-theme="{THEME}" data-type="{TYPE}" data-size="{SIZE}"\ data-tabindex="{TABINDEX}"></div> """.format(SITE_KEY=self.site_key, THEME=self.theme, TYPE=self.type, SIZE=self.size, TABINDEX=self.tabindex))
Returns the new ReCaptcha code :return:
https://github.com/mardix/flask-recaptcha/blob/bf1dbb326fa1df0c3d290e74faef712011d15623/flask_recaptcha.py#L61-L70
pytest-dev/pytest-xprocess
xprocess.py
XProcess.ensure
def ensure(self, name, preparefunc, restart=False): """ returns (PID, logfile) from a newly started or already running process. @param name: name of the external process, used for caching info across test runs. @param preparefunc: A subclass of ProcessStarter. @param restart: force restarting the process if it is running. @return: (PID, logfile) logfile will be seeked to the end if the server was running, otherwise seeked to the line after where the waitpattern matched. """ from subprocess import Popen, STDOUT info = self.getinfo(name) if not restart and not info.isrunning(): restart = True if restart: if info.pid is not None: info.terminate() controldir = info.controldir.ensure(dir=1) #controldir.remove() preparefunc = CompatStarter.wrap(preparefunc) starter = preparefunc(controldir, self) args = [str(x) for x in starter.args] self.log.debug("%s$ %s", controldir, " ".join(args)) stdout = open(str(info.logpath), "wb", 0) kwargs = {'env': starter.env} if sys.platform == "win32": kwargs["startupinfo"] = sinfo = std.subprocess.STARTUPINFO() if sys.version_info >= (2,7): sinfo.dwFlags |= std.subprocess.STARTF_USESHOWWINDOW sinfo.wShowWindow |= std.subprocess.SW_HIDE else: kwargs["close_fds"] = True kwargs["preexec_fn"] = os.setpgrp # no CONTROL-C popen = Popen(args, cwd=str(controldir), stdout=stdout, stderr=STDOUT, **kwargs) info.pid = pid = popen.pid info.pidpath.write(str(pid)) self.log.debug("process %r started pid=%s", name, pid) stdout.close() f = info.logpath.open() if not restart: f.seek(0, 2) else: if not starter.wait(f): raise RuntimeError("Could not start process %s" % name) self.log.debug("%s process startup detected", name) logfiles = self.config.__dict__.setdefault("_extlogfiles", {}) logfiles[name] = f self.getinfo(name) return info.pid, info.logpath
python
def ensure(self, name, preparefunc, restart=False): """ returns (PID, logfile) from a newly started or already running process. @param name: name of the external process, used for caching info across test runs. @param preparefunc: A subclass of ProcessStarter. @param restart: force restarting the process if it is running. @return: (PID, logfile) logfile will be seeked to the end if the server was running, otherwise seeked to the line after where the waitpattern matched. """ from subprocess import Popen, STDOUT info = self.getinfo(name) if not restart and not info.isrunning(): restart = True if restart: if info.pid is not None: info.terminate() controldir = info.controldir.ensure(dir=1) #controldir.remove() preparefunc = CompatStarter.wrap(preparefunc) starter = preparefunc(controldir, self) args = [str(x) for x in starter.args] self.log.debug("%s$ %s", controldir, " ".join(args)) stdout = open(str(info.logpath), "wb", 0) kwargs = {'env': starter.env} if sys.platform == "win32": kwargs["startupinfo"] = sinfo = std.subprocess.STARTUPINFO() if sys.version_info >= (2,7): sinfo.dwFlags |= std.subprocess.STARTF_USESHOWWINDOW sinfo.wShowWindow |= std.subprocess.SW_HIDE else: kwargs["close_fds"] = True kwargs["preexec_fn"] = os.setpgrp # no CONTROL-C popen = Popen(args, cwd=str(controldir), stdout=stdout, stderr=STDOUT, **kwargs) info.pid = pid = popen.pid info.pidpath.write(str(pid)) self.log.debug("process %r started pid=%s", name, pid) stdout.close() f = info.logpath.open() if not restart: f.seek(0, 2) else: if not starter.wait(f): raise RuntimeError("Could not start process %s" % name) self.log.debug("%s process startup detected", name) logfiles = self.config.__dict__.setdefault("_extlogfiles", {}) logfiles[name] = f self.getinfo(name) return info.pid, info.logpath
returns (PID, logfile) from a newly started or already running process. @param name: name of the external process, used for caching info across test runs. @param preparefunc: A subclass of ProcessStarter. @param restart: force restarting the process if it is running. @return: (PID, logfile) logfile will be seeked to the end if the server was running, otherwise seeked to the line after where the waitpattern matched.
https://github.com/pytest-dev/pytest-xprocess/blob/c3ee760b02dce2d0eed960b3ab0e28379853c3ef/xprocess.py#L78-L135
pytest-dev/pytest-xprocess
xprocess.py
ProcessStarter.wait
def wait(self, log_file): "Wait until the process is ready." lines = map(self.log_line, self.filter_lines(self.get_lines(log_file))) return any( std.re.search(self.pattern, line) for line in lines )
python
def wait(self, log_file): "Wait until the process is ready." lines = map(self.log_line, self.filter_lines(self.get_lines(log_file))) return any( std.re.search(self.pattern, line) for line in lines )
Wait until the process is ready.
https://github.com/pytest-dev/pytest-xprocess/blob/c3ee760b02dce2d0eed960b3ab0e28379853c3ef/xprocess.py#L188-L194
pytest-dev/pytest-xprocess
xprocess.py
CompatStarter.prep
def prep(self, wait, args, env=None): """ Given the return value of a preparefunc, prepare this CompatStarter. """ self.pattern = wait self.env = env self.args = args # wait is a function, supersedes the default behavior if callable(wait): self.wait = lambda lines: wait()
python
def prep(self, wait, args, env=None): """ Given the return value of a preparefunc, prepare this CompatStarter. """ self.pattern = wait self.env = env self.args = args # wait is a function, supersedes the default behavior if callable(wait): self.wait = lambda lines: wait()
Given the return value of a preparefunc, prepare this CompatStarter.
https://github.com/pytest-dev/pytest-xprocess/blob/c3ee760b02dce2d0eed960b3ab0e28379853c3ef/xprocess.py#L227-L238
pytest-dev/pytest-xprocess
xprocess.py
CompatStarter.wrap
def wrap(self, starter_cls): """ If starter_cls is not a ProcessStarter, assume it's the legacy preparefunc and return it bound to a CompatStarter. """ if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter): return starter_cls depr_msg = 'Pass a ProcessStarter for preparefunc' warnings.warn(depr_msg, DeprecationWarning, stacklevel=3) return functools.partial(CompatStarter, starter_cls)
python
def wrap(self, starter_cls): """ If starter_cls is not a ProcessStarter, assume it's the legacy preparefunc and return it bound to a CompatStarter. """ if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter): return starter_cls depr_msg = 'Pass a ProcessStarter for preparefunc' warnings.warn(depr_msg, DeprecationWarning, stacklevel=3) return functools.partial(CompatStarter, starter_cls)
If starter_cls is not a ProcessStarter, assume it's the legacy preparefunc and return it bound to a CompatStarter.
https://github.com/pytest-dev/pytest-xprocess/blob/c3ee760b02dce2d0eed960b3ab0e28379853c3ef/xprocess.py#L241-L250
Salamek/huawei-lte-api
huawei_lte_api/api/Monitoring.py
Monitoring.set_start_date
def set_start_date(self, start_day: int, data_limit: str, month_threshold: int): """ Sets network usage alarm for LTE :param start_day: number of day when monitoring starts :param data_limit: Maximal data limit as string eg.: 1000MB or 1GB and so on :param month_threshold: Alarm threshold in % as int number eg.: 90 :return: dict """ return self._connection.post('monitoring/start_date', OrderedDict(( ('StartDay', start_day), ('DataLimit', data_limit), ('MonthThreshold', month_threshold), ('SetMonthData', 1) )))
python
def set_start_date(self, start_day: int, data_limit: str, month_threshold: int): """ Sets network usage alarm for LTE :param start_day: number of day when monitoring starts :param data_limit: Maximal data limit as string eg.: 1000MB or 1GB and so on :param month_threshold: Alarm threshold in % as int number eg.: 90 :return: dict """ return self._connection.post('monitoring/start_date', OrderedDict(( ('StartDay', start_day), ('DataLimit', data_limit), ('MonthThreshold', month_threshold), ('SetMonthData', 1) )))
Sets network usage alarm for LTE :param start_day: number of day when monitoring starts :param data_limit: Maximal data limit as string eg.: 1000MB or 1GB and so on :param month_threshold: Alarm threshold in % as int number eg.: 90 :return: dict
https://github.com/Salamek/huawei-lte-api/blob/005655b9c5ba5853263ae7192db255ce069dff08/huawei_lte_api/api/Monitoring.py#L21-L34
kmadac/bitstamp-python-client
bitstamp/client.py
BaseClient._get
def _get(self, *args, **kwargs): """ Make a GET request. """ return self._request(requests.get, *args, **kwargs)
python
def _get(self, *args, **kwargs): """ Make a GET request. """ return self._request(requests.get, *args, **kwargs)
Make a GET request.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L35-L39
kmadac/bitstamp-python-client
bitstamp/client.py
BaseClient._post
def _post(self, *args, **kwargs): """ Make a POST request. """ data = self._default_data() data.update(kwargs.get('data') or {}) kwargs['data'] = data return self._request(requests.post, *args, **kwargs)
python
def _post(self, *args, **kwargs): """ Make a POST request. """ data = self._default_data() data.update(kwargs.get('data') or {}) kwargs['data'] = data return self._request(requests.post, *args, **kwargs)
Make a POST request.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L41-L48
kmadac/bitstamp-python-client
bitstamp/client.py
BaseClient._construct_url
def _construct_url(self, url, base, quote): """ Adds the orderbook to the url if base and quote are specified. """ if not base and not quote: return url else: url = url + base.lower() + quote.lower() + "/" return url
python
def _construct_url(self, url, base, quote): """ Adds the orderbook to the url if base and quote are specified. """ if not base and not quote: return url else: url = url + base.lower() + quote.lower() + "/" return url
Adds the orderbook to the url if base and quote are specified.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L56-L64
kmadac/bitstamp-python-client
bitstamp/client.py
BaseClient._request
def _request(self, func, url, version=1, *args, **kwargs): """ Make a generic request, adding in any proxy defined by the instance. Raises a ``requests.HTTPError`` if the response status isn't 200, and raises a :class:`BitstampError` if the response contains a json encoded error message. """ return_json = kwargs.pop('return_json', False) url = self.api_url[version] + url response = func(url, *args, **kwargs) if 'proxies' not in kwargs: kwargs['proxies'] = self.proxydict # Check for error, raising an exception if appropriate. response.raise_for_status() try: json_response = response.json() except ValueError: json_response = None if isinstance(json_response, dict): error = json_response.get('error') if error: raise BitstampError(error) elif json_response.get('status') == "error": raise BitstampError(json_response.get('reason')) if return_json: if json_response is None: raise BitstampError( "Could not decode json for: " + response.text) return json_response return response
python
def _request(self, func, url, version=1, *args, **kwargs): """ Make a generic request, adding in any proxy defined by the instance. Raises a ``requests.HTTPError`` if the response status isn't 200, and raises a :class:`BitstampError` if the response contains a json encoded error message. """ return_json = kwargs.pop('return_json', False) url = self.api_url[version] + url response = func(url, *args, **kwargs) if 'proxies' not in kwargs: kwargs['proxies'] = self.proxydict # Check for error, raising an exception if appropriate. response.raise_for_status() try: json_response = response.json() except ValueError: json_response = None if isinstance(json_response, dict): error = json_response.get('error') if error: raise BitstampError(error) elif json_response.get('status') == "error": raise BitstampError(json_response.get('reason')) if return_json: if json_response is None: raise BitstampError( "Could not decode json for: " + response.text) return json_response return response
Make a generic request, adding in any proxy defined by the instance. Raises a ``requests.HTTPError`` if the response status isn't 200, and raises a :class:`BitstampError` if the response contains a json encoded error message.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L66-L101
kmadac/bitstamp-python-client
bitstamp/client.py
Public.ticker
def ticker(self, base="btc", quote="usd"): """ Returns dictionary. """ url = self._construct_url("ticker/", base, quote) return self._get(url, return_json=True, version=2)
python
def ticker(self, base="btc", quote="usd"): """ Returns dictionary. """ url = self._construct_url("ticker/", base, quote) return self._get(url, return_json=True, version=2)
Returns dictionary.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L106-L111
kmadac/bitstamp-python-client
bitstamp/client.py
Public.order_book
def order_book(self, group=True, base="btc", quote="usd"): """ Returns dictionary with "bids" and "asks". Each is a list of open orders and each order is represented as a list of price and amount. """ params = {'group': group} url = self._construct_url("order_book/", base, quote) return self._get(url, params=params, return_json=True, version=2)
python
def order_book(self, group=True, base="btc", quote="usd"): """ Returns dictionary with "bids" and "asks". Each is a list of open orders and each order is represented as a list of price and amount. """ params = {'group': group} url = self._construct_url("order_book/", base, quote) return self._get(url, params=params, return_json=True, version=2)
Returns dictionary with "bids" and "asks". Each is a list of open orders and each order is represented as a list of price and amount.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L120-L129
kmadac/bitstamp-python-client
bitstamp/client.py
Public.transactions
def transactions(self, time=TransRange.HOUR, base="btc", quote="usd"): """ Returns transactions for the last 'timedelta' seconds. Parameter time is specified by one of two values of TransRange class. """ params = {'time': time} url = self._construct_url("transactions/", base, quote) return self._get(url, params=params, return_json=True, version=2)
python
def transactions(self, time=TransRange.HOUR, base="btc", quote="usd"): """ Returns transactions for the last 'timedelta' seconds. Parameter time is specified by one of two values of TransRange class. """ params = {'time': time} url = self._construct_url("transactions/", base, quote) return self._get(url, params=params, return_json=True, version=2)
Returns transactions for the last 'timedelta' seconds. Parameter time is specified by one of two values of TransRange class.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L131-L138
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.get_nonce
def get_nonce(self): """ Get a unique nonce for the bitstamp API. This integer must always be increasing, so use the current unix time. Every time this variable is requested, it automatically increments to allow for more than one API request per second. This isn't a thread-safe function however, so you should only rely on a single thread if you have a high level of concurrent API requests in your application. """ nonce = getattr(self, '_nonce', 0) if nonce: nonce += 1 # If the unix time is greater though, use that instead (helps low # concurrency multi-threaded apps always call with the largest nonce). self._nonce = max(int(time.time()), nonce) return self._nonce
python
def get_nonce(self): """ Get a unique nonce for the bitstamp API. This integer must always be increasing, so use the current unix time. Every time this variable is requested, it automatically increments to allow for more than one API request per second. This isn't a thread-safe function however, so you should only rely on a single thread if you have a high level of concurrent API requests in your application. """ nonce = getattr(self, '_nonce', 0) if nonce: nonce += 1 # If the unix time is greater though, use that instead (helps low # concurrency multi-threaded apps always call with the largest nonce). self._nonce = max(int(time.time()), nonce) return self._nonce
Get a unique nonce for the bitstamp API. This integer must always be increasing, so use the current unix time. Every time this variable is requested, it automatically increments to allow for more than one API request per second. This isn't a thread-safe function however, so you should only rely on a single thread if you have a high level of concurrent API requests in your application.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L177-L195
kmadac/bitstamp-python-client
bitstamp/client.py
Trading._default_data
def _default_data(self, *args, **kwargs): """ Generate a one-time signature and other data required to send a secure POST request to the Bitstamp API. """ data = super(Trading, self)._default_data(*args, **kwargs) data['key'] = self.key nonce = self.get_nonce() msg = str(nonce) + self.username + self.key signature = hmac.new( self.secret.encode('utf-8'), msg=msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest().upper() data['signature'] = signature data['nonce'] = nonce return data
python
def _default_data(self, *args, **kwargs): """ Generate a one-time signature and other data required to send a secure POST request to the Bitstamp API. """ data = super(Trading, self)._default_data(*args, **kwargs) data['key'] = self.key nonce = self.get_nonce() msg = str(nonce) + self.username + self.key signature = hmac.new( self.secret.encode('utf-8'), msg=msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest().upper() data['signature'] = signature data['nonce'] = nonce return data
Generate a one-time signature and other data required to send a secure POST request to the Bitstamp API.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L197-L212
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.account_balance
def account_balance(self, base="btc", quote="usd"): """ Returns dictionary:: {u'btc_reserved': u'0', u'fee': u'0.5000', u'btc_available': u'2.30856098', u'usd_reserved': u'0', u'btc_balance': u'2.30856098', u'usd_balance': u'114.64', u'usd_available': u'114.64', ---If base and quote were specified: u'fee': u'', ---If base and quote were not specified: u'btcusd_fee': u'0.25', u'btceur_fee': u'0.25', u'eurusd_fee': u'0.20', } There could be reasons to set base and quote to None (or False), because the result then will contain the fees for all currency pairs For backwards compatibility this can not be the default however. """ url = self._construct_url("balance/", base, quote) return self._post(url, return_json=True, version=2)
python
def account_balance(self, base="btc", quote="usd"): """ Returns dictionary:: {u'btc_reserved': u'0', u'fee': u'0.5000', u'btc_available': u'2.30856098', u'usd_reserved': u'0', u'btc_balance': u'2.30856098', u'usd_balance': u'114.64', u'usd_available': u'114.64', ---If base and quote were specified: u'fee': u'', ---If base and quote were not specified: u'btcusd_fee': u'0.25', u'btceur_fee': u'0.25', u'eurusd_fee': u'0.20', } There could be reasons to set base and quote to None (or False), because the result then will contain the fees for all currency pairs For backwards compatibility this can not be the default however. """ url = self._construct_url("balance/", base, quote) return self._post(url, return_json=True, version=2)
Returns dictionary:: {u'btc_reserved': u'0', u'fee': u'0.5000', u'btc_available': u'2.30856098', u'usd_reserved': u'0', u'btc_balance': u'2.30856098', u'usd_balance': u'114.64', u'usd_available': u'114.64', ---If base and quote were specified: u'fee': u'', ---If base and quote were not specified: u'btcusd_fee': u'0.25', u'btceur_fee': u'0.25', u'eurusd_fee': u'0.20', } There could be reasons to set base and quote to None (or False), because the result then will contain the fees for all currency pairs For backwards compatibility this can not be the default however.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L223-L246
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.user_transactions
def user_transactions(self, offset=0, limit=100, descending=True, base=None, quote=None): """ Returns descending list of transactions. Every transaction (dictionary) contains:: {u'usd': u'-39.25', u'datetime': u'2013-03-26 18:49:13', u'fee': u'0.20', u'btc': u'0.50000000', u'type': 2, u'id': 213642} Instead of the keys btc and usd, it can contain other currency codes """ data = { 'offset': offset, 'limit': limit, 'sort': 'desc' if descending else 'asc', } url = self._construct_url("user_transactions/", base, quote) return self._post(url, data=data, return_json=True, version=2)
python
def user_transactions(self, offset=0, limit=100, descending=True, base=None, quote=None): """ Returns descending list of transactions. Every transaction (dictionary) contains:: {u'usd': u'-39.25', u'datetime': u'2013-03-26 18:49:13', u'fee': u'0.20', u'btc': u'0.50000000', u'type': 2, u'id': 213642} Instead of the keys btc and usd, it can contain other currency codes """ data = { 'offset': offset, 'limit': limit, 'sort': 'desc' if descending else 'asc', } url = self._construct_url("user_transactions/", base, quote) return self._post(url, data=data, return_json=True, version=2)
Returns descending list of transactions. Every transaction (dictionary) contains:: {u'usd': u'-39.25', u'datetime': u'2013-03-26 18:49:13', u'fee': u'0.20', u'btc': u'0.50000000', u'type': 2, u'id': 213642} Instead of the keys btc and usd, it can contain other currency codes
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L248-L269
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.order_status
def order_status(self, order_id): """ Returns dictionary. - status: 'Finished' or 'In Queue' or 'Open' - transactions: list of transactions Each transaction is a dictionary with the following keys: btc, usd, price, type, fee, datetime, tid or btc, eur, .... or eur, usd, .... """ data = {'id': order_id} return self._post("order_status/", data=data, return_json=True, version=1)
python
def order_status(self, order_id): """ Returns dictionary. - status: 'Finished' or 'In Queue' or 'Open' - transactions: list of transactions Each transaction is a dictionary with the following keys: btc, usd, price, type, fee, datetime, tid or btc, eur, .... or eur, usd, .... """ data = {'id': order_id} return self._post("order_status/", data=data, return_json=True, version=1)
Returns dictionary. - status: 'Finished' or 'In Queue' or 'Open' - transactions: list of transactions Each transaction is a dictionary with the following keys: btc, usd, price, type, fee, datetime, tid or btc, eur, .... or eur, usd, ....
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L279-L293
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.cancel_order
def cancel_order(self, order_id, version=1): """ Cancel the order specified by order_id. Version 1 (default for backwards compatibility reasons): Returns True if order was successfully canceled, otherwise raise a BitstampError. Version 2: Returns dictionary of the canceled order, containing the keys: id, type, price, amount """ data = {'id': order_id} return self._post("cancel_order/", data=data, return_json=True, version=version)
python
def cancel_order(self, order_id, version=1): """ Cancel the order specified by order_id. Version 1 (default for backwards compatibility reasons): Returns True if order was successfully canceled, otherwise raise a BitstampError. Version 2: Returns dictionary of the canceled order, containing the keys: id, type, price, amount """ data = {'id': order_id} return self._post("cancel_order/", data=data, return_json=True, version=version)
Cancel the order specified by order_id. Version 1 (default for backwards compatibility reasons): Returns True if order was successfully canceled, otherwise raise a BitstampError. Version 2: Returns dictionary of the canceled order, containing the keys: id, type, price, amount
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L295-L309
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.buy_limit_order
def buy_limit_order(self, amount, price, base="btc", quote="usd", limit_price=None): """ Order to buy amount of bitcoins for specified price. """ data = {'amount': amount, 'price': price} if limit_price is not None: data['limit_price'] = limit_price url = self._construct_url("buy/", base, quote) return self._post(url, data=data, return_json=True, version=2)
python
def buy_limit_order(self, amount, price, base="btc", quote="usd", limit_price=None): """ Order to buy amount of bitcoins for specified price. """ data = {'amount': amount, 'price': price} if limit_price is not None: data['limit_price'] = limit_price url = self._construct_url("buy/", base, quote) return self._post(url, data=data, return_json=True, version=2)
Order to buy amount of bitcoins for specified price.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L320-L328
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.buy_market_order
def buy_market_order(self, amount, base="btc", quote="usd"): """ Order to buy amount of bitcoins for market price. """ data = {'amount': amount} url = self._construct_url("buy/market/", base, quote) return self._post(url, data=data, return_json=True, version=2)
python
def buy_market_order(self, amount, base="btc", quote="usd"): """ Order to buy amount of bitcoins for market price. """ data = {'amount': amount} url = self._construct_url("buy/market/", base, quote) return self._post(url, data=data, return_json=True, version=2)
Order to buy amount of bitcoins for market price.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L330-L336
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.check_bitstamp_code
def check_bitstamp_code(self, code): """ Returns JSON dictionary containing USD and BTC amount included in given bitstamp code. """ data = {'code': code} return self._post("check_code/", data=data, return_json=True, version=1)
python
def check_bitstamp_code(self, code): """ Returns JSON dictionary containing USD and BTC amount included in given bitstamp code. """ data = {'code': code} return self._post("check_code/", data=data, return_json=True, version=1)
Returns JSON dictionary containing USD and BTC amount included in given bitstamp code.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L356-L363
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.redeem_bitstamp_code
def redeem_bitstamp_code(self, code): """ Returns JSON dictionary containing USD and BTC amount added to user's account. """ data = {'code': code} return self._post("redeem_code/", data=data, return_json=True, version=1)
python
def redeem_bitstamp_code(self, code): """ Returns JSON dictionary containing USD and BTC amount added to user's account. """ data = {'code': code} return self._post("redeem_code/", data=data, return_json=True, version=1)
Returns JSON dictionary containing USD and BTC amount added to user's account.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L365-L372
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.withdrawal_requests
def withdrawal_requests(self, timedelta = 86400): """ Returns list of withdrawal requests. Each request is represented as a dictionary. By default, the last 24 hours (86400 seconds) are returned. """ data = {'timedelta': timedelta} return self._post("withdrawal_requests/", return_json=True, version=1, data=data)
python
def withdrawal_requests(self, timedelta = 86400): """ Returns list of withdrawal requests. Each request is represented as a dictionary. By default, the last 24 hours (86400 seconds) are returned. """ data = {'timedelta': timedelta} return self._post("withdrawal_requests/", return_json=True, version=1, data=data)
Returns list of withdrawal requests. Each request is represented as a dictionary. By default, the last 24 hours (86400 seconds) are returned.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L374-L383
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.litecoin_withdrawal
def litecoin_withdrawal(self, amount, address): """ Send litecoins to another litecoin wallet specified by address. """ data = {'amount': amount, 'address': address} return self._post("ltc_withdrawal/", data=data, return_json=True, version=2)
python
def litecoin_withdrawal(self, amount, address): """ Send litecoins to another litecoin wallet specified by address. """ data = {'amount': amount, 'address': address} return self._post("ltc_withdrawal/", data=data, return_json=True, version=2)
Send litecoins to another litecoin wallet specified by address.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L415-L421
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.ripple_withdrawal
def ripple_withdrawal(self, amount, address, currency): """ Returns true if successful. """ data = {'amount': amount, 'address': address, 'currency': currency} response = self._post("ripple_withdrawal/", data=data, return_json=True) return self._expect_true(response)
python
def ripple_withdrawal(self, amount, address, currency): """ Returns true if successful. """ data = {'amount': amount, 'address': address, 'currency': currency} response = self._post("ripple_withdrawal/", data=data, return_json=True) return self._expect_true(response)
Returns true if successful.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L445-L452
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.xrp_withdrawal
def xrp_withdrawal(self, amount, address, destination_tag=None): """ Sends xrps to another xrp wallet specified by address. Returns withdrawal id. """ data = {'amount': amount, 'address': address} if destination_tag: data['destination_tag'] = destination_tag return self._post("xrp_withdrawal/", data=data, return_json=True, version=2)["id"]
python
def xrp_withdrawal(self, amount, address, destination_tag=None): """ Sends xrps to another xrp wallet specified by address. Returns withdrawal id. """ data = {'amount': amount, 'address': address} if destination_tag: data['destination_tag'] = destination_tag return self._post("xrp_withdrawal/", data=data, return_json=True, version=2)["id"]
Sends xrps to another xrp wallet specified by address. Returns withdrawal id.
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L461-L470
kmadac/bitstamp-python-client
bitstamp/client.py
Trading.transfer_to_main
def transfer_to_main(self, amount, currency, subaccount=None): """ Returns dictionary with status. subaccount has to be the numerical id of the subaccount, not the name """ data = {'amount': amount, 'currency': currency,} if subaccount is not None: data['subAccount'] = subaccount return self._post("transfer-to-main/", data=data, return_json=True, version=2)
python
def transfer_to_main(self, amount, currency, subaccount=None): """ Returns dictionary with status. subaccount has to be the numerical id of the subaccount, not the name """ data = {'amount': amount, 'currency': currency,} if subaccount is not None: data['subAccount'] = subaccount return self._post("transfer-to-main/", data=data, return_json=True, version=2)
Returns dictionary with status. subaccount has to be the numerical id of the subaccount, not the name
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L495-L505
pierre-rouanet/aupyom
aupyom/sound.py
Sound.resample
def resample(self, target_sr): """ Returns a new sound with a samplerate of target_sr. """ y_hat = librosa.core.resample(self.y, self.sr, target_sr) return Sound(y_hat, target_sr)
python
def resample(self, target_sr): """ Returns a new sound with a samplerate of target_sr. """ y_hat = librosa.core.resample(self.y, self.sr, target_sr) return Sound(y_hat, target_sr)
Returns a new sound with a samplerate of target_sr.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sound.py#L36-L39
pierre-rouanet/aupyom
aupyom/sound.py
Sound.as_ipywidget
def as_ipywidget(self): """ Provides an IPywidgets player that can be used in a notebook. """ from IPython.display import Audio return Audio(data=self.y, rate=self.sr)
python
def as_ipywidget(self): """ Provides an IPywidgets player that can be used in a notebook. """ from IPython.display import Audio return Audio(data=self.y, rate=self.sr)
Provides an IPywidgets player that can be used in a notebook.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sound.py#L43-L47
pierre-rouanet/aupyom
aupyom/sound.py
Sound.from_file
def from_file(cls, filename, sr=22050): """ Loads an audiofile, uses sr=22050 by default. """ y, sr = librosa.load(filename, sr=sr) return cls(y, sr)
python
def from_file(cls, filename, sr=22050): """ Loads an audiofile, uses sr=22050 by default. """ y, sr = librosa.load(filename, sr=sr) return cls(y, sr)
Loads an audiofile, uses sr=22050 by default.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sound.py#L50-L53
pierre-rouanet/aupyom
aupyom/sound.py
Sound.chunks
def chunks(self): """ Returns a chunk iterator over the sound. """ if not hasattr(self, '_it'): class ChunkIterator(object): def __iter__(iter): return iter def __next__(iter): try: chunk = self._next_chunk() except StopIteration: if self.loop: self._init_stretching() return iter.__next__() raise return chunk next = __next__ self._it = ChunkIterator() return self._it
python
def chunks(self): """ Returns a chunk iterator over the sound. """ if not hasattr(self, '_it'): class ChunkIterator(object): def __iter__(iter): return iter def __next__(iter): try: chunk = self._next_chunk() except StopIteration: if self.loop: self._init_stretching() return iter.__next__() raise return chunk next = __next__ self._it = ChunkIterator() return self._it
Returns a chunk iterator over the sound.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sound.py#L70-L92
pierre-rouanet/aupyom
aupyom/sound.py
Sound.pitch_shifter
def pitch_shifter(self, chunk, shift): """ Pitch-Shift the given chunk by shift semi-tones. """ freq = numpy.fft.rfft(chunk) N = len(freq) shifted_freq = numpy.zeros(N, freq.dtype) S = numpy.round(shift if shift > 0 else N + shift, 0) s = N - S shifted_freq[:S] = freq[s:] shifted_freq[S:] = freq[:s] shifted_chunk = numpy.fft.irfft(shifted_freq) return shifted_chunk.astype(chunk.dtype)
python
def pitch_shifter(self, chunk, shift): """ Pitch-Shift the given chunk by shift semi-tones. """ freq = numpy.fft.rfft(chunk) N = len(freq) shifted_freq = numpy.zeros(N, freq.dtype) S = numpy.round(shift if shift > 0 else N + shift, 0) s = N - S shifted_freq[:S] = freq[s:] shifted_freq[S:] = freq[:s] shifted_chunk = numpy.fft.irfft(shifted_freq) return shifted_chunk.astype(chunk.dtype)
Pitch-Shift the given chunk by shift semi-tones.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sound.py#L108-L123
pierre-rouanet/aupyom
aupyom/sound.py
Sound._time_stretcher
def _time_stretcher(self, stretch_factor): """ Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk. """ start = self._i2 end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H)) if start >= end: raise StopIteration # The not so clean code below basically implements a phase vocoder out = numpy.zeros(self._N, dtype=numpy.complex) while self._i2 < end: if self._i1 + self._N + self._H > len(self.y): raise StopIteration a, b = self._i1, self._i1 + self._N S1 = numpy.fft.fft(self._win * self.y[a: b]) S2 = numpy.fft.fft(self._win * self.y[a + self._H: b + self._H]) self._phi += (numpy.angle(S2) - numpy.angle(S1)) self._phi = self._phi - 2.0 * numpy.pi * numpy.round(self._phi / (2.0 * numpy.pi)) out.real, out.imag = numpy.cos(self._phi), numpy.sin(self._phi) self._sy[self._i2: self._i2 + self._N] += self._win * numpy.fft.ifft(numpy.abs(S2) * out).real self._i1 += int(self._H * self.stretch_factor) self._i2 += self._H chunk = self._sy[start:end] if stretch_factor == 1.0: chunk = self.y[start:end] return chunk
python
def _time_stretcher(self, stretch_factor): """ Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk. """ start = self._i2 end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H)) if start >= end: raise StopIteration # The not so clean code below basically implements a phase vocoder out = numpy.zeros(self._N, dtype=numpy.complex) while self._i2 < end: if self._i1 + self._N + self._H > len(self.y): raise StopIteration a, b = self._i1, self._i1 + self._N S1 = numpy.fft.fft(self._win * self.y[a: b]) S2 = numpy.fft.fft(self._win * self.y[a + self._H: b + self._H]) self._phi += (numpy.angle(S2) - numpy.angle(S1)) self._phi = self._phi - 2.0 * numpy.pi * numpy.round(self._phi / (2.0 * numpy.pi)) out.real, out.imag = numpy.cos(self._phi), numpy.sin(self._phi) self._sy[self._i2: self._i2 + self._N] += self._win * numpy.fft.ifft(numpy.abs(S2) * out).real self._i1 += int(self._H * self.stretch_factor) self._i2 += self._H chunk = self._sy[start:end] if stretch_factor == 1.0: chunk = self.y[start:end] return chunk
Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This method needs to store the phase computed from the previous chunk. Thus, it can only be called chunk by chunk.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sound.py#L158-L199
vlasovskikh/funcparserlib
funcparserlib/util.py
pretty_tree
def pretty_tree(x, kids, show): """(a, (a -> list(a)), (a -> str)) -> str Returns a pseudographic tree representation of x similar to the tree command in Unix. """ (MID, END, CONT, LAST, ROOT) = (u'|-- ', u'`-- ', u'| ', u' ', u'') def rec(x, indent, sym): line = indent + sym + show(x) xs = kids(x) if len(xs) == 0: return line else: if sym == MID: next_indent = indent + CONT elif sym == ROOT: next_indent = indent + ROOT else: next_indent = indent + LAST syms = [MID] * (len(xs) - 1) + [END] lines = [rec(x, next_indent, sym) for x, sym in zip(xs, syms)] return u'\n'.join([line] + lines) return rec(x, u'', ROOT)
python
def pretty_tree(x, kids, show): """(a, (a -> list(a)), (a -> str)) -> str Returns a pseudographic tree representation of x similar to the tree command in Unix. """ (MID, END, CONT, LAST, ROOT) = (u'|-- ', u'`-- ', u'| ', u' ', u'') def rec(x, indent, sym): line = indent + sym + show(x) xs = kids(x) if len(xs) == 0: return line else: if sym == MID: next_indent = indent + CONT elif sym == ROOT: next_indent = indent + ROOT else: next_indent = indent + LAST syms = [MID] * (len(xs) - 1) + [END] lines = [rec(x, next_indent, sym) for x, sym in zip(xs, syms)] return u'\n'.join([line] + lines) return rec(x, u'', ROOT)
(a, (a -> list(a)), (a -> str)) -> str Returns a pseudographic tree representation of x similar to the tree command in Unix.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/util.py#L25-L49
vlasovskikh/funcparserlib
funcparserlib/lexer.py
make_tokenizer
def make_tokenizer(specs): """[(str, (str, int?))] -> (str -> Iterable(Token))""" def compile_spec(spec): name, args = spec return name, re.compile(*args) compiled = [compile_spec(s) for s in specs] def match_specs(specs, str, i, position): line, pos = position for type, regexp in specs: m = regexp.match(str, i) if m is not None: value = m.group() nls = value.count(u'\n') n_line = line + nls if nls == 0: n_pos = pos + len(value) else: n_pos = len(value) - value.rfind(u'\n') - 1 return Token(type, value, (line, pos + 1), (n_line, n_pos)) else: errline = str.splitlines()[line - 1] raise LexerError((line, pos + 1), errline) def f(str): length = len(str) line, pos = 1, 0 i = 0 while i < length: t = match_specs(compiled, str, i, (line, pos)) yield t line, pos = t.end i += len(t.value) return f
python
def make_tokenizer(specs): """[(str, (str, int?))] -> (str -> Iterable(Token))""" def compile_spec(spec): name, args = spec return name, re.compile(*args) compiled = [compile_spec(s) for s in specs] def match_specs(specs, str, i, position): line, pos = position for type, regexp in specs: m = regexp.match(str, i) if m is not None: value = m.group() nls = value.count(u'\n') n_line = line + nls if nls == 0: n_pos = pos + len(value) else: n_pos = len(value) - value.rfind(u'\n') - 1 return Token(type, value, (line, pos + 1), (n_line, n_pos)) else: errline = str.splitlines()[line - 1] raise LexerError((line, pos + 1), errline) def f(str): length = len(str) line, pos = 1, 0 i = 0 while i < length: t = match_specs(compiled, str, i, (line, pos)) yield t line, pos = t.end i += len(t.value) return f
[(str, (str, int?))] -> (str -> Iterable(Token))
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/lexer.py#L76-L112
vlasovskikh/funcparserlib
funcparserlib/parser.py
finished
def finished(tokens, s): """Parser(a, None) Throws an exception if any tokens are left in the input unparsed. """ if s.pos >= len(tokens): return None, s else: raise NoParseError(u'should have reached <EOF>', s)
python
def finished(tokens, s): """Parser(a, None) Throws an exception if any tokens are left in the input unparsed. """ if s.pos >= len(tokens): return None, s else: raise NoParseError(u'should have reached <EOF>', s)
Parser(a, None) Throws an exception if any tokens are left in the input unparsed.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L264-L272
vlasovskikh/funcparserlib
funcparserlib/parser.py
many
def many(p): """Parser(a, b) -> Parser(a, [b]) Returns a parser that infinitely applies the parser p to the input sequence of tokens while it successfully parsers them. The resulting parser returns a list of parsed values. """ @Parser def _many(tokens, s): """Iterative implementation preventing the stack overflow.""" res = [] try: while True: (v, s) = p.run(tokens, s) res.append(v) except NoParseError, e: return res, State(s.pos, e.state.max) _many.name = u'{ %s }' % p.name return _many
python
def many(p): """Parser(a, b) -> Parser(a, [b]) Returns a parser that infinitely applies the parser p to the input sequence of tokens while it successfully parsers them. The resulting parser returns a list of parsed values. """ @Parser def _many(tokens, s): """Iterative implementation preventing the stack overflow.""" res = [] try: while True: (v, s) = p.run(tokens, s) res.append(v) except NoParseError, e: return res, State(s.pos, e.state.max) _many.name = u'{ %s }' % p.name return _many
Parser(a, b) -> Parser(a, [b]) Returns a parser that infinitely applies the parser p to the input sequence of tokens while it successfully parsers them. The resulting parser returns a list of parsed values.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L278-L298
vlasovskikh/funcparserlib
funcparserlib/parser.py
some
def some(pred): """(a -> bool) -> Parser(a, a) Returns a parser that parses a token if it satisfies a predicate pred. """ @Parser def _some(tokens, s): if s.pos >= len(tokens): raise NoParseError(u'no tokens left in the stream', s) else: t = tokens[s.pos] if pred(t): pos = s.pos + 1 s2 = State(pos, max(pos, s.max)) if debug: log.debug(u'*matched* "%s", new state = %s' % (t, s2)) return t, s2 else: if debug: log.debug(u'failed "%s", state = %s' % (t, s)) raise NoParseError(u'got unexpected token', s) _some.name = u'(some)' return _some
python
def some(pred): """(a -> bool) -> Parser(a, a) Returns a parser that parses a token if it satisfies a predicate pred. """ @Parser def _some(tokens, s): if s.pos >= len(tokens): raise NoParseError(u'no tokens left in the stream', s) else: t = tokens[s.pos] if pred(t): pos = s.pos + 1 s2 = State(pos, max(pos, s.max)) if debug: log.debug(u'*matched* "%s", new state = %s' % (t, s2)) return t, s2 else: if debug: log.debug(u'failed "%s", state = %s' % (t, s)) raise NoParseError(u'got unexpected token', s) _some.name = u'(some)' return _some
(a -> bool) -> Parser(a, a) Returns a parser that parses a token if it satisfies a predicate pred.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L301-L325
vlasovskikh/funcparserlib
funcparserlib/parser.py
a
def a(value): """Eq(a) -> Parser(a, a) Returns a parser that parses a token that is equal to the value value. """ name = getattr(value, 'name', value) return some(lambda t: t == value).named(u'(a "%s")' % (name,))
python
def a(value): """Eq(a) -> Parser(a, a) Returns a parser that parses a token that is equal to the value value. """ name = getattr(value, 'name', value) return some(lambda t: t == value).named(u'(a "%s")' % (name,))
Eq(a) -> Parser(a, a) Returns a parser that parses a token that is equal to the value value.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L328-L334
vlasovskikh/funcparserlib
funcparserlib/parser.py
oneplus
def oneplus(p): """Parser(a, b) -> Parser(a, [b]) Returns a parser that applies the parser p one or more times. """ @Parser def _oneplus(tokens, s): (v1, s2) = p.run(tokens, s) (v2, s3) = many(p).run(tokens, s2) return [v1] + v2, s3 _oneplus.name = u'(%s , { %s })' % (p.name, p.name) return _oneplus
python
def oneplus(p): """Parser(a, b) -> Parser(a, [b]) Returns a parser that applies the parser p one or more times. """ @Parser def _oneplus(tokens, s): (v1, s2) = p.run(tokens, s) (v2, s3) = many(p).run(tokens, s2) return [v1] + v2, s3 _oneplus.name = u'(%s , { %s })' % (p.name, p.name) return _oneplus
Parser(a, b) -> Parser(a, [b]) Returns a parser that applies the parser p one or more times.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L366-L378
vlasovskikh/funcparserlib
funcparserlib/parser.py
with_forward_decls
def with_forward_decls(suspension): """(None -> Parser(a, b)) -> Parser(a, b) Returns a parser that computes itself lazily as a result of the suspension provided. It is needed when some parsers contain forward references to parsers defined later and such references are cyclic. See examples for more details. """ @Parser def f(tokens, s): return suspension().run(tokens, s) return f
python
def with_forward_decls(suspension): """(None -> Parser(a, b)) -> Parser(a, b) Returns a parser that computes itself lazily as a result of the suspension provided. It is needed when some parsers contain forward references to parsers defined later and such references are cyclic. See examples for more details. """ @Parser def f(tokens, s): return suspension().run(tokens, s) return f
(None -> Parser(a, b)) -> Parser(a, b) Returns a parser that computes itself lazily as a result of the suspension provided. It is needed when some parsers contain forward references to parsers defined later and such references are cyclic. See examples for more details.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L381-L394
vlasovskikh/funcparserlib
funcparserlib/parser.py
Parser.define
def define(self, p): """Defines a parser wrapped into this object.""" f = getattr(p, 'run', p) if debug: setattr(self, '_run', f) else: setattr(self, 'run', f) self.named(getattr(p, 'name', p.__doc__))
python
def define(self, p): """Defines a parser wrapped into this object.""" f = getattr(p, 'run', p) if debug: setattr(self, '_run', f) else: setattr(self, 'run', f) self.named(getattr(p, 'name', p.__doc__))
Defines a parser wrapped into this object.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L90-L97
vlasovskikh/funcparserlib
funcparserlib/parser.py
Parser.run
def run(self, tokens, s): """Sequence(a), State -> (b, State) Runs a parser wrapped into this object. """ if debug: log.debug(u'trying %s' % self.name) return self._run(tokens, s)
python
def run(self, tokens, s): """Sequence(a), State -> (b, State) Runs a parser wrapped into this object. """ if debug: log.debug(u'trying %s' % self.name) return self._run(tokens, s)
Sequence(a), State -> (b, State) Runs a parser wrapped into this object.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L99-L106
vlasovskikh/funcparserlib
funcparserlib/parser.py
Parser.parse
def parse(self, tokens): """Sequence(a) -> b Applies the parser to a sequence of tokens producing a parsing result. It provides a way to invoke a parser hiding details related to the parser state. Also it makes error messages more readable by specifying the position of the rightmost token that has been reached. """ try: (tree, _) = self.run(tokens, State()) return tree except NoParseError, e: max = e.state.max if len(tokens) > max: tok = tokens[max] else: tok = u'<EOF>' raise NoParseError(u'%s: %s' % (e.msg, tok), e.state)
python
def parse(self, tokens): """Sequence(a) -> b Applies the parser to a sequence of tokens producing a parsing result. It provides a way to invoke a parser hiding details related to the parser state. Also it makes error messages more readable by specifying the position of the rightmost token that has been reached. """ try: (tree, _) = self.run(tokens, State()) return tree except NoParseError, e: max = e.state.max if len(tokens) > max: tok = tokens[max] else: tok = u'<EOF>' raise NoParseError(u'%s: %s' % (e.msg, tok), e.state)
Sequence(a) -> b Applies the parser to a sequence of tokens producing a parsing result. It provides a way to invoke a parser hiding details related to the parser state. Also it makes error messages more readable by specifying the position of the rightmost token that has been reached.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L111-L129
vlasovskikh/funcparserlib
funcparserlib/parser.py
Parser.bind
def bind(self, f): """Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c) NOTE: A monadic bind function. It is used internally to implement other combinators. Functions bind and pure make the Parser a Monad. """ @Parser def _bind(tokens, s): (v, s2) = self.run(tokens, s) return f(v).run(tokens, s2) _bind.name = u'(%s >>=)' % (self.name,) return _bind
python
def bind(self, f): """Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c) NOTE: A monadic bind function. It is used internally to implement other combinators. Functions bind and pure make the Parser a Monad. """ @Parser def _bind(tokens, s): (v, s2) = self.run(tokens, s) return f(v).run(tokens, s2) _bind.name = u'(%s >>=)' % (self.name,) return _bind
Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c) NOTE: A monadic bind function. It is used internally to implement other combinators. Functions bind and pure make the Parser a Monad.
https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L207-L220
pierre-rouanet/aupyom
aupyom/sampler.py
Sampler.play
def play(self, sound): """ Adds and plays a new Sound to the Sampler. :param sound: sound to play .. note:: If the sound is already playing, it will restart from the beginning. """ self.is_done.clear() # hold is_done until the sound is played if self.sr != sound.sr: raise ValueError('You can only play sound with a samplerate of {} (here {}). Use the Sound.resample method for instance.', self.sr, sound.sr) if sound in self.sounds: self.remove(sound) with self.chunk_available: self.sounds.append(sound) sound.playing = True self.chunk_available.notify() self.is_done.wait()
python
def play(self, sound): """ Adds and plays a new Sound to the Sampler. :param sound: sound to play .. note:: If the sound is already playing, it will restart from the beginning. """ self.is_done.clear() # hold is_done until the sound is played if self.sr != sound.sr: raise ValueError('You can only play sound with a samplerate of {} (here {}). Use the Sound.resample method for instance.', self.sr, sound.sr) if sound in self.sounds: self.remove(sound) with self.chunk_available: self.sounds.append(sound) sound.playing = True self.chunk_available.notify() self.is_done.wait()
Adds and plays a new Sound to the Sampler. :param sound: sound to play .. note:: If the sound is already playing, it will restart from the beginning.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sampler.py#L48-L68
pierre-rouanet/aupyom
aupyom/sampler.py
Sampler.remove
def remove(self, sound): """ Remove a currently played sound. """ with self.chunk_available: sound.playing = False self.sounds.remove(sound)
python
def remove(self, sound): """ Remove a currently played sound. """ with self.chunk_available: sound.playing = False self.sounds.remove(sound)
Remove a currently played sound.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sampler.py#L70-L74
pierre-rouanet/aupyom
aupyom/sampler.py
Sampler.next_chunks
def next_chunks(self): """ Gets a new chunk from all played sound and mix them together. """ with self.chunk_available: while True: playing_sounds = [s for s in self.sounds if s.playing] chunks = [] for s in playing_sounds: try: chunks.append(next(s.chunks)) except StopIteration: s.playing = False self.sounds.remove(s) self.is_done.set() # sound was played, release is_done to end the wait in play if chunks: break self.chunk_available.wait() return numpy.mean(chunks, axis=0)
python
def next_chunks(self): """ Gets a new chunk from all played sound and mix them together. """ with self.chunk_available: while True: playing_sounds = [s for s in self.sounds if s.playing] chunks = [] for s in playing_sounds: try: chunks.append(next(s.chunks)) except StopIteration: s.playing = False self.sounds.remove(s) self.is_done.set() # sound was played, release is_done to end the wait in play if chunks: break self.chunk_available.wait() return numpy.mean(chunks, axis=0)
Gets a new chunk from all played sound and mix them together.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sampler.py#L78-L98
pierre-rouanet/aupyom
aupyom/sampler.py
Sampler.run
def run(self): """ Play loop, i.e. send all sound chunk by chunk to the soundcard. """ self.running = True def chunks_producer(): while self.running: self.chunks.put(self.next_chunks()) t = Thread(target=chunks_producer) t.start() with self.BackendStream(samplerate=self.sr, channels=1) as stream: while self.running: try: stream.write(self.chunks.get(timeout=self.timeout)) # timeout so stream.write() thread can exit except Empty: self.running = False
python
def run(self): """ Play loop, i.e. send all sound chunk by chunk to the soundcard. """ self.running = True def chunks_producer(): while self.running: self.chunks.put(self.next_chunks()) t = Thread(target=chunks_producer) t.start() with self.BackendStream(samplerate=self.sr, channels=1) as stream: while self.running: try: stream.write(self.chunks.get(timeout=self.timeout)) # timeout so stream.write() thread can exit except Empty: self.running = False
Play loop, i.e. send all sound chunk by chunk to the soundcard.
https://github.com/pierre-rouanet/aupyom/blob/90f819b2d0b6cf7467b1945af029317a61e52e56/aupyom/sampler.py#L100-L116
suds-community/suds
suds/wsse.py
UsernameToken.xml
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) if self.password_digest: p.set("Type", wsdigest) p.setText(self.password_digest) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.nonce_has_encoding: n.set("EncodingType", nonce_encoding_type) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(DateTime(self.created))) root.append(n) return root
python
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) if self.password_digest: p.set("Type", wsdigest) p.setText(self.password_digest) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.nonce_has_encoding: n.set("EncodingType", nonce_encoding_type) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(DateTime(self.created))) root.append(n) return root
Get xml representation of the object. @return: The root node. @rtype: L{Element}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsse.py#L177-L203
suds-community/suds
suds/umx/attrlist.py
AttrList.skip
def skip(self, attr): """ Get whether to skip (filter-out) the specified attribute. @param attr: An attribute. @type attr: I{Attribute} @return: True if should be skipped. @rtype: bool """ ns = attr.namespace() skip = ( Namespace.xmlns[1], 'http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/envelope/', 'http://www.w3.org/2003/05/soap-envelope', ) return ( Namespace.xs(ns) or ns[1] in skip )
python
def skip(self, attr): """ Get whether to skip (filter-out) the specified attribute. @param attr: An attribute. @type attr: I{Attribute} @return: True if should be skipped. @rtype: bool """ ns = attr.namespace() skip = ( Namespace.xmlns[1], 'http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/envelope/', 'http://www.w3.org/2003/05/soap-envelope', ) return ( Namespace.xs(ns) or ns[1] in skip )
Get whether to skip (filter-out) the specified attribute. @param attr: An attribute. @type attr: I{Attribute} @return: True if should be skipped. @rtype: bool
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/umx/attrlist.py#L73-L88
suds-community/suds
suds/xsd/depsort.py
dependency_sort
def dependency_sort(dependency_tree): """ Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and its dependency list, as given in the input dependency tree. If B is directly or indirectly dependent on A and they are not both a part of the same dependency cycle (i.e. then A is neither directly nor indirectly dependent on B) then A needs to come before B. If A and B are a part of the same dependency cycle, i.e. if they are both directly or indirectly dependent on each other, then it does not matter which comes first. Any entries found listed as dependencies, but that do not have their own dependencies listed as well, are logged & ignored. @return: The sorted items. @rtype: list """ sorted = [] processed = set() for key, deps in dependency_tree.iteritems(): _sort_r(sorted, processed, key, deps, dependency_tree) return sorted
python
def dependency_sort(dependency_tree): """ Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and its dependency list, as given in the input dependency tree. If B is directly or indirectly dependent on A and they are not both a part of the same dependency cycle (i.e. then A is neither directly nor indirectly dependent on B) then A needs to come before B. If A and B are a part of the same dependency cycle, i.e. if they are both directly or indirectly dependent on each other, then it does not matter which comes first. Any entries found listed as dependencies, but that do not have their own dependencies listed as well, are logged & ignored. @return: The sorted items. @rtype: list """ sorted = [] processed = set() for key, deps in dependency_tree.iteritems(): _sort_r(sorted, processed, key, deps, dependency_tree) return sorted
Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and its dependency list, as given in the input dependency tree. If B is directly or indirectly dependent on A and they are not both a part of the same dependency cycle (i.e. then A is neither directly nor indirectly dependent on B) then A needs to come before B. If A and B are a part of the same dependency cycle, i.e. if they are both directly or indirectly dependent on each other, then it does not matter which comes first. Any entries found listed as dependencies, but that do not have their own dependencies listed as well, are logged & ignored. @return: The sorted items. @rtype: list
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/depsort.py#L27-L57
suds-community/suds
suds/xsd/depsort.py
_sort_r
def _sort_r(sorted, processed, key, deps, dependency_tree): """Recursive topological sort implementation.""" if key in processed: return processed.add(key) for dep_key in deps: dep_deps = dependency_tree.get(dep_key) if dep_deps is None: log.debug('"%s" not found, skipped', Repr(dep_key)) continue _sort_r(sorted, processed, dep_key, dep_deps, dependency_tree) sorted.append((key, deps))
python
def _sort_r(sorted, processed, key, deps, dependency_tree): """Recursive topological sort implementation.""" if key in processed: return processed.add(key) for dep_key in deps: dep_deps = dependency_tree.get(dep_key) if dep_deps is None: log.debug('"%s" not found, skipped', Repr(dep_key)) continue _sort_r(sorted, processed, dep_key, dep_deps, dependency_tree) sorted.append((key, deps))
Recursive topological sort implementation.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/depsort.py#L60-L71
suds-community/suds
suds/xsd/sxbasic.py
TypedContent.resolve
def resolve(self, nobuiltin=False): """ Resolve the node's type reference and return the referenced type node. Returns self if the type is defined locally, e.g. as a <complexType> subnode. Otherwise returns the referenced external node. @param nobuiltin: Flag indicating whether resolving to XSD built-in types should not be allowed. @return: The resolved (true) type. @rtype: L{SchemaObject} """ cached = self.resolved_cache.get(nobuiltin) if cached is not None: return cached resolved = self.__resolve_type(nobuiltin) self.resolved_cache[nobuiltin] = resolved return resolved
python
def resolve(self, nobuiltin=False): """ Resolve the node's type reference and return the referenced type node. Returns self if the type is defined locally, e.g. as a <complexType> subnode. Otherwise returns the referenced external node. @param nobuiltin: Flag indicating whether resolving to XSD built-in types should not be allowed. @return: The resolved (true) type. @rtype: L{SchemaObject} """ cached = self.resolved_cache.get(nobuiltin) if cached is not None: return cached resolved = self.__resolve_type(nobuiltin) self.resolved_cache[nobuiltin] = resolved return resolved
Resolve the node's type reference and return the referenced type node. Returns self if the type is defined locally, e.g. as a <complexType> subnode. Otherwise returns the referenced external node. @param nobuiltin: Flag indicating whether resolving to XSD built-in types should not be allowed. @return: The resolved (true) type. @rtype: L{SchemaObject}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L45-L63
suds-community/suds
suds/xsd/sxbasic.py
TypedContent.__resolve_type
def __resolve_type(self, nobuiltin=False): """ Private resolve() worker without any result caching. @param nobuiltin: Flag indicating whether resolving to XSD built-in types should not be allowed. @return: The resolved (true) type. @rtype: L{SchemaObject} """ # There is no need for a recursive implementation here since a node can # reference an external type node but XSD specification explicitly # states that that external node must not be a reference to yet another # node. qref = self.qref() if qref is None: return self query = TypeQuery(qref) query.history = [self] log.debug("%s, resolving: %s\n using:%s", self.id, qref, query) resolved = query.execute(self.schema) if resolved is None: log.debug(self.schema) raise TypeNotFound(qref) if resolved.builtin() and nobuiltin: return self return resolved
python
def __resolve_type(self, nobuiltin=False): """ Private resolve() worker without any result caching. @param nobuiltin: Flag indicating whether resolving to XSD built-in types should not be allowed. @return: The resolved (true) type. @rtype: L{SchemaObject} """ # There is no need for a recursive implementation here since a node can # reference an external type node but XSD specification explicitly # states that that external node must not be a reference to yet another # node. qref = self.qref() if qref is None: return self query = TypeQuery(qref) query.history = [self] log.debug("%s, resolving: %s\n using:%s", self.id, qref, query) resolved = query.execute(self.schema) if resolved is None: log.debug(self.schema) raise TypeNotFound(qref) if resolved.builtin() and nobuiltin: return self return resolved
Private resolve() worker without any result caching. @param nobuiltin: Flag indicating whether resolving to XSD built-in types should not be allowed. @return: The resolved (true) type. @rtype: L{SchemaObject}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L65-L91
suds-community/suds
suds/xsd/sxbasic.py
Element.implany
def implany(self): """ Set the type to <xsd:any/> when implicit. An element has an implicit <xsd:any/> type when it has no body and no explicitly defined type. @return: self @rtype: L{Element} """ if self.type is None and self.ref is None and self.root.isempty(): self.type = self.anytype()
python
def implany(self): """ Set the type to <xsd:any/> when implicit. An element has an implicit <xsd:any/> type when it has no body and no explicitly defined type. @return: self @rtype: L{Element} """ if self.type is None and self.ref is None and self.root.isempty(): self.type = self.anytype()
Set the type to <xsd:any/> when implicit. An element has an implicit <xsd:any/> type when it has no body and no explicitly defined type. @return: self @rtype: L{Element}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L389-L401
suds-community/suds
suds/xsd/sxbasic.py
Element.namespace
def namespace(self, prefix=None): """ Get this schema element's target namespace. In case of reference elements, the target namespace is defined by the referenced and not the referencing element node. @param prefix: The default prefix. @type prefix: str @return: The schema element's target namespace @rtype: (I{prefix},I{URI}) """ e = self.__deref() if e is not None: return e.namespace(prefix) return super(Element, self).namespace()
python
def namespace(self, prefix=None): """ Get this schema element's target namespace. In case of reference elements, the target namespace is defined by the referenced and not the referencing element node. @param prefix: The default prefix. @type prefix: str @return: The schema element's target namespace @rtype: (I{prefix},I{URI}) """ e = self.__deref() if e is not None: return e.namespace(prefix) return super(Element, self).namespace()
Get this schema element's target namespace. In case of reference elements, the target namespace is defined by the referenced and not the referencing element node. @param prefix: The default prefix. @type prefix: str @return: The schema element's target namespace @rtype: (I{prefix},I{URI})
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L443-L459
suds-community/suds
suds/xsd/sxbasic.py
Import.open
def open(self, options, loaded_schemata): """ Open and import the referenced schema. @param options: An options dictionary. @type options: L{options.Options} @param loaded_schemata: Already loaded schemata cache (URL --> Schema). @type loaded_schemata: dict @return: The referenced schema. @rtype: L{Schema} """ if self.opened: return self.opened = True log.debug("%s, importing ns='%s', location='%s'", self.id, self.ns[1], self.location) result = self.__locate() if result is None: if self.location is None: log.debug("imported schema (%s) not-found", self.ns[1]) else: url = self.location if "://" not in url: url = urljoin(self.schema.baseurl, url) result = (loaded_schemata.get(url) or self.__download(url, loaded_schemata, options)) log.debug("imported:\n%s", result) return result
python
def open(self, options, loaded_schemata): """ Open and import the referenced schema. @param options: An options dictionary. @type options: L{options.Options} @param loaded_schemata: Already loaded schemata cache (URL --> Schema). @type loaded_schemata: dict @return: The referenced schema. @rtype: L{Schema} """ if self.opened: return self.opened = True log.debug("%s, importing ns='%s', location='%s'", self.id, self.ns[1], self.location) result = self.__locate() if result is None: if self.location is None: log.debug("imported schema (%s) not-found", self.ns[1]) else: url = self.location if "://" not in url: url = urljoin(self.schema.baseurl, url) result = (loaded_schemata.get(url) or self.__download(url, loaded_schemata, options)) log.debug("imported:\n%s", result) return result
Open and import the referenced schema. @param options: An options dictionary. @type options: L{options.Options} @param loaded_schemata: Already loaded schemata cache (URL --> Schema). @type loaded_schemata: dict @return: The referenced schema. @rtype: L{Schema}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L552-L580
suds-community/suds
suds/xsd/sxbasic.py
Import.__locate
def __locate(self): """Find the schema locally.""" if self.ns[1] != self.schema.tns[1]: return self.schema.locate(self.ns)
python
def __locate(self): """Find the schema locally.""" if self.ns[1] != self.schema.tns[1]: return self.schema.locate(self.ns)
Find the schema locally.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L582-L585
suds-community/suds
suds/xsd/sxbasic.py
Import.__download
def __download(self, url, loaded_schemata, options): """Download the schema.""" try: reader = DocumentReader(options) d = reader.open(url) root = d.root() root.set("url", url) return self.schema.instance(root, url, loaded_schemata, options) except TransportError: msg = "import schema (%s) at (%s), failed" % (self.ns[1], url) log.error("%s, %s", self.id, msg, exc_info=True) raise Exception(msg)
python
def __download(self, url, loaded_schemata, options): """Download the schema.""" try: reader = DocumentReader(options) d = reader.open(url) root = d.root() root.set("url", url) return self.schema.instance(root, url, loaded_schemata, options) except TransportError: msg = "import schema (%s) at (%s), failed" % (self.ns[1], url) log.error("%s, %s", self.id, msg, exc_info=True) raise Exception(msg)
Download the schema.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L587-L598
suds-community/suds
suds/xsd/sxbasic.py
Include.__applytns
def __applytns(self, root): """Make sure included schema has the same target namespace.""" TNS = "targetNamespace" tns = root.get(TNS) if tns is None: tns = self.schema.tns[1] root.set(TNS, tns) else: if self.schema.tns[1] != tns: raise Exception, "%s mismatch" % TNS
python
def __applytns(self, root): """Make sure included schema has the same target namespace.""" TNS = "targetNamespace" tns = root.get(TNS) if tns is None: tns = self.schema.tns[1] root.set(TNS, tns) else: if self.schema.tns[1] != tns: raise Exception, "%s mismatch" % TNS
Make sure included schema has the same target namespace.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbasic.py#L662-L671
suds-community/suds
suds/wsdl.py
WObject.resolve
def resolve(self, definitions): """ Resolve named references to other WSDL objects. Can be safely called multiple times. @param definitions: A definitions object. @type definitions: L{Definitions} """ if not self.__resolved: self.do_resolve(definitions) self.__resolved = True
python
def resolve(self, definitions): """ Resolve named references to other WSDL objects. Can be safely called multiple times. @param definitions: A definitions object. @type definitions: L{Definitions} """ if not self.__resolved: self.do_resolve(definitions) self.__resolved = True
Resolve named references to other WSDL objects. Can be safely called multiple times. @param definitions: A definitions object. @type definitions: L{Definitions}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L70-L82
suds-community/suds
suds/wsdl.py
Definitions.mktns
def mktns(self, root): """Get/create the target namespace.""" tns = root.get("targetNamespace") prefix = root.findPrefix(tns) if prefix is None: log.debug("warning: tns (%s), not mapped to prefix", tns) prefix = "tns" return (prefix, tns)
python
def mktns(self, root): """Get/create the target namespace.""" tns = root.get("targetNamespace") prefix = root.findPrefix(tns) if prefix is None: log.debug("warning: tns (%s), not mapped to prefix", tns) prefix = "tns" return (prefix, tns)
Get/create the target namespace.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L196-L203
suds-community/suds
suds/wsdl.py
Definitions.open_imports
def open_imports(self, imported_definitions): """Import the I{imported} WSDLs.""" for imp in self.imports: imp.load(self, imported_definitions)
python
def open_imports(self, imported_definitions): """Import the I{imported} WSDLs.""" for imp in self.imports: imp.load(self, imported_definitions)
Import the I{imported} WSDLs.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L230-L233
suds-community/suds
suds/wsdl.py
Definitions.add_methods
def add_methods(self, service): """Build method view for service.""" bindings = { "document/literal": Document(self), "rpc/literal": RPC(self), "rpc/encoded": Encoded(self)} for p in service.ports: binding = p.binding ptype = p.binding.type operations = p.binding.type.operations.values() for name in (op.name for op in operations): m = Facade("Method") m.name = name m.location = p.location m.binding = Facade("binding") op = binding.operation(name) m.soap = op.soap key = "/".join((op.soap.style, op.soap.input.body.use)) m.binding.input = bindings.get(key) key = "/".join((op.soap.style, op.soap.output.body.use)) m.binding.output = bindings.get(key) p.methods[name] = m
python
def add_methods(self, service): """Build method view for service.""" bindings = { "document/literal": Document(self), "rpc/literal": RPC(self), "rpc/encoded": Encoded(self)} for p in service.ports: binding = p.binding ptype = p.binding.type operations = p.binding.type.operations.values() for name in (op.name for op in operations): m = Facade("Method") m.name = name m.location = p.location m.binding = Facade("binding") op = binding.operation(name) m.soap = op.soap key = "/".join((op.soap.style, op.soap.input.body.use)) m.binding.input = bindings.get(key) key = "/".join((op.soap.style, op.soap.output.body.use)) m.binding.output = bindings.get(key) p.methods[name] = m
Build method view for service.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L261-L282
suds-community/suds
suds/wsdl.py
Import.import_definitions
def import_definitions(self, definitions, d): """Import/merge WSDL definitions.""" definitions.types += d.types definitions.messages.update(d.messages) definitions.port_types.update(d.port_types) definitions.bindings.update(d.bindings) self.imported = d log.debug("imported (WSDL):\n%s", d)
python
def import_definitions(self, definitions, d): """Import/merge WSDL definitions.""" definitions.types += d.types definitions.messages.update(d.messages) definitions.port_types.update(d.port_types) definitions.bindings.update(d.bindings) self.imported = d log.debug("imported (WSDL):\n%s", d)
Import/merge WSDL definitions.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L363-L370
suds-community/suds
suds/wsdl.py
Import.import_schema
def import_schema(self, definitions, d): """Import schema as <types/> content.""" if not definitions.types: root = Element("types", ns=wsdlns) definitions.root.insert(root) types = Types(root, definitions) definitions.types.append(types) else: types = definitions.types[-1] types.root.append(d.root) log.debug("imported (XSD):\n%s", d.root)
python
def import_schema(self, definitions, d): """Import schema as <types/> content.""" if not definitions.types: root = Element("types", ns=wsdlns) definitions.root.insert(root) types = Types(root, definitions) definitions.types.append(types) else: types = definitions.types[-1] types.root.append(d.root) log.debug("imported (XSD):\n%s", d.root)
Import schema as <types/> content.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L372-L382
suds-community/suds
suds/wsdl.py
PortType.operation
def operation(self, name): """ Shortcut used to get a contained operation by name. @param name: An operation name. @type name: str @return: The named operation. @rtype: Operation @raise L{MethodNotFound}: When not found. """ try: return self.operations[name] except Exception, e: raise MethodNotFound(name)
python
def operation(self, name): """ Shortcut used to get a contained operation by name. @param name: An operation name. @type name: str @return: The named operation. @rtype: Operation @raise L{MethodNotFound}: When not found. """ try: return self.operations[name] except Exception, e: raise MethodNotFound(name)
Shortcut used to get a contained operation by name. @param name: An operation name. @type name: str @return: The named operation. @rtype: Operation @raise L{MethodNotFound}: When not found.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L555-L569
suds-community/suds
suds/wsdl.py
Binding.soaproot
def soaproot(self): """Get the soap:binding.""" for ns in (soapns, soap12ns): sr = self.root.getChild("binding", ns=ns) if sr is not None: return sr
python
def soaproot(self): """Get the soap:binding.""" for ns in (soapns, soap12ns): sr = self.root.getChild("binding", ns=ns) if sr is not None: return sr
Get the soap:binding.
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L605-L610
suds-community/suds
suds/wsdl.py
Binding.do_resolve
def do_resolve(self, definitions): """ Resolve named references to other WSDL objects. This includes cross-linking information (from) the portType (to) the I{SOAP} protocol information on the binding for each operation. @param definitions: A definitions object. @type definitions: L{Definitions} """ self.__resolveport(definitions) for op in self.operations.values(): self.__resolvesoapbody(definitions, op) self.__resolveheaders(definitions, op) self.__resolvefaults(definitions, op)
python
def do_resolve(self, definitions): """ Resolve named references to other WSDL objects. This includes cross-linking information (from) the portType (to) the I{SOAP} protocol information on the binding for each operation. @param definitions: A definitions object. @type definitions: L{Definitions} """ self.__resolveport(definitions) for op in self.operations.values(): self.__resolvesoapbody(definitions, op) self.__resolveheaders(definitions, op) self.__resolvefaults(definitions, op)
Resolve named references to other WSDL objects. This includes cross-linking information (from) the portType (to) the I{SOAP} protocol information on the binding for each operation. @param definitions: A definitions object. @type definitions: L{Definitions}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L696-L710
suds-community/suds
suds/wsdl.py
Binding.__resolveport
def __resolveport(self, definitions): """ Resolve port_type reference. @param definitions: A definitions object. @type definitions: L{Definitions} """ ref = qualify(self.type, self.root, definitions.tns) port_type = definitions.port_types.get(ref) if port_type is None: raise Exception("portType '%s', not-found" % (self.type,)) # Later on we will require access to the message data referenced by # this port_type instance, and in order for those data references to be # available, port_type first needs to dereference its message # identification string. The only scenario where the port_type might # possibly not have already resolved its references, and where this # explicit resolve() call is required, is if we are dealing with a # recursive WSDL import chain. port_type.resolve(definitions) self.type = port_type
python
def __resolveport(self, definitions): """ Resolve port_type reference. @param definitions: A definitions object. @type definitions: L{Definitions} """ ref = qualify(self.type, self.root, definitions.tns) port_type = definitions.port_types.get(ref) if port_type is None: raise Exception("portType '%s', not-found" % (self.type,)) # Later on we will require access to the message data referenced by # this port_type instance, and in order for those data references to be # available, port_type first needs to dereference its message # identification string. The only scenario where the port_type might # possibly not have already resolved its references, and where this # explicit resolve() call is required, is if we are dealing with a # recursive WSDL import chain. port_type.resolve(definitions) self.type = port_type
Resolve port_type reference. @param definitions: A definitions object. @type definitions: L{Definitions}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L712-L732
suds-community/suds
suds/wsdl.py
Service.port
def port(self, name): """ Locate a port by name. @param name: A port name. @type name: str @return: The port object. @rtype: L{Port} """ for p in self.ports: if p.name == name: return p
python
def port(self, name): """ Locate a port by name. @param name: A port name. @type name: str @return: The port object. @rtype: L{Port} """ for p in self.ports: if p.name == name: return p
Locate a port by name. @param name: A port name. @type name: str @return: The port object. @rtype: L{Port}
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L910-L922