code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if columns is None:
columns = self.fetch_attr_names(table_name)
result = self.select(
select=AttrList(columns), table_name=table_name, where=where, extra=extra
)
if result is None:
return TableData(None, [], [])
if type_hints is No... | def select_as_tabledata(
self, table_name, columns=None, where=None, extra=None, type_hints=None
) | Get data in the database and return fetched data as a
:py:class:`tabledata.TableData` instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra:... | 2.716909 | 2.821933 | 0.962783 |
return self.select_as_tabledata(table_name, columns, where, extra).as_dict().get(table_name) | def select_as_dict(self, table_name, columns=None, where=None, extra=None) | Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
... | 4.662224 | 7.289186 | 0.639608 |
table_schema = self.schema_extractor.fetch_table_schema(table_name)
memdb = connect_memdb()
memdb.create_table_from_tabledata(
self.select_as_tabledata(table_name, columns, where, extra),
primary_key=table_schema.primary_key,
index_attrs=table_schem... | def select_as_memdb(self, table_name, columns=None, where=None, extra=None) | Get data in the database and return fetched data as a
in-memory |SimpleSQLite| instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_s... | 3.886637 | 4.234458 | 0.917859 |
self.insert_many(table_name, records=[record], attr_names=attr_names) | def insert(self, table_name, record, attr_names=None) | Send an INSERT query to the database.
:param str table_name: Table name of executing the query.
:param record: Record to be inserted.
:type record: |dict|/|namedtuple|/|list|/|tuple|
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
... | 3.905722 | 5.912067 | 0.660636 |
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name)
if attr_names:
logger.debug(
"insert {number} records into {table}({attrs})".format(
number=len(records) if records else 0, table=table_name, attrs=attr_... | def insert_many(self, table_name, records, attr_names=None) | Send an INSERT query with multiple records to the database.
:param str table: Table name of executing the query.
:param records: Records to be inserted.
:type records: list of |dict|/|namedtuple|/|list|/|tuple|
:return: Number of inserted records.
:rtype: int
:raises IOE... | 2.687796 | 2.688378 | 0.999784 |
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name)
query = SqlQuery.make_update(table_name, set_query, where)
return self.execute_query(query, logging.getLogger().findCaller()) | def update(self, table_name, set_query, where=None) | Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (|str|):
``SET`` clause for the update query.
where (|arg_where_type| , optional):
``WHERE`` clause for the update query.
... | 5.898991 | 5.615378 | 1.050507 |
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name)
query = "DELETE FROM {:s}".format(table_name)
if where:
query += " WHERE {:s}".format(where)
return self.execute_query(query, logging.getLogger().findCaller()) | def delete(self, table_name, where=None) | Send a DELETE query to the database.
:param str table_name: Table name of executing the query.
:param where: |arg_select_where|
:type where: |arg_where_type| | 4.217363 | 4.415834 | 0.955055 |
try:
self.verify_table_existence(table_name)
except TableNotFoundError as e:
logger.debug(e)
return None
result = self.execute_query(
Select(select, table_name, where, extra), logging.getLogger().findCaller()
)
if result ... | def fetch_value(self, select, table_name, where=None, extra=None) | Fetch a value from the table. Return |None| if no value matches
the conditions, or the table not found in the database.
:param str select: Attribute for SELECT query
:param str table_name: Table name of executing the query.
:param where: |arg_select_where|
:type where: |arg_wher... | 3.444597 | 3.435354 | 1.00269 |
self.check_connection()
return self.schema_extractor.fetch_table_names(include_system_table) | def fetch_table_names(self, include_system_table=False) | :return: List of table names in the database.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Sample Code:
.. code:: python
from simplesql... | 4.996569 | 6.320101 | 0.790584 |
self.verify_table_existence(table_name)
return self.schema_extractor.fetch_table_schema(table_name).get_attr_names() | def fetch_attr_names(self, table_name) | :return: List of attribute names in the table.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operatio... | 5.182369 | 5.355503 | 0.967672 |
self.verify_table_existence(table_name)
result = self.execute_query(
"SELECT sql FROM sqlite_master WHERE type='table' and name={:s}".format(
Value(table_name)
)
)
query = result.fetchone()[0]
match = re.search("[(].*[)]", query)... | def fetch_attr_type(self, table_name) | :return:
Dictionary of attribute names and attribute types in the table.
:rtype: dict
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesql... | 3.681721 | 3.3402 | 1.102246 |
return self.fetch_value(select="COUNT(*)", table_name=table_name, where=where) | def fetch_num_records(self, table_name, where=None) | Fetch the number of records in a table.
:param str table_name: Table name to get number of records.
:param where: |arg_select_where|
:type where: |arg_where_type|
:return:
Number of records in the table.
|None| if no value matches the conditions,
or t... | 5.096454 | 5.27476 | 0.966196 |
from collections import namedtuple
profile_table_name = "sql_profile"
value_matrix = [
[query, execute_time, self.__dict_query_count.get(query, 0)]
for query, execute_time in six.iteritems(self.__dict_query_totalexectime)
]
attr_names = ("sql_q... | def get_profile(self, profile_count=50) | Get profile of query execution time.
:param int profile_count:
Number of profiles to retrieve,
counted from the top query in descending order by
the cumulative execution time.
:return: Profile information for each query.
:rtype: list of |namedtuple|
:... | 3.667454 | 3.398396 | 1.079172 |
try:
validate_table_name(table_name)
except NameValidationError:
return False
return table_name in self.fetch_table_names() | def has_table(self, table_name) | :param str table_name: Table name to be tested.
:return: |True| if the database has the table.
:rtype: bool
:Sample Code:
.. code:: python
from simplesqlite import SimpleSQLite
con = SimpleSQLite("sample.sqlite", "w")
con.create_tabl... | 5.107428 | 6.119946 | 0.834554 |
self.verify_table_existence(table_name)
if typepy.is_null_string(attr_name):
return False
return attr_name in self.fetch_attr_names(table_name) | def has_attr(self, table_name, attr_name) | :param str table_name: Table name that the attribute exists.
:param str attr_name: Attribute name to be tested.
:return: |True| if the table has the attribute.
:rtype: bool
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:Sample Code:
... | 3.726009 | 3.408803 | 1.093055 |
if typepy.is_empty_sequence(attr_names):
return False
not_exist_fields = [
attr_name for attr_name in attr_names if not self.has_attr(table_name, attr_name)
]
if not_exist_fields:
return False
return True | def has_attrs(self, table_name, attr_names) | :param str table_name: Table name that attributes exists.
:param str attr_names: Attribute names to tested.
:return: |True| if the table has all of the attribute.
:rtype: bool
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:Sample Code:
... | 2.865578 | 2.964694 | 0.966568 |
validate_table_name(table_name)
if self.has_table(table_name):
return
raise TableNotFoundError(
"'{}' table not found in '{}' database".format(table_name, self.database_path)
) | def verify_table_existence(self, table_name) | :param str table_name: Table name to be tested.
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.NameValidationError:
|raises_validate_table_name|
:Sample Code:
.. code:: python
import simplesqlite... | 3.705358 | 3.443192 | 1.07614 |
self.verify_table_existence(table_name)
if self.has_attr(table_name, attr_name):
return
raise AttributeNotFoundError(
"'{}' attribute not found in '{}' table".format(attr_name, table_name)
) | def verify_attr_existence(self, table_name, attr_name) | :param str table_name: Table name that the attribute exists.
:param str attr_name: Attribute name to tested.
:raises simplesqlite.AttributeNotFoundError:
If attribute not found in the table
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
... | 2.866036 | 2.375029 | 1.206737 |
self.check_connection()
if typepy.is_null_string(self.mode):
raise ValueError("mode is not set")
if self.mode not in valid_permissions:
raise IOError(
"invalid access: expected-mode='{}', current-mode='{}'".format(
"' or '".... | def validate_access_permission(self, valid_permissions) | :param valid_permissions:
List of permissions that access is allowed.
:type valid_permissions: |list|/|tuple|
:raises ValueError: If the |attr_mode| is invalid.
:raises IOError:
If the |attr_mode| not in the ``valid_permissions``.
:raises simplesqlite.NullDatabase... | 4.120682 | 3.553945 | 1.159467 |
self.validate_access_permission(["w", "a"])
if table_name in SQLITE_SYSTEM_TABLES:
# warning message
return
if self.has_table(table_name):
query = "DROP TABLE IF EXISTS '{:s}'".format(table_name)
self.execute_query(query, logging.getLog... | def drop_table(self, table_name) | :param str table_name: Table name to drop.
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises IOError: |raises_write_permission| | 5.663353 | 5.35386 | 1.057807 |
self.validate_access_permission(["w", "a"])
table_name = table_name.strip()
if self.has_table(table_name):
return True
query = "CREATE TABLE IF NOT EXISTS '{:s}' ({:s})".format(
table_name, ", ".join(attr_descriptions)
)
logger.debug(qu... | def create_table(self, table_name, attr_descriptions) | :param str table_name: Table name to create.
:param list attr_descriptions: List of table description.
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises IOError: |raises_write_permission| | 3.856457 | 3.89475 | 0.990168 |
self.verify_table_existence(table_name)
self.validate_access_permission(["w", "a"])
query_format = "CREATE INDEX IF NOT EXISTS {index:s} ON {table}({attr})"
query = query_format.format(
index=make_index_name(table_name, attr_name),
table=Table(table_nam... | def create_index(self, table_name, attr_name) | :param str table_name:
Table name that contains the attribute to be indexed.
:param str attr_name: Attribute name to create index.
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simple... | 4.164475 | 3.864143 | 1.077723 |
self.validate_access_permission(["w", "a"])
if typepy.is_empty_sequence(attr_names):
return
table_attr_set = set(self.fetch_attr_names(table_name))
index_attr_set = set(AttrList.sanitize(attr_names))
for attribute in list(table_attr_set.intersection(index... | def create_index_list(self, table_name, attr_names) | :param str table_name: Table name that exists attribute.
:param list attr_names:
List of attribute names to create indices.
Ignore attributes that are not existing in the table.
.. seealso:: :py:meth:`.create_index` | 4.168543 | 4.245335 | 0.981911 |
self.__create_table_from_tabledata(
TableData(table_name, attr_names, data_matrix),
primary_key,
add_primary_key_column,
index_attrs,
) | def create_table_from_data_matrix(
self,
table_name,
attr_names,
data_matrix,
primary_key=None,
add_primary_key_column=False,
index_attrs=None,
) | Create a table if not exists. Moreover, insert data into the created
table.
:param str table_name: Table name to create.
:param list attr_names: Attribute names of the table.
:param data_matrix: Data to be inserted into the table.
:type data_matrix: List of |dict|/|namedtuple|/|... | 2.745861 | 3.661729 | 0.749881 |
self.__create_table_from_tabledata(
table_data, primary_key, add_primary_key_column, index_attrs
) | def create_table_from_tabledata(
self, table_data, primary_key=None, add_primary_key_column=False, index_attrs=None
) | Create a table from :py:class:`tabledata.TableData`.
:param tabledata.TableData table_data: Table data to create.
:param str primary_key: |primary_key|
:param tuple index_attrs: |index_attrs|
.. seealso::
:py:meth:`.create_table_from_data_matrix` | 2.402583 | 2.863938 | 0.838909 |
import pytablereader as ptr
loader = ptr.CsvTableFileLoader(csv_source)
if typepy.is_not_null_string(table_name):
loader.table_name = table_name
loader.headers = attr_names
loader.delimiter = delimiter
loader.quotechar = quotechar
loader.enc... | def create_table_from_csv(
self,
csv_source,
table_name="",
attr_names=(),
delimiter=",",
quotechar='"',
encoding="utf-8",
primary_key=None,
add_primary_key_column=False,
index_attrs=None,
) | Create a table from a CSV file/text.
:param str csv_source: Path to the CSV file or CSV text.
:param str table_name:
Table name to create.
Using CSV file basename as the table name if the value is empty.
:param list attr_names:
Attribute names of the table.
... | 1.898063 | 1.83101 | 1.036621 |
import pytablereader as ptr
loader = ptr.JsonTableFileLoader(json_source)
if typepy.is_not_null_string(table_name):
loader.table_name = table_name
try:
for table_data in loader.load():
self.__create_table_from_tabledata(
... | def create_table_from_json(
self,
json_source,
table_name="",
primary_key=None,
add_primary_key_column=False,
index_attrs=None,
) | Create a table from a JSON file/text.
:param str json_source: Path to the JSON file or JSON text.
:param str table_name: Table name to create.
:param str primary_key: |primary_key|
:param tuple index_attrs: |index_attrs|
:Dependency Packages:
- `pytablereader <https... | 2.116455 | 2.059412 | 1.027699 |
self.__create_table_from_tabledata(
TableData.from_dataframe(dataframe=dataframe, table_name=table_name),
primary_key,
add_primary_key_column,
index_attrs,
) | def create_table_from_dataframe(
self,
dataframe,
table_name="",
primary_key=None,
add_primary_key_column=False,
index_attrs=None,
) | Create a table from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe: DataFrame instance to convert.
:param str table_name: Table name to create.
:param str primary_key: |primary_key|
:param tuple index_attrs: |index_attrs|
:Examples:
:ref:`example-cre... | 2.859684 | 3.492764 | 0.818745 |
try:
self.check_connection()
except NullDatabaseConnectionError:
return
logger.debug("rollback: path='{}'".format(self.database_path))
self.connection.rollback() | def rollback(self) | .. seealso:: :py:meth:`sqlite3.Connection.rollback` | 7.235945 | 6.481492 | 1.116401 |
try:
self.check_connection()
except NullDatabaseConnectionError:
return
logger.debug("commit: path='{}'".format(self.database_path))
try:
self.connection.commit()
except sqlite3.ProgrammingError:
pass | def commit(self) | .. seealso:: :py:meth:`sqlite3.Connection.commit` | 5.789229 | 4.980114 | 1.162469 |
if self.__delayed_connection_path and self.__connection is None:
self.__initialize_connection()
return
try:
self.check_connection()
except (SystemError, NullDatabaseConnectionError):
return
logger.debug("close connection to a SQ... | def close(self) | Commit and close the connection.
.. seealso:: :py:meth:`sqlite3.Connection.close` | 7.62156 | 6.675678 | 1.141691 |
self.__validate_db_path(database_path)
if not os.path.isfile(os.path.realpath(database_path)):
raise IOError("file not found: " + database_path)
try:
connection = sqlite3.connect(database_path)
except sqlite3.OperationalError as e:
raise Ope... | def __verify_db_file_existence(self, database_path) | :raises SimpleSQLite.OperationalError: If unable to open database file. | 2.507792 | 2.320653 | 1.080641 |
typename_table = {
typepy.Typecode.INTEGER: "INTEGER",
typepy.Typecode.REAL_NUMBER: "REAL",
typepy.Typecode.STRING: "TEXT",
}
return dict(
[
[col_idx, typename_table.get(col_dp.typecode, "TEXT")]
for col_i... | def __extract_col_type_from_tabledata(table_data) | Extract data type name for each column as SQLite names.
:param tabledata.TableData table_data:
:return: { column_number : column_data_type }
:rtype: dictionary | 3.453067 | 3.463806 | 0.996899 |
try:
validate_sqlite_table_name(name)
except (InvalidCharError, InvalidReservedNameError) as e:
raise NameValidationError(e)
except NullNameError:
raise NameValidationError("table name is empty")
except ValidReservedNameError:
pass | def validate_table_name(name) | :param str name: Table name to validate.
:raises NameValidationError: |raises_validate_table_name| | 6.006074 | 5.665611 | 1.060093 |
try:
validate_sqlite_attr_name(name)
except (InvalidCharError, InvalidReservedNameError) as e:
raise NameValidationError(e)
except NullNameError:
raise NameValidationError("attribute name is empty") | def validate_attr_name(name) | :param str name: Name to validate.
:raises NameValidationError: |raises_validate_attr_name| | 6.325979 | 5.857601 | 1.079961 |
logger.debug(
"append table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}".format(
src_db=src_con.database_path,
src_tbl=table_name,
dst_db=dst_con.database_path,
dst_tbl=table_name,
)
)
src_con.verify_table_existence(table_name)
d... | def append_table(src_con, dst_con, table_name) | Append a table from source database to destination database.
:param SimpleSQLite src_con: Connection to the source database.
:param SimpleSQLite dst_con: Connection to the destination database.
:param str table_name: Table name to append.
:return: |True| if the append operation succeed.
:rtype: boo... | 2.717288 | 2.425656 | 1.120228 |
logger.debug(
"copy table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}".format(
src_db=src_con.database_path,
src_tbl=src_table_name,
dst_db=dst_con.database_path,
dst_tbl=dst_table_name,
)
)
src_con.verify_table_existence(src_table_n... | def copy_table(src_con, dst_con, src_table_name, dst_table_name, is_overwrite=True) | Copy a table from source to destination.
:param SimpleSQLite src_con: Connection to the source database.
:param SimpleSQLite dst_con: Connection to the destination database.
:param str src_table_name: Source table name to copy.
:param str dst_table_name: Destination table name.
:param bool is_overw... | 2.368612 | 2.236633 | 1.059008 |
if not name:
raise NullNameError("null name")
if __RE_INVALID_CHARS.search(name):
raise InvalidCharError("unprintable character found")
name = name.upper()
if name in __SQLITE_INVALID_RESERVED_KEYWORDS_TABLE:
raise InvalidReservedNameError("'{:s}' is a reserved keyword b... | def validate_sqlite_table_name(name) | :param str name: Name to validate.
:raises pathvalidate.NullNameError: If the ``name`` is empty.
:raises pathvalidate.InvalidCharError:
If the ``name`` includes unprintable character(s).
:raises pathvalidate.InvalidReservedNameError:
|raises_sqlite_keywords|
And invalid as a table na... | 3.85999 | 2.716909 | 1.420729 |
if not name:
raise NullNameError("null name")
if __RE_INVALID_CHARS.search(name):
raise InvalidCharError("unprintable character found")
name = name.upper()
if name in __SQLITE_INVALID_RESERVED_KEYWORDS_ATTR:
raise InvalidReservedNameError("'{}' is a reserved keyword by s... | def validate_sqlite_attr_name(name) | :param str name: Name to validate.
:raises pathvalidate.NullNameError: If the ``name`` is empty.
:raises pathvalidate.InvalidCharError:
If the ``name`` includes unprintable character(s).
:raises pathvalidate.InvalidReservedNameError:
|raises_sqlite_keywords|
And invalid as an attribu... | 3.845647 | 2.648266 | 1.452138 |
assert six.PY2, "This function should be used with Python 2 only"
assert from_type != to_type
if from_type == six.binary_type and isinstance(v, six.binary_type):
return six.text_type(v, encoding)
elif from_type == six.text_type and isinstance(v, six.text_type):
return v.encode(en... | def _generic_convert_string(v, from_type, to_type, encoding) | Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 interpreter only.
:param v: The value to convert
:param from_type: The original string type to con... | 1.992227 | 2.015805 | 0.988304 |
assert six.PY2, "This function should be used with Python 2 only"
if not strtype:
return arg
if strtype == six.binary_type or strtype == 'str':
# We want to convert from unicode to str
return _generic_convert_string(arg, six.text_type, six.binary_type, encoding)
elif strt... | def standardize_strings(arg, strtype=settings.MODERNRPC_PY2_STR_TYPE, encoding=settings.MODERNRPC_PY2_STR_ENCODING) | Python 2 only. Lookup given *arg* and convert its str or unicode value according to MODERNRPC_PY2_STR_TYPE and
MODERNRPC_PY2_STR_ENCODING settings. | 2.96823 | 2.934067 | 1.011643 |
if isinstance(date, datetime.datetime):
# Default XML-RPC handler is configured to decode dateTime.iso8601 type
# to builtin datetime.datetim instance
return date
elif isinstance(date, xmlrpc_client.DateTime):
# If constant settings.MODERNRPC_XMLRPC_USE_BUILTIN_TYPES has bee... | def get_builtin_date(date, date_format="%Y-%m-%dT%H:%M:%S", raise_exception=False) | Try to convert a date to a builtin instance of ``datetime.datetime``.
The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime``
instance. The returned object is a ``datetime.datetime``.
:param date: The date object to convert.
:param date_format:... | 5.863155 | 5.954787 | 0.984612 |
def wrapper(rpc_method):
if hasattr(rpc_method, 'modernrpc_auth_predicates'):
rpc_method.modernrpc_auth_predicates.append(predicate)
rpc_method.modernrpc_auth_predicates_params.append(params)
else:
rpc_method.modernrpc_auth_predicates = [predicate]
... | def set_authentication_predicate(predicate, params=()) | Assign a new authentication predicate to an RPC method.
This is the most generic decorator used to implement authentication.
Predicate is a standard function with the following signature:
.. code:: python
def my_predicate(request, *params):
# Inspect request and extract required informat... | 2.32934 | 2.484943 | 0.937381 |
if isinstance(group, Group):
return user_is_superuser(user) or group in user.groups.all()
elif isinstance(group, six.string_types):
return user_is_superuser(user) or user.groups.filter(name=group).exists()
raise TypeError("'group' argument must be a string or a Group instance") | def user_in_group(user, group) | Returns True if the given user is in given group | 2.227546 | 2.277077 | 0.978248 |
return user_is_superuser(user) or any(user_in_group(user, group) for group in groups) | def user_in_any_group(user, groups) | Returns True if the given user is in at least 1 of the given groups | 2.900193 | 3.396314 | 0.853924 |
return user_is_superuser(user) or all(user_in_group(user, group) for group in groups) | def user_in_all_groups(user, groups) | Returns True if the given user is in all given groups | 3.247441 | 3.493171 | 0.929654 |
handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS]
if self.protocol == ALL:
return handler_classes
else:
return [cls for cls in handler_classes if cls.protocol in ensure_sequence(self.protocol)] | def get_handler_classes(self) | Return the list of handlers to use when receiving RPC requests. | 5.255347 | 4.664296 | 1.126718 |
logger.debug('RPC request received...')
for handler_cls in self.get_handler_classes():
handler = handler_cls(request, self.entry_point)
try:
if not handler.can_handle():
continue
logger.debug('Request will be handl... | def post(self, request, *args, **kwargs) | Handle a XML-RPC or JSON-RPC request.
:param request: Incoming request
:param args: Additional arguments
:param kwargs: Additional named arguments
:return: A HttpResponse containing XML-RPC or JSON-RPC response, depending on the incoming request | 4.184867 | 4.014093 | 1.042543 |
kwargs.update({
'methods': registry.get_all_methods(self.entry_point, sort_methods=True),
})
return super(RPCEntryPoint, self).get_context_data(**kwargs) | def get_context_data(self, **kwargs) | Update context data with list of RPC methods of the current entry point.
Will be used to display methods documentation page | 6.365006 | 3.890378 | 1.63609 |
# In previous version, django-modern-rpc used the django cache system to store methods registry.
# It is useless now, so clean the cache from old data
clean_old_cache_content()
# For security (and unit tests), make sure the registry is empty before registering rpc methods
... | def rpc_methods_registration() | Look into each module listed in settings.MODERNRPC_METHODS_MODULES, import each module and register
functions annotated with @rpc_method decorator in the registry | 5.533629 | 5.066376 | 1.092226 |
try:
# If standard auth middleware already authenticated a user, use it
if user_is_authenticated(request.user):
return request.user
except AttributeError:
pass
# This was grabbed from https://www.djangosnippets.org/snippets/243/
# Thanks to http://stackoverflow... | def http_basic_auth_get_user(request) | Inspect the given request to find a logged user. If not found, the header HTTP_AUTHORIZATION
is read for 'Basic Auth' login and password, and try to authenticate against default UserModel.
Always return a User instance (possibly anonymous, meaning authentication failed) | 3.107059 | 2.96982 | 1.046211 |
wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated])
# If @http_basic_auth_login_required() is used (with parenthesis)
if func is None:
return wrapper
# If @http_basic_auth_login_required is used without parenthesis
return wrapper(func... | def http_basic_auth_login_required(func=None) | Decorator. Use it to specify a RPC method is available only to logged users | 5.376212 | 5.012391 | 1.072584 |
wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_superuser])
# If @http_basic_auth_superuser_required() is used (with parenthesis)
if func is None:
return wrapper
# If @http_basic_auth_superuser_required is used without parenthesis
return wrapper(... | def http_basic_auth_superuser_required(func=None) | Decorator. Use it to specify a RPC method is available only to logged superusers | 5.23695 | 4.934689 | 1.061252 |
if isinstance(permissions, six.string_types):
return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_has_perm, permissions])
else:
return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_has_all_perms, permissions]) | def http_basic_auth_permissions_required(permissions) | Decorator. Use it to specify a RPC method is available only to logged users with given permissions | 3.697607 | 3.685361 | 1.003323 |
if isinstance(groups, six.string_types):
# Check user is in a group
return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_group, groups])
else:
# Check user is in many group
return auth.set_authentication_predicate(http_basic_auth_check_user, [a... | def http_basic_auth_group_member_required(groups) | Decorator. Use it to specify a RPC method is available only to logged users with given permissions | 3.563878 | 3.804702 | 0.936704 |
def decorated(_func):
_func.modernrpc_enabled = True
_func.modernrpc_name = name or _func.__name__
_func.modernrpc_entry_point = entry_point
_func.modernrpc_protocol = protocol
_func.str_standardization = str_standardization
_func.str_standardization_encoding =... | def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL,
str_standardization=settings.MODERNRPC_PY2_STR_TYPE,
str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING) | Mark a standard python function as RPC method.
All arguments are optional
:param func: A standard function
:param name: Used as RPC method name instead of original function name
:param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points
:param protoc... | 2.420764 | 2.491831 | 0.97148 |
return registry.get_all_method_names(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods) | def get_all_method_names(entry_point=ALL, protocol=ALL, sort_methods=False) | For backward compatibility. Use registry.get_all_method_names() instead (with same arguments) | 2.40845 | 1.560583 | 1.543302 |
return registry.get_all_methods(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods) | def get_all_methods(entry_point=ALL, protocol=ALL, sort_methods=False) | For backward compatibility. Use registry.get_all_methods() instead (with same arguments) | 2.499706 | 1.618829 | 1.544145 |
if not content:
return
raw_docstring = ''
# We use the helper defined in django admindocs app to remove indentation chars from docstring,
# and parse it as title, body, metadata. We don't use metadata for now.
docstring = trim_docstring(content)
fo... | def parse_docstring(self, content) | Parse the given full docstring, and extract method description, arguments, and return documentation.
This method try to find arguments description and types, and put the information in "args_doc" and "signature"
members. Also parse return type and description, and put the information in "return_doc" me... | 2.78493 | 2.631096 | 1.058468 |
if not self.raw_docstring:
result = ''
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'):
from docutils.core import publish_parts
result = publish_parts(self.raw_docstring, writer_name='html')['body']
elif sett... | def html_doc(self) | Methods docstring, as HTML | 3.131921 | 2.874068 | 1.089717 |
if not self.predicates:
return True
# All registered authentication predicates must return True
return all(
predicate(request, *self.predicates_params[i])
for i, predicate in enumerate(self.predicates)
) | def check_permissions(self, request) | Call the predicate(s) associated with the RPC method, to check if the current request
can actually call the method.
Return a boolean indicating if the method should be executed (True) or not (False) | 5.736254 | 5.36868 | 1.068466 |
if self.protocol == ALL or protocol == ALL:
return True
return protocol in ensure_sequence(self.protocol) | def available_for_protocol(self, protocol) | Check if the current function can be executed from a request defining the given protocol | 9.316373 | 8.251643 | 1.129032 |
if self.entry_point == ALL or entry_point == ALL:
return True
return entry_point in ensure_sequence(self.entry_point) | def available_for_entry_point(self, entry_point) | Check if the current function can be executed from a request to the given entry point | 6.923401 | 6.103075 | 1.134412 |
return self.available_for_entry_point(entry_point) and self.available_for_protocol(protocol) | def is_valid_for(self, entry_point, protocol) | Check if the current function can be executed from a request to the given entry point
and with the given protocol | 3.505571 | 3.026556 | 1.158271 |
return bool(self.return_doc and (self.return_doc.get('text') or self.return_doc.get('type'))) | def is_return_doc_available(self) | Returns True if this method's return is documented | 4.600663 | 3.721574 | 1.236214 |
if not getattr(func, 'modernrpc_enabled', False):
raise ImproperlyConfigured('Error: trying to register {} as RPC method, but it has not been decorated.'
.format(func.__name__))
# Define the external name of the function
name = getattr... | def register_method(self, func) | Register a function to be available as RPC method.
The given function will be inspected to find external_name, protocol and entry_point values set by the decorator
@rpc_method.
:param func: A function previously decorated using @rpc_method
:return: The name of registered method | 4.710615 | 4.536716 | 1.038331 |
method_names = [
name for name, method in self._registry.items() if method.is_valid_for(entry_point, protocol)
]
if sort_methods:
method_names = sorted(method_names)
return method_names | def get_all_method_names(self, entry_point=ALL, protocol=ALL, sort_methods=False) | Return the names of all RPC methods registered supported by the given entry_point / protocol pair | 2.522849 | 2.578157 | 0.978548 |
if sort_methods:
return [
method for (_, method) in sorted(self._registry.items()) if method.is_valid_for(entry_point, protocol)
]
return self._registry.values() | def get_all_methods(self, entry_point=ALL, protocol=ALL, sort_methods=False) | Return a list of all methods in the registry supported by the given entry_point / protocol pair | 3.685244 | 3.539521 | 1.04117 |
if name in self._registry and self._registry[name].is_valid_for(entry_point, protocol):
return self._registry[name]
return None | def get_method(self, name, entry_point, protocol) | Retrieve a method from the given name | 3.459107 | 3.593573 | 0.962582 |
if six.PY3:
return logger.hasHandlers()
else:
c = logger
rv = False
while c:
if c.handlers:
rv = True
break
if not c.propagate:
break
else:
c = c.parent
return rv | def logger_has_handlers(logger) | Check if given logger has at least 1 handler associated, return a boolean value.
Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. | 3.065067 | 2.922123 | 1.048918 |
logger = logging.getLogger(name)
if not logger_has_handlers(logger):
# If logging is not configured in the current project, configure this logger to discard all logs messages.
# This will prevent the 'No handlers could be found for logger XXX' error on Python 2,
# and avoid redirect... | def get_modernrpc_logger(name) | Get a logger from default logging manager. If no handler is associated, add a default NullHandler | 6.909035 | 6.754679 | 1.022852 |
_method = registry.get_method(name, self.entry_point, self.protocol)
if not _method:
raise RPCUnknownMethod(name)
logger.debug('Check authentication / permissions for method {} and user {}'
.format(name, self.request.user))
if not _method.che... | def execute_procedure(self, name, args=None, kwargs=None) | Call the concrete python function corresponding to given RPC Method `name` and return the result.
Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class. | 4.958766 | 4.545015 | 1.091034 |
entry_point = kwargs.get(ENTRY_POINT_KEY)
protocol = kwargs.get(PROTOCOL_KEY)
return registry.get_all_method_names(entry_point, protocol, sort_methods=True) | def __system_listMethods(**kwargs) | Returns a list of all methods available in the current entry point | 5.449768 | 4.733945 | 1.15121 |
entry_point = kwargs.get(ENTRY_POINT_KEY)
protocol = kwargs.get(PROTOCOL_KEY)
method = registry.get_method(method_name, entry_point, protocol)
if method is None:
raise RPCInvalidParams('Unknown method {}. Unable to retrieve signature.'.format(method_name))
return method.signature | def __system_methodSignature(method_name, **kwargs) | Returns an array describing the signature of the given method name.
The result is an array with:
- Return type as first elements
- Types of method arguments from element 1 to N
:param method_name: Name of a method available for current entry point (and protocol)
:param kwargs:
:return: An arr... | 4.159936 | 4.275287 | 0.973019 |
entry_point = kwargs.get(ENTRY_POINT_KEY)
protocol = kwargs.get(PROTOCOL_KEY)
method = registry.get_method(method_name, entry_point, protocol)
if method is None:
raise RPCInvalidParams('Unknown method {}. Unable to retrieve its documentation.'.format(method_name))
return method.html_do... | def __system_methodHelp(method_name, **kwargs) | Returns the documentation of the given method name.
:param method_name: Name of a method available for current entry point (and protocol)
:param kwargs:
:return: Documentation text for the RPC method | 4.783614 | 4.271585 | 1.119869 |
if not isinstance(calls, list):
raise RPCInvalidParams('system.multicall first argument should be a list, {} given.'.format(type(calls)))
handler = kwargs.get(HANDLER_KEY)
results = []
for call in calls:
try:
result = handler.execute_procedure(call['methodName'], args... | def __system_multiCall(calls, **kwargs) | Call multiple RPC methods at once.
:param calls: An array of struct like {"methodName": string, "params": array }
:param kwargs: Internal data
:type calls: list
:type kwargs: dict
:return: | 5.03731 | 4.967358 | 1.014082 |
serial_number = find_mfa_for_user(args.serial_number, session, session3)
if not serial_number:
print("There are no MFA devices associated with this user.",
file=sys.stderr)
return None, None, USER_RECOVERABLE_ERROR
token_code = args.token_code
if token_code is None:
... | def acquire_code(args, session, session3) | returns the user's token serial number, MFA token code, and an
error code. | 3.515526 | 3.069883 | 1.145166 |
current_access_key_id = credentials.get(
args.identity_profile, 'aws_access_key_id')
# create new sessions using the MFA credentials
session, session3, err = make_session(args.target_profile)
if err:
return err
iam = session3.resource('iam')
# find the AccessKey correspond... | def rotate(args, credentials) | rotate the identity profile's AWS access key pair. | 3.719664 | 3.408738 | 1.091214 |
if self._coerce is not None:
value = self._coerce(value)
return value | def coerce(self, value) | Coerce a cleaned value. | 3.818295 | 3.299462 | 1.157248 |
pq_items = cls._get_items(*args, **kwargs)
return [cls(item=i) for i in pq_items.items()] | def all_from(cls, *args, **kwargs) | Query for items passing PyQuery args explicitly. | 6.951557 | 4.539601 | 1.531314 |
url = urljoin(cls._meta.base_url, path)
pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs)
item = pq_items.eq(index)
if not item:
raise ItemDoesNotExist("%s not found" % cls.__name__)
return cls(item=item) | def one(cls, path='', index=0) | Return ocurrence (the first one, unless specified) of the item. | 4.707282 | 4.617479 | 1.019448 |
url = urljoin(cls._meta.base_url, path)
pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs)
return [cls(item=i) for i in pq_items.items()] | def all(cls, path='') | Return all ocurrences of the item. | 6.128297 | 5.487829 | 1.116707 |
if attributes:
return self.call('customer.info', [id, attributes])
else:
return self.call('customer.info', [id]) | def info(self, id, attributes=None) | Retrieve customer data
:param id: ID of customer
:param attributes: `List` of attributes needed | 3.422028 | 4.687377 | 0.730052 |
options = {
'imported': False,
'filters': filters or {},
'fields': fields or [],
'limit': limit or 1000,
'page': page,
}
return self.call('sales_order.search', [options]) | def search(self, filters=None, fields=None, limit=None, page=1) | Retrieve order list by options using search api. Using this result can
be paginated
:param options: Dictionary of options.
:param filters: `{<attribute>:{<operator>:<value>}}`
:param fields: [<String: magento field names>, ...]
:param limit: `page limit`
:param page: `c... | 4.077217 | 4.935717 | 0.826064 |
if comment is None:
comment = ""
return bool(self.call(
'sales_order.addComment',
[order_increment_id, status, comment, notify]
)
) | def addcomment(self, order_increment_id,
status, comment=None, notify=False) | Add comment to order or change its state
:param order_increment_id: Order ID
TODO: Identify possible values for status | 5.063177 | 5.421735 | 0.933867 |
if comment is None:
comment = ''
return self.call(
'sales_order_creditmemo.create', [
order_increment_id, creditmemo_data, comment, email, include_comment, refund_to_store_credit_amount
]
) | def create(
self,
order_increment_id,
creditmemo_data=None,
comment=None,
email=False,
include_comment=False,
refund_to_store_credit_amount=None) | Create new credit_memo for order
:param order_increment_id: Order Increment ID
:type order_increment_id: str
:param creditmemo_data: Sales order credit memo data (optional)
:type creditmemo_data: associative array as dict
{
'qtys': [
{
... | 2.745832 | 3.302373 | 0.831472 |
return bool(
self.call(
'sales_order_creditmemo.addComment',
[creditmemo_increment_id, comment, email, include_in_email]
)
) | def addcomment(self, creditmemo_increment_id,
comment, email=True, include_in_email=False) | Add new comment to credit memo
:param creditmemo_increment_id: Credit memo increment ID
:return: bool | 4.462769 | 4.475573 | 0.997139 |
if comment is None:
comment = ''
return self.call(
'sales_order_shipment.create', [
order_increment_id, items_qty, comment, email, include_comment
]
) | def create(self, order_increment_id,
items_qty, comment=None, email=True, include_comment=False) | Create new shipment for order
:param order_increment_id: Order Increment ID
:type order_increment_id: str
:param items_qty: items qty to ship
:type items_qty: associative array (order_item_id ⇒ qty) as dict
:param comment: Shipment Comment
:type comment: str
:par... | 3.450429 | 3.509902 | 0.983056 |
return self.call(
'sales_order_shipment.addTrack',
[shipment_increment_id, carrier, title, track_number]
) | def addtrack(self, shipment_increment_id, carrier, title, track_number) | Add new tracking number
:param shipment_increment_id: Shipment ID
:param carrier: Carrier Code
:param title: Tracking title
:param track_number: Tracking Number | 4.675553 | 5.803007 | 0.805712 |
if comment is None:
comment = ""
return bool(
self.call(
'sales_order_invoice.addComment',
[invoice_increment_id, comment, email, include_comment]
)
) | def addcomment(self, invoice_increment_id,
comment=None, email=False, include_comment=False) | Add comment to invoice or change its state
:param invoice_increment_id: Invoice ID | 4.503908 | 5.187059 | 0.868297 |
if protocol == 'soap':
ws_part = 'api/?wsdl'
elif protocol == 'xmlrpc':
ws_part = 'index.php/api/xmlrpc'
else:
ws_part = 'index.php/rest/V1'
return url.endswith('/') and url + ws_part or url + '/' + ws_part | def expand_url(url, protocol) | Expands the given URL to a full URL by adding
the magento soap/wsdl parts
:param url: URL to be expanded
:param service: 'xmlrpc' or 'soap' | 4.178891 | 3.804776 | 1.098328 |
"Converts CamelCase to camel_case"
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | def camel_2_snake(name) | Converts CamelCase to camel_case | 1.89885 | 1.739918 | 1.091344 |
return self.call(
'catalog_category.level', [website, store_view, parent_category]
) | def level(self, website=None, store_view=None, parent_category=None) | Retrieve one level of categories by website/store view/parent category
:param website: Website code or ID
:param store_view: storeview code or ID
:param parent_category: Parent Category ID
:return: Dictionary | 6.102174 | 8.866233 | 0.688249 |
return self.call(
'catalog_category.info', [category_id, store_view, attributes]
) | def info(self, category_id, store_view=None, attributes=None) | Retrieve Category details
:param category_id: ID of category to retrieve
:param store_view: Store view ID or code
:param attributes: Return the fields specified
:return: Dictionary of data | 5.400898 | 7.010788 | 0.77037 |
return int(self.call(
'catalog_category.create', [parent_id, data, store_view])
) | def create(self, parent_id, data, store_view=None) | Create new category and return its ID
:param parent_id: ID of parent
:param data: Data for category
:param store_view: Store view ID or Code
:return: Integer ID | 8.567293 | 8.264727 | 1.036609 |
return bool(
self.call(
'catalog_category.update', [category_id, data, store_view]
)
) | def update(self, category_id, data, store_view=None) | Update Category
:param category_id: ID of category
:param data: Category Data
:param store_view: Store view ID or code
:return: Boolean | 6.803184 | 6.259713 | 1.08682 |
return bool(self.call(
'catalog_category.move', [category_id, parent_id, after_id])
) | def move(self, category_id, parent_id, after_id=None) | Move category in tree
:param category_id: ID of category to move
:param parent_id: New parent of the category
:param after_id: Category ID after what position it will be moved
:return: Boolean | 6.411464 | 6.621197 | 0.968324 |
return bool(self.call(
'catalog_category.assignProduct', [category_id, product, position])
) | def assignproduct(self, category_id, product, position=None) | Assign product to a category
:param category_id: ID of a category
:param product: ID or Code of the product
:param position: Position of product in category
:return: boolean | 8.640166 | 9.454964 | 0.913823 |
return bool(self.call(
'catalog_category.updateProduct', [category_id, product, position])
) | def updateproduct(self, category_id, product, position=None) | Update assigned product
:param category_id: ID of a category
:param product: ID or Code of the product
:param position: Position of product in category
:return: boolean | 8.64785 | 9.376328 | 0.922307 |
args = [store_view] if store_view else []
return int(self.call('catalog_category_attribute.currentStore', args)) | def currentStore(self, store_view=None) | Set/Get current store view
:param store_view: Store view ID or Code
:return: int | 10.711167 | 12.019883 | 0.891121 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.