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 None:
type_hints = self.fetch_data_types(table_name)
return TableData(
table_name,
columns,
result.fetchall(),
type_hints=[type_hints.get(col) for col in columns],
)
|
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: |arg_select_extra|
:return: Table data as a :py:class:`tabledata.TableData` instance.
:rtype: tabledata.TableData
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
.. note::
``pandas`` package required to execute this method.
| 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|
:return: Table data as |OrderedDict| instances.
:rtype: |list| of |OrderedDict|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-select-as-dict`
| 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_schema.index_list,
)
return memdb
|
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_select_extra|
:return:
Table data as a |SimpleSQLite| instance that connected to in
memory database.
:rtype: |SimpleSQLite|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
| 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:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-insert-records`
| 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_names
)
)
else:
logger.debug(
"insert {number} records into {table}".format(
number=len(records) if records else 0, table=table_name
)
)
if typepy.is_empty_sequence(records):
return 0
if attr_names is None:
attr_names = self.fetch_attr_names(table_name)
records = RecordConvertor.to_records(attr_names, records)
query = Insert(table_name, AttrList(attr_names)).to_query()
if self.debug_query or self.global_debug_query:
logging_count = 8
num_records = len(records)
logs = [query] + [
" record {:4d}: {}".format(i, record)
for i, record in enumerate(records[:logging_count])
]
if num_records - logging_count > 0:
logs.append(
" and other {} records will be inserted".format(num_records - logging_count)
)
logger.debug("\n".join(logs))
try:
self.connection.executemany(query, records)
except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
caller = logging.getLogger().findCaller()
file_path, line_no, func_name = caller[:3]
raise OperationalError(
"{:s}({:d}) {:s}: failed to execute query:\n".format(file_path, line_no, func_name)
+ " query={}\n".format(query)
+ " msg='{}'\n".format(e)
+ " db={}\n".format(self.database_path)
+ " records={}\n".format(records[:2])
)
return len(records)
|
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 IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-insert-records`
| 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.
Defaults to |None|.
Raises:
IOError:
|raises_write_permission|
simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
simplesqlite.OperationalError:
|raises_operational_error|
| 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 is None:
return None
fetch = result.fetchone()
if fetch is None:
return None
return fetch[0]
|
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_where_type|
:return: Result of execution of the query.
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
| 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 simplesqlite import SimpleSQLite
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
"hoge",
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.fetch_table_names())
:Output:
.. code-block:: python
['hoge']
| 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_operational_error|
:Example:
.. code:: python
import simplesqlite
table_name = "sample_table"
con = simplesqlite.SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
table_name,
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.fetch_attr_names(table_name))
try:
print(con.fetch_attr_names("not_existing"))
except simplesqlite.TableNotFoundError as e:
print(e)
:Output:
.. parsed-literal::
['attr_a', 'attr_b']
'not_existing' table not found in /tmp/sample.sqlite
| 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 get_entry(items):
key = " ".join(items[:-1])
value = items[-1]
return [key, value]
return dict([get_entry(item.split(" ")) for item in match.group().strip("()").split(", ")])
|
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 simplesqlite.OperationalError: |raises_operational_error|
| 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 the table not found in the database.
:rtype: int
| 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_query", "cumulative_time", "count")
con_tmp = connect_memdb()
try:
con_tmp.create_table_from_data_matrix(
profile_table_name, attr_names, data_matrix=value_matrix
)
except ValueError:
return []
try:
result = con_tmp.select(
select="{:s},SUM({:s}),SUM({:s})".format(*attr_names),
table_name=profile_table_name,
extra="GROUP BY {:s} ORDER BY {:s} DESC LIMIT {:d}".format(
attr_names[0], attr_names[1], profile_count
),
)
except sqlite3.OperationalError:
return []
if result is None:
return []
SqliteProfile = namedtuple("SqliteProfile", " ".join(attr_names))
return [SqliteProfile(*profile) for profile in result.fetchall()]
|
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|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-get-profile`
| 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_table_from_data_matrix(
"hoge",
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.has_table("hoge"))
print(con.has_table("not_existing"))
:Output:
.. code-block:: python
True
False
| 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:
.. code:: python
import simplesqlite
table_name = "sample_table"
con = simplesqlite.SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
table_name,
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.has_attr(table_name, "attr_a"))
print(con.has_attr(table_name, "not_existing"))
try:
print(con.has_attr("not_existing", "attr_a"))
except simplesqlite.TableNotFoundError as e:
print(e)
:Output:
.. parsed-literal::
True
False
'not_existing' table not found in /tmp/sample.sqlite
| 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:
.. code:: python
import simplesqlite
table_name = "sample_table"
con = simplesqlite.SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
table_name,
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.has_attrs(table_name, ["attr_a"]))
print(con.has_attrs(table_name, ["attr_a", "attr_b"]))
print(con.has_attrs(table_name, ["attr_a", "attr_b", "not_existing"]))
try:
print(con.has_attr("not_existing", ["attr_a"]))
except simplesqlite.TableNotFoundError as e:
print(e)
:Output:
.. parsed-literal::
True
True
False
'not_existing' table not found in /tmp/sample.sqlite
| 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
table_name = "sample_table"
con = simplesqlite.SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
table_name,
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
con.verify_table_existence(table_name)
try:
con.verify_table_existence("not_existing")
except simplesqlite.TableNotFoundError as e:
print(e)
:Output:
.. parsed-literal::
'not_existing' table not found in /tmp/sample.sqlite
| 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|
:Sample Code:
.. code:: python
from simplesqlite import (
SimpleSQLite,
TableNotFoundError,
AttributeNotFoundError
)
table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
table_name,
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
con.verify_attr_existence(table_name, "attr_a")
try:
con.verify_attr_existence(table_name, "not_existing")
except AttributeNotFoundError as e:
print(e)
try:
con.verify_attr_existence("not_existing", "attr_a")
except TableNotFoundError as e:
print(e)
:Output:
.. parsed-literal::
'not_existing' attribute not found in 'sample_table' table
'not_existing' table not found in /tmp/sample.sqlite
| 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 '".join(valid_permissions), self.mode
)
)
|
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.NullDatabaseConnectionError:
|raises_check_connection|
| 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.getLogger().findCaller())
self.commit()
|
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(query)
if self.execute_query(query, logging.getLogger().findCaller()) is None:
return False
return True
|
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_name),
attr=Attr(attr_name),
)
logger.debug(query)
self.execute_query(query, logging.getLogger().findCaller())
|
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 simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
| 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_attr_set)):
self.create_index(table_name, attribute)
|
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|/|list|/|tuple|
:param str primary_key: |primary_key|
:param tuple index_attrs: |index_attrs|
:raises simplesqlite.NameValidationError:
|raises_validate_table_name|
:raises simplesqlite.NameValidationError:
|raises_validate_attr_name|
:raises ValueError: If the ``data_matrix`` is empty.
:Example:
:ref:`example-create-table-from-data-matrix`
.. seealso::
:py:meth:`.create_table`
:py:meth:`.insert_many`
:py:meth:`.create_index_list`
| 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.encoding = encoding
try:
for table_data in loader.load():
self.__create_table_from_tabledata(
table_data, primary_key, add_primary_key_column, index_attrs
)
return
except (ptr.InvalidFilePathError, IOError):
pass
loader = ptr.CsvTableTextLoader(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.encoding = encoding
for table_data in loader.load():
self.__create_table_from_tabledata(
table_data, primary_key, add_primary_key_column, index_attrs
)
|
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.
Use the first line of the CSV file as attributes if ``attr_names`` is empty.
:param str delimiter:
A one-character string used to separate fields.
:param str quotechar:
A one-character string used to quote fields containing special
characters, such as the ``delimiter`` or ``quotechar``,
or which contain new-line characters.
:param str encoding: CSV file encoding.
:param str primary_key: |primary_key|
:param tuple index_attrs: |index_attrs|
:raises ValueError: If the CSV data is invalid.
:Dependency Packages:
- `pytablereader <https://github.com/thombashi/pytablereader>`__
:Example:
:ref:`example-create-table-from-csv`
.. seealso::
:py:meth:`.create_table_from_data_matrix`
:py:func:`csv.reader`
:py:meth:`.pytablereader.CsvTableFileLoader.load`
:py:meth:`.pytablereader.CsvTableTextLoader.load`
| 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(
table_data, primary_key, add_primary_key_column, index_attrs
)
return
except (ptr.InvalidFilePathError, IOError):
pass
loader = ptr.JsonTableTextLoader(json_source)
if typepy.is_not_null_string(table_name):
loader.table_name = table_name
for table_data in loader.load():
self.__create_table_from_tabledata(
table_data, primary_key, add_primary_key_column, index_attrs
)
|
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://github.com/thombashi/pytablereader>`__
:Examples:
:ref:`example-create-table-from-json`
.. seealso::
:py:meth:`.pytablereader.JsonTableFileLoader.load`
:py:meth:`.pytablereader.JsonTableTextLoader.load`
| 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-create-table-from-df`
| 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 SQLite database: path='{}'".format(self.database_path))
self.commit()
self.connection.close()
self.__initialize_connection()
|
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 OperationalError(e)
connection.close()
|
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_idx, col_dp in enumerate(table_data.column_dp_list)
]
)
|
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)
dst_con.validate_access_permission(["w", "a"])
if dst_con.has_table(table_name):
src_attrs = src_con.fetch_attr_names(table_name)
dst_attrs = dst_con.fetch_attr_names(table_name)
if src_attrs != dst_attrs:
raise ValueError(
dedent(
.format(
src_attrs, dst_attrs
)
)
)
primary_key, index_attrs, type_hints = extract_table_metadata(src_con, table_name)
dst_con.create_table_from_tabledata(
src_con.select_as_tabledata(table_name, type_hints=type_hints),
primary_key=primary_key,
index_attrs=index_attrs,
)
return True
|
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: bool
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises ValueError:
If attributes of the table are different from each other.
| 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_name)
dst_con.validate_access_permission(["w", "a"])
if dst_con.has_table(dst_table_name):
if is_overwrite:
dst_con.drop_table(dst_table_name)
else:
logger.error(
"failed to copy table: the table already exists "
"(src_table={}, dst_table={})".format(src_table_name, dst_table_name)
)
return False
primary_key, index_attrs, _ = extract_table_metadata(src_con, src_table_name)
result = src_con.select(select="*", table_name=src_table_name)
if result is None:
return False
dst_con.create_table_from_data_matrix(
dst_table_name,
src_con.fetch_attr_names(src_table_name),
result.fetchall(),
primary_key=primary_key,
index_attrs=index_attrs,
)
return True
|
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_overwrite: If |True|, overwrite existing table.
:return: |True| if the copy operation succeed.
:rtype: bool
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises ValueError:
If attributes of the table are different from each other.
| 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 by sqlite".format(name))
if name in __SQLITE_VALID_RESERVED_KEYWORDS_TABLE:
raise ValidReservedNameError("'{:s}' is a reserved keyword by sqlite".format(name))
|
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 name.
:raises pathvalidate.ValidReservedNameError:
|raises_sqlite_keywords|
However, valid as a table name.
| 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 sqlite".format(name))
if name in __SQLITE_VALID_RESERVED_KEYWORDS_ATTR:
raise ValidReservedNameError("'{}' is a reserved keyword by sqlite".format(name))
|
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 attribute name.
:raises pathvalidate.ValidReservedNameError:
|raises_sqlite_keywords|
However, valid as an attribute name.
| 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(encoding)
elif isinstance(v, (list, tuple, set)):
return type(v)([_generic_convert_string(element, from_type, to_type, encoding) for element in v])
elif isinstance(v, dict):
return {k: _generic_convert_string(v, from_type, to_type, encoding) for k, v in v.iteritems()}
return v
|
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 convert
:param to_type: The target string type to convert to
:param encoding: When
:return:
| 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 strtype == six.text_type or strtype == 'unicode':
# We want to convert from str to unicode
return _generic_convert_string(arg, six.binary_type, six.text_type, encoding)
raise TypeError('standardize_strings() called with an invalid strtype: "{}". Allowed values: str or unicode'
.format(repr(strtype)))
|
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 been set to True
# the date is decoded as DateTime object
return datetime.datetime.strptime(date.value, "%Y%m%dT%H:%M:%S")
else:
# If date is given as str (or unicode for python 2)
# This is the normal behavior for JSON-RPC
try:
return datetime.datetime.strptime(date, date_format)
except ValueError:
if raise_exception:
raise
else:
return None
|
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: If the given date is a str, format is passed to strptime to parse it
:param raise_exception: If set to True, an exception will be raised if the input string cannot be parsed
:return: A valid ``datetime.datetime`` instance
| 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]
rpc_method.modernrpc_auth_predicates_params = [params]
return rpc_method
return wrapper
|
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 information
if <condition>:
# The condition to execute the method are met
return True
return False
:param predicate:
:param params:
:return:
| 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 handled by {}'.format(handler_cls.__name__))
result = handler.process_request()
return handler.result_success(result)
except AuthenticationFailed as e:
# Customize HttpResponse instance used when AuthenticationFailed was raised
logger.warning(e)
return handler.result_error(e, HttpResponseForbidden)
except RPCException as e:
logger.warning('RPC exception: {}'.format(e), exc_info=settings.MODERNRPC_LOG_EXCEPTIONS)
return handler.result_error(e)
except Exception as e:
logger.error('Exception raised from a RPC method: "{}"'.format(e),
exc_info=settings.MODERNRPC_LOG_EXCEPTIONS)
return handler.result_error(RPCInternalError(str(e)))
logger.error('Unable to handle incoming request.')
return HttpResponse('Unable to handle your request. Please ensure you called the right entry point. If not, '
'this could be a server error.')
|
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
registry.reset()
if not settings.MODERNRPC_METHODS_MODULES:
# settings.MODERNRPC_METHODS_MODULES is undefined or empty, but we already notified user
# with check_required_settings_defined() function. See http://docs.djangoproject.com/en/1.10/topics/checks/
return
# Lookup content of MODERNRPC_METHODS_MODULES, and add the module containing system methods
for module_name in settings.MODERNRPC_METHODS_MODULES + ['modernrpc.system_methods']:
try:
# Import the module in current scope
rpc_module = import_module(module_name)
except ImportError:
msg = 'Unable to load module "{}" declared in settings.MODERNRPC_METHODS_MODULES. Please ensure ' \
'it is available and doesn\'t contains any error'.format(module_name)
warnings.warn(msg, category=Warning)
continue
# Lookup all global functions in module
for _, func in inspect.getmembers(rpc_module, inspect.isfunction):
# And register only functions with attribute 'modernrpc_enabled' defined to True
if getattr(func, 'modernrpc_enabled', False):
registry.register_method(func)
logger.info('django-modern-rpc initialized: {} RPC methods registered'.format(registry.total_count()))
|
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.com/a/1087736/1887976
if 'HTTP_AUTHORIZATION' in request.META:
auth_data = request.META['HTTP_AUTHORIZATION'].split()
if len(auth_data) == 2 and auth_data[0].lower() == "basic":
uname, passwd = base64.b64decode(auth_data[1]).decode('utf-8').split(':')
django_user = authenticate(username=uname, password=passwd)
if django_user is not None:
login(request, django_user)
# In all cases, return the current request's user (may be anonymous user if no login succeed)
try:
return request.user
except AttributeError:
return AnonymousUser()
|
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(func)
|
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, [auth.user_in_any_group, groups])
|
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 = str_standardization_encoding
return _func
# If @rpc_method() is used with parenthesis (with or without argument)
if func is None:
return decorated
# If @rpc_method is used without parenthesis
return decorated(func)
|
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 protocol: Default: ALL. Used to limit usage of the RPC method for a specific protocol (JSONRPC or XMLRPC)
:param str_standardization: Default: settings.MODERNRPC_PY2_STR_TYPE. Configure string standardization on python 2.
Ignored on python 3.
:param str_standardization_encoding: Default: settings.MODERNRPC_PY2_STR_ENCODING. Configure the encoding used
to perform string standardization conversion. Ignored on python 3.
:type name: str
:type entry_point: str
:type protocol: str
:type str_standardization: type str or unicode
:type str_standardization_encoding: str
| 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)
for line in docstring.split('\n'):
# Empty line
if not line:
raw_docstring += '\n'
continue
param_match = PARAM_REXP.match(line)
if param_match:
param_name, description = param_match.group(1, 2)
if param_name == 'kwargs':
continue
doc = self.args_doc.setdefault(param_name, {})
doc['text'] = description
continue
param_type_match = PARAM_TYPE_REXP.match(line)
if param_type_match:
param_name, param_type = param_type_match.group(1, 2)
if param_name == 'kwargs':
continue
doc = self.args_doc.setdefault(param_name, {})
doc['type'] = param_type
self.signature.append(param_type)
continue
return_match = RETURN_REXP.match(line)
if return_match:
return_description = return_match.group(1)
self.return_doc['text'] = return_description
continue
return_type_match = RETURN_TYPE_REXP.match(line)
if return_type_match:
return_description = return_type_match.group(1)
self.return_doc['type'] = return_description
self.signature.insert(0, return_description)
continue
# Line doesn't match with known args/return regular expressions,
# add the line to raw help text
raw_docstring += line + '\n'
return raw_docstring
|
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" member.
All other lines are added to the returned string
:param content: The full docstring
:type content: str
:return: The parsed method description
:rtype: str
| 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 settings.MODERNRPC_DOC_FORMAT.lower() in ('md', 'markdown'):
import markdown
result = markdown.markdown(self.raw_docstring)
else:
result = "<p>{}</p>".format(self.raw_docstring.replace('\n\n', '</p><p>').replace('\n', ' '))
return result
|
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(func, 'modernrpc_name', func.__name__)
logger.debug('Register RPC method "{}"'.format(name))
if name.startswith('rpc.'):
raise ImproperlyConfigured('According to RPC standard, method names starting with "rpc." are reserved for '
'system extensions and must not be used. See '
'http://www.jsonrpc.org/specification#extensions for more information.')
# Encapsulate the function in a RPCMethod object
method = RPCMethod(func)
# Ensure method names are unique in the registry
existing_method = self.get_method(method.name, ALL, ALL)
if existing_method is not None:
# Trying to register many times the same function is OK, because if a method is decorated
# with @rpc_method(), it could be imported in different places of the code
if method == existing_method:
return method.name
# But if we try to use the same name to register 2 different methods, we
# must inform the developer there is an error in the code
else:
raise ImproperlyConfigured("A RPC method with name {} has already been registered".format(method.name))
# Store the method
self._registry[method.name] = method
logger.debug('Method registered. len(registry): {}'.format(len(self._registry)))
return method.name
|
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 redirecting errors to the default 'lastResort' StreamHandler on Python 3
logger.addHandler(logging.NullHandler())
return logger
|
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.check_permissions(self.request):
raise AuthenticationFailed(name)
logger.debug('RPC method {} will be executed'.format(name))
# Replace default None value with empty instance of corresponding type
args = args or []
kwargs = kwargs or {}
# If the RPC method needs to access some internals, update kwargs dict
if _method.accept_kwargs:
kwargs.update({
REQUEST_KEY: self.request,
ENTRY_POINT_KEY: self.entry_point,
PROTOCOL_KEY: self.protocol,
HANDLER_KEY: self,
})
if six.PY2:
method_std, encoding = _method.str_standardization, _method.str_std_encoding
args = modernrpc.compat.standardize_strings(args, strtype=method_std, encoding=encoding)
kwargs = modernrpc.compat.standardize_strings(kwargs, strtype=method_std, encoding=encoding)
logger.debug('Params: args = {} - kwargs = {}'.format(args, kwargs))
try:
# Call the rpc method, as standard python function
return _method.function(*args, **kwargs)
except TypeError as e:
# If given arguments cannot be transmitted properly to python function,
# raise an Invalid Params exceptions
raise RPCInvalidParams(str(e))
|
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 array describing types of return values and method arguments
| 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_doc
|
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=call.get('params'))
# From https://mirrors.talideon.com/articles/multicall.html:
# "Notice that regular return values are always nested inside a one-element array. This allows you to
# return structs from functions without confusing them with faults."
results.append([result])
except RPCException as e:
results.append({
'faultCode': e.code,
'faultString': e.message,
})
except Exception as e:
results.append({
'faultCode': RPC_INTERNAL_ERROR,
'faultString': str(e),
})
return results
|
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:
while token_code is None or len(token_code) != 6:
token_code = getpass.getpass("MFA Token Code: ")
return serial_number, token_code, OK
|
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 corresponding to the identity profile and delete it.
current_access_key = next((key for key
in iam.CurrentUser().access_keys.all()
if key.access_key_id == current_access_key_id))
current_access_key.delete()
# create the new access key pair
iam_service = session3.client('iam')
new_access_key_pair = iam_service.create_access_key()["AccessKey"]
print("Rotating from %s to %s." % (current_access_key.access_key_id,
new_access_key_pair['AccessKeyId']),
file=sys.stderr)
update_credentials_file(args.aws_credentials,
args.identity_profile,
args.identity_profile,
credentials,
new_access_key_pair)
print("%s profile updated." % args.identity_profile, file=sys.stderr)
return OK
|
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: `current page`
:return: `list` of `dict`
| 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': [
{
'order_item_id': str, # Order item ID to be refunded
'qty': int # Items quantity to be refunded
},
...
],
'shipping_amount': float # refund shipping amount (optional)
'adjustment_positive': float # adjustment refund amount (optional)
'adjustment_negative': float # adjustment fee amount (optional)
}
:param comment: Credit memo Comment
:type comment: str
:param email: send e-mail flag (optional)
:type email: bool
:param include_comment: include comment in e-mail flag (optional)
:type include_comment: bool
:param refund_to_store_credit_amount: amount to refund to store credit
:type refund_to_store_credit_amount: float
:return str, increment id of credit memo created
| 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
:param email: send e-mail flag (optional)
:type email: bool
:param include_comment: include comment in e-mail flag (optional)
:type include_comment: bool
| 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.