pywikibot.data package¶
Module providing several layers of data access to the wiki.
Submodules¶
pywikibot.data.api module¶
Interface to Mediawiki’s api.php.
-
class
pywikibot.data.api.
APIGenerator
(action: str, continue_name: str = 'continue', limit_name: str = 'limit', data_name: str = 'data', **kwargs)[source]¶ Bases:
pywikibot.data.api._RequestWrapper
Iterator that handle API responses containing lists.
The iterator will iterate each item in the query response and use the continue request parameter to retrieve the next portion of items automatically. If the limit attribute is set, the iterator will stop after iterating that many values.
Initialize an APIGenerator object.
kwargs are used to create a Request object; see that object’s documentation for values.
- Parameters
action – API action name.
continue_name – Name of the continue API parameter.
limit_name – Name of the limit API parameter.
data_name – Name of the data in API response.
-
set_maximum_items
(value: Optional[Union[int, str]])[source]¶ Set the maximum number of items to be retrieved from the wiki.
If not called, most queries will continue as long as there is more data to be retrieved from the API.
- Parameters
value – The value of maximum number of items to be retrieved in total to set. Ignores None value.
-
class
pywikibot.data.api.
CTEBinaryBytesGenerator
(*args, **kwargs)[source]¶ Bases:
email.generator.BytesGenerator
Workaround for bug in python 3 email handling of CTE binary.
-
class
pywikibot.data.api.
CTEBinaryMIMEMultipart
(_subtype='mixed', boundary=None, _subparts=None, *, policy=None, **_params)[source]¶ Bases:
email.mime.multipart.MIMEMultipart
Workaround for bug in python 3 email handling of CTE binary.
Creates a multipart/* type message.
By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers.
_subtype is the subtype of the multipart content type, defaulting to `mixed’.
boundary is the multipart boundary string. By default it is calculated as needed.
_subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method.
Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument).
-
class
pywikibot.data.api.
CachedRequest
(expiry, *args, **kwargs)[source]¶ Bases:
pywikibot.data.api.Request
Cached request.
Initialize a CachedRequest object.
- Parameters
expiry – either a number of days or a datetime.timedelta object
-
class
pywikibot.data.api.
ListGenerator
(listaction: str, **kwargs)[source]¶ Bases:
pywikibot.data.api.QueryGenerator
Iterator for queries of type action=query&list=foo.
See the API documentation for types of lists that can be queried. Lists include both site-wide information (such as ‘allpages’) and page-specific information (such as ‘backlinks’).
This iterator yields a dict object for each member of the list returned by the API, with the format of the dict depending on the particular list command used. For those lists that contain page information, it may be easier to use the PageGenerator class instead, as that will convert the returned information into a Page object.
Required and optional parameters are as for
Request
, except that action=query is assumed and listaction is required.- Parameters
listaction – the “list=” type from api.php
-
class
pywikibot.data.api.
LogEntryListGenerator
(logtype=None, **kwargs)[source]¶ Bases:
pywikibot.data.api.ListGenerator
Iterator for queries of list ‘logevents’.
Yields LogEntry objects instead of dicts.
-
class
pywikibot.data.api.
LoginManager
(password: Optional[str] = None, site: Any = None, user: Optional[str] = None, username='[deprecated name of user]', verbose=NotImplemented, sysop=NotImplemented)[source]¶ Bases:
pywikibot.login.LoginManager
Supply login_to_site method to use API interface.
All parameters default to defaults in user-config.
- Parameters
site – Site object to log into
user – username to use. If user is None, the username is loaded from config.usernames.
password – password to use
- Raises
pywikibot.exceptions.NoUsernameError – No username is configured for the requested site.
-
get_login_token
() → Optional[str][source]¶ Fetch login token for MediaWiki 1.27+.
- Returns
login token
-
login_to_site
() → None[source]¶ Login to the site.
Note, this doesn’t do anything with cookies. The http module takes care of all the cookie stuff. Throws exception on failure.
-
mapping
= {'fail': ('Failed', 'FAIL'), 'ldap': ('lgdomain', 'domain'), 'password': ('lgpassword', 'password'), 'reason': ('reason', 'message'), 'result': ('result', 'status'), 'success': ('Success', 'PASS'), 'token': ('lgtoken', 'logintoken'), 'user': ('lgname', 'username')}¶
-
pywikibot.data.api.
MIMEMultipart
¶
-
class
pywikibot.data.api.
OptionSet
(site=None, module: Optional[str] = None, param: Optional[str] = None, dict: Optional[dict] = None)[source]¶ Bases:
collections.abc.MutableMapping
A class to store a set of options which can be either enabled or not.
If it is instantiated with the associated site, module and parameter it will only allow valid names as options. If instantiated ‘lazy loaded’ it won’t checks if the names are valid until the site has been set (which isn’t required, but recommended). The site can only be set once if it’s not None and after setting it, any site (even None) will fail.
If a site is given, the module and param must be given too.
- Parameters
site (pywikibot.site.APISite or None) – The associated site
module – The module name which is used by paraminfo. (Ignored when site is None)
param – The parameter name inside the module. That parameter must have a ‘type’ entry. (Ignored when site is None)
dict – The initializing dict which is used for
from_dict
-
from_dict
(dictionary)[source]¶ Load options from the dict.
The options are not cleared before. If changes have been made previously, but only the dict values should be applied it needs to be cleared first.
- Parameters
dictionary (dict (keys are strings, values are bool/None)) – a dictionary containing for each entry either the value False, True or None. The names must be valid depending on whether they enable or disable the option. All names with the value None can be in either of the list.
-
class
pywikibot.data.api.
PageGenerator
(generator: str, g_content=False, **kwargs)[source]¶ Bases:
pywikibot.data.api.QueryGenerator
Iterator for response to a request of type action=query&generator=foo.
This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page objects.
Required and optional parameters are as for
Request
, except that action=query is assumed and generator is required.- Parameters
generator – the “generator=” type from api.php
g_content – if True, retrieve the contents of the current version of each Page (default False)
-
class
pywikibot.data.api.
ParamInfo
(site, preloaded_modules=None, modules_only_mode=None)[source]¶ Bases:
collections.abc.Sized
,collections.abc.Container
API parameter information data object.
Provides cache aware fetching of parameter information.
It does not support the format modules.
- Parameters
preloaded_modules (set of string) – API modules to preload
modules_only_mode (bool or None to only use default, which True if the site is 1.25wmf4+) – use the ‘modules’ only syntax for API request
-
property
action_modules
¶ Set of all action modules.
-
attributes
(attribute: str, modules: Optional[set] = None)[source]¶ Mapping of modules with an attribute to the attribute value.
It will include all modules which have that attribute set, also if that attribute is empty or set to False.
- Parameters
attribute – attribute name
modules – modules to include. If None (default), it’ll load all modules including all submodules using the paths.
- Return type
dict using modules as keys
-
fetch
(modules) → None[source]¶ Fetch paraminfo for multiple modules.
No exception is raised when paraminfo for a module does not exist. Use __getitem__ to cause an exception if a module does not exist.
- Parameters
modules (iterable or str) – API modules to load
-
init_modules
= frozenset({'main', 'paraminfo'})¶
-
property
module_paths
¶ Set of all modules using their paths.
-
normalize_modules
(modules) → set[source]¶ Convert the modules into module paths.
Add query+ to any query module name not also in action modules.
- Returns
The modules converted into a module paths
-
classmethod
normalize_paraminfo
(data)[source]¶ Convert both old and new API JSON into a new-ish data structure.
For duplicate paths, the value will be False.
-
parameter
(module: str, param_name: str) → Optional[dict][source]¶ Get details about one modules parameter.
Returns None if the parameter does not exist.
- Parameters
module – API module name
param_name – parameter name in the module
- Returns
metadata that describes how the parameter may be used
-
paraminfo_keys
= frozenset({'formatmodules', 'mainmodule', 'modules', 'pagesetmodule', 'querymodules'})¶
-
property
prefix_map
¶ Mapping of module to its prefix for all modules with a prefix.
This loads paraminfo for all modules.
-
property
query_modules
¶ Set of all query module names without query+ path prefix.
-
root_modules
= frozenset({'main', 'pageset'})¶
-
class
pywikibot.data.api.
PropertyGenerator
(prop: str, **kwargs)[source]¶ Bases:
pywikibot.data.api.QueryGenerator
Iterator for queries of type action=query&prop=foo.
See the API documentation for types of page properties that can be queried.
This iterator yields one or more dict object(s) corresponding to each “page” item(s) from the API response; the calling module has to decide what to do with the contents of the dict. There will be one dict for each page queried via a titles= or ids= parameter (which must be supplied when instantiating this class).
Required and optional parameters are as for
Request
, except that action=query is assumed and prop is required.- Parameters
prop – the “prop=” type from api.php
-
property
props
¶ The requested property names.
-
class
pywikibot.data.api.
QueryGenerator
(**kwargs)[source]¶ Bases:
pywikibot.data.api._RequestWrapper
Base class for iterators that handle responses to API action=query.
By default, the iterator will iterate each item in the query response, and use the (query-)continue element, if present, to continue iterating as long as the wiki returns additional values. However, if the iterator’s limit attribute is set to a positive int, the iterator will stop after iterating that many values. If limit is negative, the limit parameter will not be passed to the API at all.
Most common query types are more efficiently handled by subclasses, but this class can be used directly for custom queries and miscellaneous types (such as “meta=…”) that don’t return the usual list of pages or links. See the API documentation for specific query options.
Initialize a QueryGenerator object.
kwargs are used to create a Request object; see that object’s documentation for values. ‘action’=’query’ is assumed.
-
set_maximum_items
(value: Optional[Union[int, str]])[source]¶ Set the maximum number of items to be retrieved from the wiki.
If not called, most queries will continue as long as there is more data to be retrieved from the API.
If set to -1 (or any negative value), the “limit” parameter will be omitted from the request. For some request types (such as prop=revisions), this is necessary to signal that only current revision is to be returned.
- Parameters
value – The value of maximum number of items to be retrieved in total to set. Ignores None value.
-
set_namespace
(namespaces)[source]¶ Set a namespace filter on this query.
- Parameters
namespaces (iterable of str or Namespace key, or a single instance of those types. May be a '|' separated list of namespace identifiers. An empty iterator clears any namespace restriction.) – namespace identifiers to limit query results
- Raises
KeyError – a namespace identifier was not resolved
# TODO: T196619 # @raises TypeError: module does not support a namespace parameter # or a namespace identifier has an inappropriate # type such as NoneType or bool, or more than one namespace # if the API module does not support multiple namespaces
-
-
class
pywikibot.data.api.
Request
(site=None, mime: Optional[dict] = None, throttle: bool = True, max_retries: Optional[int] = None, retry_wait: Optional[int] = None, use_get: Optional[bool] = None, parameters=<object object>, **kwargs)[source]¶ Bases:
collections.abc.MutableMapping
A request to a Site’s api.php interface.
Attributes of this object (except for the special parameters listed below) get passed as commands to api.php, and can be get or set using the dict interface. All attributes must be strings. Use an empty string for parameters that don’t require a value. For example, Request(action=”query”, titles=”Foo bar”, prop=”info”, redirects=””) corresponds to the API request “api.php?action=query&titles=Foo%20bar&prop=info&redirects”
This is the lowest-level interface to the API, and can be used for any request that a particular site’s API supports. See the API documentation (https://www.mediawiki.org/wiki/API) and site-specific settings for details on what parameters are accepted for each request type.
Uploading files is a special case: to upload, the parameter “mime” must contain a dict, and the parameter “file” must be set equal to a valid filename on the local computer, _not_ to the content of the file.
Returns a dict containing the JSON data returned by the wiki. Normally, one of the dict keys will be equal to the value of the ‘action’ parameter. Errors are caught and raise an APIError exception.
Example:
>>> r = Request(parameters={'action': 'query', 'meta': 'userinfo'}) >>> # This is equivalent to >>> # https://{path}/api.php?action=query&meta=userinfo&format=json >>> # change a parameter >>> r['meta'] = "userinfo|siteinfo" >>> # add a new parameter >>> r['siprop'] = "namespaces" >>> # note that "uiprop" param gets added automatically >>> str(r.action) 'query' >>> sorted(str(key) for key in r._params.keys()) ['action', 'meta', 'siprop'] >>> [str(key) for key in r._params['action']] ['query'] >>> [str(key) for key in r._params['meta']] ['userinfo', 'siteinfo'] >>> [str(key) for key in r._params['siprop']] ['namespaces'] >>> data = r.submit() >>> isinstance(data, dict) True >>> set(['query', 'batchcomplete', 'warnings']).issuperset(data.keys()) True >>> 'query' in data True >>> sorted(str(key) for key in data['query'].keys()) ['namespaces', 'userinfo']
Create a new Request instance with the given parameters.
The parameters for the request can be defined via either the ‘parameters’ parameter or the keyword arguments. The keyword arguments were the previous implementation but could cause problems when there are arguments to the API named the same as normal arguments to this class. So the second parameter ‘parameters’ was added which just contains all parameters. When a Request instance is created it must use either one of them and not both at the same time. To have backwards compatibility it adds a parameter named ‘parameters’ to kwargs when both parameters are set as that indicates an old call and ‘parameters’ was originally supplied as a keyword parameter.
If undefined keyword arguments were given AND the ‘parameters’ parameter was supplied as a positional parameter it still assumes ‘parameters’ were part of the keyword arguments.
If a class is using Request and is directly forwarding the parameters,
Request.clean_kwargs
can be used to automatically convert the old kwargs mode into the new parameter mode. This normalizes the arguments so that when the API parameters are modified the changes can always be applied to the ‘parameters’ parameter.- Parameters
site – The Site to which the request will be submitted. If not supplied, uses the user’s configured default Site.
mime – If not None, send in “multipart/form-data” format (default None). Parameters which should only be transferred via mime mode are defined via this parameter (even an empty dict means mime shall be used).
max_retries – Maximum number of times to retry after errors, defaults to config.max_retries.
retry_wait – Minimum time in seconds to wait after an error, defaults to config.retry_wait seconds (doubles each retry until config.retry_max seconds is reached).
use_get – Use HTTP GET request if possible. If False it uses a POST request. If None, it’ll try to determine via action=paraminfo if the action requires a POST.
parameters (dict) – The parameters used for the request to the API.
kwargs – The parameters used for the request to the API.
-
classmethod
clean_kwargs
(kwargs: dict) → dict[source]¶ Convert keyword arguments into new parameters mode.
If there are no other arguments in kwargs apart from the used arguments by the class’ initializer it’ll just return kwargs and otherwise remove those which aren’t in the initializer and put them in a dict which is added as a ‘parameters’ keyword. It will always create a shallow copy.
- Parameters
kwargs – The original keyword arguments which is not modified.
- Returns
The normalized keyword arguments.
-
classmethod
create_simple
(req_site, **kwargs)[source]¶ Create a new instance using all args except site for the API.
-
pywikibot.data.api.
encode_url
(query) → str[source]¶ Encode parameters to pass with a url.
Reorder parameters so that token parameters go last and call wraps
urlencode
. Return an HTTP URL query fragment which complies with https://www.mediawiki.org/wiki/API:Edit#Parameters (See the ‘token’ bullet.)- Parameters
query (mapping object or a sequence of two-element tuples) – keys and values to be uncoded for passing with a url
- Returns
encoded parameters with token parameters at the end
-
pywikibot.data.api.
removeprefix
(self, prefix, /)¶ Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
-
pywikibot.data.api.
update_page
(page, pagedict: dict, props=None)[source]¶ Update attributes of Page object page, based on query data in pagedict.
- Parameters
page (pywikibot.page.Page) – object to be updated
pagedict – the contents of a “page” element of a query response
props (iterable of string) – the property names which resulted in pagedict. If a missing value in pagedict can indicate both ‘false’ and ‘not present’ the property which would make the value present must be in the props parameter.
- Raises
pywikibot.exceptions.InvalidTitleError – Page title is invalid
pywikibot.exceptions.UnsupportedPageError – Page with namespace < 0 is not supported yet
pywikibot.data.mysql module¶
Miscellaneous helper functions for mysql queries.
-
pywikibot.data.mysql.
mysql_query
(query: str, params=None, dbname: Optional[str] = None, verbose: Optional[bool] = None, encoding=NotImplemented)[source]¶ Yield rows from a MySQL query.
An example query that yields all ns0 pages might look like:
SELECT page_namespace, page_title, FROM page WHERE page_namespace = 0;
Supported MediaWiki projects use Unicode (UTF-8) character encoding. Cursor charset is utf8.
- Parameters
query – MySQL query to execute
params (tuple, list or dict of str) – input parameters for the query, if needed if list or tuple, %s shall be used as placeholder in the query string. if a dict, %(key)s shall be used as placeholder in the query string.
dbname – db name
verbose – if True, print query to be executed; if None, config.verbose_output will be used.
- Returns
generator which yield tuples
pywikibot.data.sparql module¶
SPARQL Query interface.
-
class
pywikibot.data.sparql.
Bnode
(data: dict, **kwargs)[source]¶ Bases:
pywikibot.data.sparql.SparqlNode
Representation of blank node.
Create Bnode.
-
class
pywikibot.data.sparql.
Literal
(data: dict, **kwargs)[source]¶ Bases:
pywikibot.data.sparql.SparqlNode
Representation of RDF literal result type.
Create Literal object.
-
class
pywikibot.data.sparql.
SparqlNode
(value)[source]¶ Bases:
object
Base class for SPARQL nodes.
Create a SparqlNode.
-
class
pywikibot.data.sparql.
SparqlQuery
(endpoint: Optional[str] = None, entity_url: Optional[str] = None, repo=None, max_retries: Optional[int] = None, retry_wait: Optional[float] = None)[source]¶ Bases:
object
SPARQL Query class.
This class allows to run SPARQL queries against any SPARQL endpoint.
Create endpoint.
- Parameters
endpoint – SPARQL endpoint URL
entity_url – URL prefix for any entities returned in a query.
repo (pywikibot.site.DataSite) – The Wikibase site which we want to run queries on. If provided this overrides any value in endpoint and entity_url. Defaults to Wikidata.
max_retries – (optional) Maximum number of times to retry after errors, defaults to config.max_retries.
retry_wait – (optional) Minimum time in seconds to wait after an error, defaults to config.retry_wait seconds (doubles each retry until config.retry_max is reached).
-
ask
(query: str, headers={'Accept': 'application/sparql-results+json', 'cache-control': 'no-cache'}) → bool[source]¶ Run SPARQL ASK query and return boolean result.
- Parameters
query – Query text
-
get_items
(query, item_name='item', result_type=<class 'set'>)[source]¶ Retrieve items which satisfy given query.
Items are returned as Wikibase IDs.
- Parameters
query – Query string. Must contain ?{item_name} as one of the projected values.
item_name – Name of the value to extract
result_type (iterable) – type of the iterable in which SPARQL results are stored (default set)
- Returns
item ids, e.g. Q1234
- Return type
same as result_type
-
get_last_response
()[source]¶ Return last received response.
- Returns
Response object from last request or None
-
query
(query: str, headers={'Accept': 'application/sparql-results+json', 'cache-control': 'no-cache'})[source]¶ Run SPARQL query and return parsed JSON result.
- Parameters
query – Query text
-
select
(query: str, full_data: bool = False, headers={'Accept': 'application/sparql-results+json', 'cache-control': 'no-cache'})[source]¶ Run SPARQL query and return the result.
The response is assumed to be in format defined by: https://www.w3.org/TR/2013/REC-sparql11-results-json-20130321/
- Parameters
query – Query text
full_data – Whether return full data objects or only values
- Returns
List of query results or None if query failed
-
class
pywikibot.data.sparql.
URI
(data: dict, entity_url, **kwargs)[source]¶ Bases:
pywikibot.data.sparql.SparqlNode
Representation of URI result type.
Create URI object.
pywikibot.data.wikistats module¶
Objects representing WikiStats API.
-
class
pywikibot.data.wikistats.
WikiStats
(url='https://wikistats.wmcloud.org/')[source]¶ Bases:
object
Light wrapper around WikiStats data, caching responses and data.
The methods accept a Pywikibot family name as the WikiStats table name, mapping the names before calling the WikiStats API.
-
ALL_KEYS
= {'editthis', 'gamepedias', 'gentoo', 'lxde', 'mediawikis', 'metapedias', 'neoseeker', 'opensuse', 'orain', 'pardus', 'referata', 'rodovid', 'scoutwiki', 'shoutwiki', 'sourceforge', 'uncyclomedia', 'w3cwikis', 'wikia', 'wikibooks', 'wikifur', 'wikinews', 'wikipedia', 'wikipedias', 'wikiquote', 'wikiquotes', 'wikisite', 'wikisource', 'wikisources', 'wikitravel', 'wikiversity', 'wikivoyage', 'wikkii', 'wiktionaries', 'wiktionary', 'wmspecials'}¶
-
ALL_TABLES
= {'editthis', 'gamepedias', 'gentoo', 'lxde', 'mediawikis', 'metapedias', 'neoseeker', 'opensuse', 'orain', 'pardus', 'referata', 'rodovid', 'scoutwiki', 'shoutwiki', 'sourceforge', 'uncyclomedia', 'w3cwikis', 'wikia', 'wikibooks', 'wikifur', 'wikinews', 'wikipedias', 'wikiquotes', 'wikisite', 'wikisources', 'wikitravel', 'wikiversity', 'wikivoyage', 'wikkii', 'wiktionaries', 'wmspecials'}¶
-
FAMILY_MAPPING
= {'wikipedia': 'wikipedias', 'wikiquote': 'wikiquotes', 'wikisource': 'wikisources', 'wiktionary': 'wiktionaries'}¶
-
MISC_SITES_TABLE
= 'mediawikis'¶
-
OTHER_MULTILANG_TABLES
= {'gentoo', 'lxde', 'metapedias', 'opensuse', 'pardus', 'rodovid', 'scoutwiki', 'uncyclomedia', 'wikifur', 'wikitravel'}¶
-
OTHER_TABLES
= {'editthis', 'gamepedias', 'neoseeker', 'orain', 'referata', 'shoutwiki', 'sourceforge', 'w3cwikis', 'wikia', 'wikisite', 'wikkii', 'wmspecials'}¶
-
WMF_MULTILANG_TABLES
= {'wikibooks', 'wikinews', 'wikipedias', 'wikiquotes', 'wikisources', 'wikiversity', 'wikivoyage', 'wiktionaries'}¶
-
get
(table: str) → list[source]¶ Get a list of a table of data.
- Parameters
table – table of data to fetch
-
get_dict
(table: str) → dict[source]¶ Get dictionary of a table of data.
- Parameters
table – table of data to fetch
-
sorted
(table: str, key: str, reverse: Optional[bool] = None) → list[source]¶ Reverse numerical sort of data.
- Parameters
table – name of table of data
key – data table key
reverse – If set to True the sorting order is reversed. If None the sorting order for numeric keys are reversed whereas alphanumeric keys are sorted in normal way.
- Returns
The sorted table
-