index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
7,178
wikitools3.page
move
Move the page Params are the same as the API: mvto - page title to move to, the only required param reason - summary for the log movetalk - move the corresponding talk page noredirect - don't create a redirect at the previous title watch - add the page to your watchlist ...
def move( self, mvto, reason=False, movetalk=False, noredirect=False, watch=False, unwatch=False, ): """Move the page Params are the same as the API: mvto - page title to move to, the only required param reason - summary for the log movetalk - move the corresponding talk ...
(self, mvto, reason=False, movetalk=False, noredirect=False, watch=False, unwatch=False)
7,179
wikitools3.page
protect
Protect a page Restrictions and expirations are dictionaries of protection level/expiry settings, e.g., {'edit':'sysop'} and {'move':'3 days'}. expirations can also be a string to set all levels to the same expiration reason - summary for log cascade - apply protection ...
def protect(self, restrictions={}, expirations={}, reason=False, cascade=False): """Protect a page Restrictions and expirations are dictionaries of protection level/expiry settings, e.g., {'edit':'sysop'} and {'move':'3 days'}. expirations can also be a string to set all levels to the same expiratio...
(self, restrictions={}, expirations={}, reason=False, cascade=False)
7,180
wikitools3.page
setNamespace
Change the namespace number of a page object Updates the title with the new prefix newns - integer namespace number recheck - redo pageinfo checks
def setNamespace(self, newns, recheck=False): """Change the namespace number of a page object Updates the title with the new prefix newns - integer namespace number recheck - redo pageinfo checks """ if not newns in self.site.namespaces.keys(): raise BadNamespace if self.namespace ==...
(self, newns, recheck=False)
7,181
wikitools3.page
setPageInfo
Sets basic page info, required for almost everything
def setPageInfo(self): """Sets basic page info, required for almost everything""" followRedir = self.followRedir params = {"action": "query"} if self.pageid: params["pageids"] = self.pageid else: params["titles"] = self.title if followRedir: params["redirects"] = "" r...
(self)
7,182
wikitools3.page
setSection
Set a section for the page section - the section name number - the section number
def setSection(self, section=None, number=None): """Set a section for the page section - the section name number - the section number """ if section is None and number is None: self.section = False elif number is not None: try: self.section = str(int(number)) ...
(self, section=None, number=None)
7,183
wikitools3.page
toggleTalk
Switch to and from the talk namespaces Returns a new page object that's either the talk or non-talk version of the current page check and followRedir - same meaning as Page constructor
def toggleTalk(self, check=True, followRedir=True): """Switch to and from the talk namespaces Returns a new page object that's either the talk or non-talk version of the current page check and followRedir - same meaning as Page constructor """ if not self.title: self.setPageInfo() ns...
(self, check=True, followRedir=True)
7,184
wikitools3.wiki
CookiesExpired
Cookies are expired, needs to be an exception so login() will use the API instead
class CookiesExpired(WikiError): """Cookies are expired, needs to be an exception so login() will use the API instead"""
null
7,185
wikitools3.page
EditError
Problem with edit request
class EditError(wiki.WikiError): """Problem with edit request"""
null
7,186
wikitools3.wikifile
File
A file on the wiki
class File(page.Page): """A file on the wiki""" def __init__( self, wiki, title, check=True, followRedir=False, section=False, sectionnumber=False, pageid=False, ): """ wiki - A wiki object title - The page title, as a ...
(wiki, title, check=True, followRedir=False, section=False, sectionnumber=False, pageid=False)
7,187
wikitools3.wikifile
__extractToList
null
def __extractToList(self, json, stuff): list = [] if stuff in json["query"]: for item in json["query"][stuff]: list.append(item["title"]) return list
(self, json, stuff)
7,188
wikitools3.wikifile
__getUsageInternal
null
def __getUsageInternal(self, namespaces=False): params = { "action": "query", "list": "imageusage", "iutitle": self.title, "iulimit": self.site.limit, } if namespaces is not False: params["iunamespace"] = "|".join([str(ns) for ns in namespaces]) while True: ...
(self, namespaces=False)
7,194
wikitools3.wikifile
__init__
wiki - A wiki object title - The page title, as a string or unicode object check - Checks for existence, normalizes title, required for most things followRedir - follow redirects (check must be true) section - the section name sectionnumber - the section number p...
def __init__( self, wiki, title, check=True, followRedir=False, section=False, sectionnumber=False, pageid=False, ): """ wiki - A wiki object title - The page title, as a string or unicode object check - Checks for existence, normalizes title, required for most things ...
(self, wiki, title, check=True, followRedir=False, section=False, sectionnumber=False, pageid=False)
7,200
wikitools3.wikifile
download
Download the image to a local file width/height - set width OR height of the downloaded image location - set the filename to save to. If not set, the page title minus the namespace prefix will be used and saved to the current directory
def download(self, width=False, height=False, location=False): """Download the image to a local file width/height - set width OR height of the downloaded image location - set the filename to save to. If not set, the page title minus the namespace prefix will be used and saved to the current directory ...
(self, width=False, height=False, location=False)
7,203
wikitools3.wikifile
getFileHistory
null
def getFileHistory(self, force=False): if self.filehistory and not force: return self.filehistory if self.pageid == 0 and not self.title: self.setPageInfo() params = { "action": "query", "prop": "imageinfo", "iilimit": self.site.limit, } if self.pageid > 0: ...
(self, force=False)
7,204
wikitools3.wikifile
getHistory
null
def getHistory(self, force=False): warnings.warn( """File.getHistory has been renamed to File.getFileHistory""", FutureWarning ) return self.getFileHistory(force)
(self, force=False)
7,209
wikitools3.wikifile
getUsage
Gets a list of pages that use the file titleonly - set to True to only create a list of strings, else it will be a list of Page objects force - reload the list even if it was generated before namespaces - List of namespaces to restrict to (queries with this option will not be cached) ...
def getUsage(self, titleonly=False, force=False, namespaces=False): """Gets a list of pages that use the file titleonly - set to True to only create a list of strings, else it will be a list of Page objects force - reload the list even if it was generated before namespaces - List of namespaces to re...
(self, titleonly=False, force=False, namespaces=False)
7,210
wikitools3.wikifile
getUsageGen
Generator function for pages that use the file titleonly - set to True to return strings, else it will return Page objects force - reload the list even if it was generated before namespaces - List of namespaces to restrict to (queries with this option will not be cached)
def getUsageGen(self, titleonly=False, force=False, namespaces=False): """Generator function for pages that use the file titleonly - set to True to return strings, else it will return Page objects force - reload the list even if it was generated before namespaces - List of namespaces to restrict to ...
(self, titleonly=False, force=False, namespaces=False)
7,220
wikitools3.wikifile
upload
Upload a file, requires the "poster3" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A URL to upload the file from, if allowed on the wiki ignorewarnings - Ignore wa...
def upload( self, fileobj=None, comment="", url=None, ignorewarnings=False, watch=False ): """Upload a file, requires the "poster3" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A U...
(self, fileobj=None, comment='', url=None, ignorewarnings=False, watch=False)
7,221
wikitools3.wikifile
FileDimensionError
Invalid dimensions
class FileDimensionError(wiki.WikiError): """Invalid dimensions"""
null
7,222
urllib.request
HTTPPasswordMgrWithDefaultRealm
null
class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): def find_user_password(self, realm, authuri): user, password = HTTPPasswordMgr.find_user_password(self, realm, authuri) if user is not None: return user, password ...
()
7,223
urllib.request
__init__
null
def __init__(self): self.passwd = {}
(self)
7,224
urllib.request
add_password
null
def add_password(self, realm, uri, user, passwd): # uri could be a single URI or a sequence if isinstance(uri, str): uri = [uri] if realm not in self.passwd: self.passwd[realm] = {} for default_port in True, False: reduced_uri = tuple( self.reduce_uri(u, default_port)...
(self, realm, uri, user, passwd)
7,225
urllib.request
find_user_password
null
def find_user_password(self, realm, authuri): user, password = HTTPPasswordMgr.find_user_password(self, realm, authuri) if user is not None: return user, password return HTTPPasswordMgr.find_user_password(self, None, authuri)
(self, realm, authuri)
7,226
urllib.request
is_suburi
Check if test is below base in a URI tree Both args must be URIs in reduced form.
def is_suburi(self, base, test): """Check if test is below base in a URI tree Both args must be URIs in reduced form. """ if base == test: return True if base[0] != test[0]: return False prefix = base[1] if prefix[-1:] != '/': prefix += '/' return test[1].startswi...
(self, base, test)
7,227
urllib.request
reduce_uri
Accept authority or URI and extract only the authority and path.
def reduce_uri(self, uri, default_port=True): """Accept authority or URI and extract only the authority and path.""" # note HTTP URLs do not have a userinfo component parts = urlsplit(uri) if parts[1]: # URI scheme = parts[0] authority = parts[1] path = parts[2] or '/' ...
(self, uri, default_port=True)
7,228
wikitools3.wiki
Namespace
Class for namespace 'constants' Names are based on canonical (non-localized) names This functions as an integer in every way, except that the OR operator ( | ) is overridden to produce a string namespace list for use in API queries wikiobj.NS_MAIN|wikiobj.NS_USER|wikiobj.NS_PROJECT returns '0|2|4' ...
class Namespace(int): """ Class for namespace 'constants' Names are based on canonical (non-localized) names This functions as an integer in every way, except that the OR operator ( | ) is overridden to produce a string namespace list for use in API queries wikiobj.NS_MAIN|wikiobj.NS_USER|wikiob...
null
7,229
wikitools3.wiki
__or__
null
def __or__(self, other): return "|".join([str(self), str(other)])
(self, other)
7,230
wikitools3.wiki
__ror__
null
def __ror__(self, other): return "|".join([str(other), str(self)])
(self, other)
7,231
wikitools3.page
NoPage
Non-existent page
class NoPage(wiki.WikiError): """Non-existent page"""
null
7,232
wikitools3.page
Page
A page on the wiki
class Page(object): """A page on the wiki""" def __init__( self, site, title=False, check=True, followRedir=True, section=False, sectionnumber=None, pageid=False, namespace=False, ): """ wiki - A wiki object tit...
(site, title=False, check=True, followRedir=True, section=False, sectionnumber=None, pageid=False, namespace=False)
7,238
wikitools3.page
__init__
wiki - A wiki object title - The page title, as a string or unicode object check - Checks for existence, normalizes title, required for most things followRedir - follow redirects (check must be true) section - the section name sectionnumber - the section number p...
def __init__( self, site, title=False, check=True, followRedir=True, section=False, sectionnumber=None, pageid=False, namespace=False, ): """ wiki - A wiki object title - The page title, as a string or unicode object check - Checks for existence, normalizes title, req...
(self, site, title=False, check=True, followRedir=True, section=False, sectionnumber=None, pageid=False, namespace=False)
7,260
wikitools3.page
ProtectError
Problem with protection request
class ProtectError(wiki.WikiError): """Problem with protection request"""
null
7,262
wikitools3.wikifile
UploadError
Error during uploading
class UploadError(wiki.WikiError): """Error during uploading"""
null
7,263
wikitools3.user
User
A user on the wiki
class User: """A user on the wiki""" def __init__(self, site, name, check=True): """ wiki - A wiki object name - The username, as a string check - Checks for existence, normalizes name """ self.site = site self.name = name.strip() if not isinstanc...
(site, name, check=True)
7,264
wikitools3.user
IPcheck
null
def IPcheck(self): try: # IPv4 check s = socket.inet_aton(self.name.replace(" ", "_")) if socket.inet_ntoa(s) == self.name: self.isIP = True self.exists = False return except: pass try: s = socket.inet_pton(socket.AF_INET6, self.name.replace("...
(self)
7,265
wikitools3.user
IPnorm
This is basically a port of MediaWiki's IP::sanitizeIP but assuming no CIDR ranges
def IPnorm(self, ip): """This is basically a port of MediaWiki's IP::sanitizeIP but assuming no CIDR ranges""" ip = ip.upper() # Expand zero abbreviations abbrevPos = ip.find("::") if abbrevPos != -1: addressEnd = len(ip) - 1 # If the '::' is at the beginning... if abbrevPos ...
(self, ip)
7,266
wikitools3.user
__eq__
null
def __eq__(self, other): if not isinstance(other, User): return False if self.name == other.name and self.site == other.site: return True return False
(self, other)
7,267
wikitools3.user
__hash__
null
def __hash__(self): return int(self.name) ^ hash(self.site.apibase)
(self)
7,268
wikitools3.user
__init__
wiki - A wiki object name - The username, as a string check - Checks for existence, normalizes name
def __init__(self, site, name, check=True): """ wiki - A wiki object name - The username, as a string check - Checks for existence, normalizes name """ self.site = site self.name = name.strip() if not isinstance(self.name, str): self.name = str(self.name, "utf8") self.exists ...
(self, site, name, check=True)
7,269
wikitools3.user
__ne__
null
def __ne__(self, other): if not isinstance(other, User): return True if self.name == other.name and self.site == other.site: return False return True
(self, other)
7,270
wikitools3.user
__repr__
null
def __repr__(self): return ( "<" + self.__module__ + "." + self.__class__.__name__ + " " + repr(self.name) + " on " + repr(self.site.apibase) + ">" )
(self)
7,271
wikitools3.user
__str__
null
def __str__(self): return ( self.__class__.__name__ + " " + repr(self.name) + " on " + repr(self.site.domain) )
(self)
7,272
wikitools3.user
block
Block the user Params are the same as the API reason - block reason expiry - block expiration anononly - block anonymous users only nocreate - disable account creation autoblock - block IP addresses used by the user noemail - block user from sending email through...
def block( self, reason=False, expiry=False, anononly=False, nocreate=False, autoblock=False, noemail=False, hidename=False, allowusertalk=False, reblock=False, ): """Block the user Params are the same as the API reason - block reason expiry - block expiration ...
(self, reason=False, expiry=False, anononly=False, nocreate=False, autoblock=False, noemail=False, hidename=False, allowusertalk=False, reblock=False)
7,273
wikitools3.user
getTalkPage
Convenience function to get an object for the user's talk page
def getTalkPage(self, check=True, followRedir=False): """Convenience function to get an object for the user's talk page""" return page.Page( self.site, ":".join([self.site.namespaces[3]["*"], self.name]), check=check, followRedir=False, )
(self, check=True, followRedir=False)
7,274
wikitools3.user
isBlocked
Determine if a user is blocked
def isBlocked(self, force=False): """Determine if a user is blocked""" if self.blocked is not None and not force: return self.blocked params = { "action": "query", "list": "blocks", "bkusers": self.name, "bkprop": "id", } req = api.APIRequest(self.site, params...
(self, force=False)
7,275
wikitools3.user
setUserInfo
Sets basic user info
def setUserInfo(self): """Sets basic user info""" params = { "action": "query", "list": "users", "ususers": self.name, "usprop": "blockinfo|groups|editcount", } req = api.APIRequest(self.site, params) response = req.query(False) user = response["query"]["users"][0...
(self)
7,276
wikitools3.user
unblock
Unblock the user reason - reason for the log
def unblock(self, reason=False): """Unblock the user reason - reason for the log """ token = self.site.getToken("csrf") params = {"action": "unblock", "user": self.name, "token": token} if reason: params["reason"] = reason req = api.APIRequest(self.site, params, write=False) res ...
(self, reason=False)
7,277
wikitools3.wiki
UserBlocked
Trying to edit while blocked
class UserBlocked(WikiError): """Trying to edit while blocked"""
null
7,278
wikitools3.wiki
Wiki
A Wiki site
class Wiki: """A Wiki site""" def __init__( self, url="https://en.wikipedia.org/w/api.php", httpuser=None, httppass=None, preauth=False, ): """ url - A URL to the site's API, defaults to en.wikipedia httpuser - optional user name for HTTP Auth...
(url='https://en.wikipedia.org/w/api.php', httpuser=None, httppass=None, preauth=False)
7,279
wikitools3.wiki
__eq__
null
def __eq__(self, other): if not isinstance(other, Wiki): return False if self.apibase == other.apibase: return True return False
(self, other)
7,280
wikitools3.wiki
__hash__
null
def __hash__(self): return hash(self.apibase)
(self)
7,281
wikitools3.wiki
__init__
url - A URL to the site's API, defaults to en.wikipedia httpuser - optional user name for HTTP Auth httppass - password for HTTP Auth, leave out to enter interactively preauth - true to send headers for HTTP Auth on the first request instead of relying on the negot...
def __init__( self, url="https://en.wikipedia.org/w/api.php", httpuser=None, httppass=None, preauth=False, ): """ url - A URL to the site's API, defaults to en.wikipedia httpuser - optional user name for HTTP Auth httppass - password for HTTP Auth, leave out to enter interactivel...
(self, url='https://en.wikipedia.org/w/api.php', httpuser=None, httppass=None, preauth=False)
7,282
wikitools3.wiki
__ne__
null
def __ne__(self, other): if not isinstance(other, Wiki): return True if self.apibase == other.apibase: return False return True
(self, other)
7,283
wikitools3.wiki
__repr__
null
def __repr__(self): if self.username: user = " User:" + self.username else: user = " not logged in" return ( "<" + self.__module__ + "." + self.__class__.__name__ + " " + repr(self.apibase) + user + ">" )
(self)
7,284
wikitools3.wiki
__str__
null
def __str__(self): if self.username: user = " - using User:" + self.username else: user = " - not logged in" return self.domain + user
(self)
7,285
wikitools3.wiki
getToken
Get a token For wikis with MW 1.24 or newer: type (string) - csrf, deleteglobalaccount, patrol, rollback, setglobalaccountstatus, userrights, watch For older wiki versions, only csrf (edit, move, etc.) tokens are supported
def getToken(self, type): """Get a token For wikis with MW 1.24 or newer: type (string) - csrf, deleteglobalaccount, patrol, rollback, setglobalaccountstatus, userrights, watch For older wiki versions, only csrf (edit, move, etc.) tokens are supported """ if self.newtoken: params = { ...
(self, type)
7,286
wikitools3.wiki
isLoggedIn
Verify that we are a logged in user username - specify a username to check against
def isLoggedIn(self, username=False): """Verify that we are a logged in user username - specify a username to check against """ data = { "action": "query", "meta": "userinfo", } if self.maxlag < 120: data["maxlag"] = 120 req = api.APIRequest(self, data) info = req...
(self, username=False)
7,287
wikitools3.wiki
login
Login to the site remember - saves cookies to a file - the filename will be: hash(username - apibase).cookies the cookies will be saved in the current directory, change cookiepath to use a different location force - forces login over the API even if a cookie file exists ...
def login( self, username, password=False, remember=False, force=False, verify=True, domain=None, ): """Login to the site remember - saves cookies to a file - the filename will be: hash(username - apibase).cookies the cookies will be saved in the current directory, change coo...
(self, username, password=False, remember=False, force=False, verify=True, domain=None)
7,288
wikitools3.wiki
logout
null
def logout(self): params = {"action": "logout"} if self.maxlag < 120: params["maxlag"] = 120 cookiefile = ( self.cookiepath + str(hash(self.username + " - " + self.apibase)) + ".cookies" ) try: os.remove(cookiefile) except: pass req = api.APIRe...
(self)
7,289
wikitools3.wiki
setAssert
Set an assertion value This only makes a difference on sites with the AssertEdit extension on others it will be silently ignored This is only checked on edits, so only applied to write queries Set to None (the default) to not use anything http://www.mediawiki.org/wiki/Extension...
def setAssert(self, value): """Set an assertion value This only makes a difference on sites with the AssertEdit extension on others it will be silently ignored This is only checked on edits, so only applied to write queries Set to None (the default) to not use anything http://www.mediawiki.org/w...
(self, value)
7,290
wikitools3.wiki
setMaxlag
Set the maximum server lag to allow If the lag is > the maxlag value, all requests will wait Setting to a negative number will disable maxlag checks
def setMaxlag(self, maxlag=5): """Set the maximum server lag to allow If the lag is > the maxlag value, all requests will wait Setting to a negative number will disable maxlag checks """ try: int(maxlag) except: raise WikiError("maxlag must be an integer") self.maxlag = int(m...
(self, maxlag=5)
7,291
wikitools3.wiki
setSiteinfo
Retrieves basic siteinfo Called when constructing, or after login if the first call failed
def setSiteinfo(self): """Retrieves basic siteinfo Called when constructing, or after login if the first call failed """ params = { "action": "query", "meta": "siteinfo|tokens", "siprop": "general|namespaces|namespacealiases", } if self.maxlag < 120: params["m...
(self)
7,292
wikitools3.wiki
setUserAgent
Function to set a different user-agent
def setUserAgent(self, useragent): """Function to set a different user-agent""" self.useragent = str(useragent) return self.useragent
(self, useragent)
7,293
wikitools3.wiki
WikiCookieJar
null
class WikiCookieJar(http.cookiejar.FileCookieJar): def save(self, site, filename=None, ignore_discard=False, ignore_expires=False): if not filename: filename = self.filename old_umask = os.umask(0o077) f = open(filename, "w") f.write("") content = "" for c...
(filename=None, delayload=False, policy=None)
7,294
http.cookiejar
__init__
Cookies are NOT loaded from the named file until either the .load() or .revert() method is called.
def __init__(self, filename=None, delayload=False, policy=None): """ Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. """ CookieJar.__init__(self, policy) if filename is not None: filename = os.fspath(filename) self.filename = filenam...
(self, filename=None, delayload=False, policy=None)
7,295
http.cookiejar
__iter__
null
def __iter__(self): return deepvalues(self._cookies)
(self)
7,296
http.cookiejar
__len__
Return number of contained cookies.
def __len__(self): """Return number of contained cookies.""" i = 0 for cookie in self: i = i + 1 return i
(self)
7,297
http.cookiejar
__repr__
null
def __repr__(self): r = [] for cookie in self: r.append(repr(cookie)) return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r))
(self)
7,298
http.cookiejar
__str__
null
def __str__(self): r = [] for cookie in self: r.append(str(cookie)) return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r))
(self)
7,299
http.cookiejar
_cookie_attrs
Return a list of cookie-attributes to be returned to server. like ['foo="bar"; $Path="/"', ...] The $Version attribute is also added when appropriate (currently only once per request).
def _cookie_attrs(self, cookies): """Return a list of cookie-attributes to be returned to server. like ['foo="bar"; $Path="/"', ...] The $Version attribute is also added when appropriate (currently only once per request). """ # add cookies in order of most specific (ie. longest) path first c...
(self, cookies)
7,300
http.cookiejar
_cookie_from_cookie_tuple
null
def _cookie_from_cookie_tuple(self, tup, request): # standard is dict of standard cookie-attributes, rest is dict of the # rest of them name, value, standard, rest = tup domain = standard.get("domain", Absent) path = standard.get("path", Absent) port = standard.get("port", Absent) expires = ...
(self, tup, request)
7,301
http.cookiejar
_cookies_for_domain
null
def _cookies_for_domain(self, domain, request): cookies = [] if not self._policy.domain_return_ok(domain, request): return [] _debug("Checking %s for cookies to return", domain) cookies_by_path = self._cookies[domain] for path in cookies_by_path.keys(): if not self._policy.path_retur...
(self, domain, request)
7,302
http.cookiejar
_cookies_for_request
Return a list of cookies to be returned to server.
def _cookies_for_request(self, request): """Return a list of cookies to be returned to server.""" cookies = [] for domain in self._cookies.keys(): cookies.extend(self._cookies_for_domain(domain, request)) return cookies
(self, request)
7,303
http.cookiejar
_cookies_from_attrs_set
null
def _cookies_from_attrs_set(self, attrs_set, request): cookie_tuples = self._normalized_cookie_tuples(attrs_set) cookies = [] for tup in cookie_tuples: cookie = self._cookie_from_cookie_tuple(tup, request) if cookie: cookies.append(cookie) return cookies
(self, attrs_set, request)
7,304
http.cookiejar
_normalized_cookie_tuples
Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name and value, standard is a dictionary c...
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name ...
(self, attrs_set)
7,305
http.cookiejar
_process_rfc2109_cookies
null
def _process_rfc2109_cookies(self, cookies): rfc2109_as_ns = getattr(self._policy, 'rfc2109_as_netscape', None) if rfc2109_as_ns is None: rfc2109_as_ns = not self._policy.rfc2965 for cookie in cookies: if cookie.version == 1: cookie.rfc2109 = True if rfc2109_as_ns: ...
(self, cookies)
7,306
http.cookiejar
add_cookie_header
Add correct Cookie: header to request (urllib.request.Request object). The Cookie2 header is also added unless policy.hide_cookie2 is true.
def add_cookie_header(self, request): """Add correct Cookie: header to request (urllib.request.Request object). The Cookie2 header is also added unless policy.hide_cookie2 is true. """ _debug("add_cookie_header") self._cookies_lock.acquire() try: self._policy._now = self._now = int(time....
(self, request)
7,307
http.cookiejar
clear
Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that domain are removed. If given three argumen...
def clear(self, domain=None, path=None, name=None): """Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that d...
(self, domain=None, path=None, name=None)
7,308
http.cookiejar
clear_expired_cookies
Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save expired cookies anyway (un...
def clear_expired_cookies(self): """Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save exp...
(self)
7,309
http.cookiejar
clear_session_cookies
Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.
def clear_session_cookies(self): """Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument. """ self._cookies_lock.acquire() try: for cookie in self: if cookie.discard: ...
(self)
7,310
http.cookiejar
extract_cookies
Extract cookies from response, where allowable given the request.
def extract_cookies(self, response, request): """Extract cookies from response, where allowable given the request.""" _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() try: for cookie in self.make_cookies(response, request): if self._policy.set_ok(cookie, re...
(self, response, request)
7,311
wikitools3.wiki
load
null
def load(self, site, filename, ignore_discard, ignore_expires): f = open(filename, "r") cookies = f.read().split("|~|") saved = cookies[len(cookies) - 2] if ( int(time.time()) - int(saved) > 1296000 ): # 15 days, not sure when the cookies actually expire... f.close() os.remo...
(self, site, filename, ignore_discard, ignore_expires)
7,312
http.cookiejar
make_cookies
Return sequence of Cookie objects extracted from response object.
def make_cookies(self, response, request): """Return sequence of Cookie objects extracted from response object.""" # get cookie-attributes for RFC 2965 and Netscape protocols headers = response.info() rfc2965_hdrs = headers.get_all("Set-Cookie2", []) ns_hdrs = headers.get_all("Set-Cookie", []) s...
(self, response, request)
7,313
http.cookiejar
revert
Clear all cookies and reload cookies from a saved file. Raises LoadError (or OSError) if reversion is not successful; the object's state will not be altered if this happens.
def revert(self, filename=None, ignore_discard=False, ignore_expires=False): """Clear all cookies and reload cookies from a saved file. Raises LoadError (or OSError) if reversion is not successful; the object's state will not be altered if this happens. """ if filename is None: if...
(self, filename=None, ignore_discard=False, ignore_expires=False)
7,314
wikitools3.wiki
save
null
def save(self, site, filename=None, ignore_discard=False, ignore_expires=False): if not filename: filename = self.filename old_umask = os.umask(0o077) f = open(filename, "w") f.write("") content = "" for c in self: if not ignore_discard and c.discard: continue ...
(self, site, filename=None, ignore_discard=False, ignore_expires=False)
7,315
http.cookiejar
set_cookie
Set a cookie, without checking whether or not it should be set.
def set_cookie(self, cookie): """Set a cookie, without checking whether or not it should be set.""" c = self._cookies self._cookies_lock.acquire() try: if cookie.domain not in c: c[cookie.domain] = {} c2 = c[cookie.domain] if cookie.path not in c2: c2[cookie.path] = {} c3...
(self, cookie)
7,316
http.cookiejar
set_cookie_if_ok
Set a cookie if policy says it's OK to do so.
def set_cookie_if_ok(self, cookie, request): """Set a cookie if policy says it's OK to do so.""" self._cookies_lock.acquire() try: self._policy._now = self._now = int(time.time()) if self._policy.set_ok(cookie, request): self.set_cookie(cookie) finally: self._cookies_...
(self, cookie, request)
7,317
http.cookiejar
set_policy
null
def set_policy(self, policy): self._policy = policy
(self, policy)
7,318
wikitools3.wiki
WikiError
Base class for errors
class WikiError(Exception): """Base class for errors"""
null
7,328
poster3.encode
multipart_encode
Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and ei...
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parame...
(params, boundary=None, cb=None)
7,329
wikitools3.page
namespaceDetect
Detect the namespace of a given title title - the page title site - the wiki object the page is on
def namespaceDetect(title, site): """Detect the namespace of a given title title - the page title site - the wiki object the page is on """ bits = title.split(":", 1) if len(bits) == 1 or bits[0] == "": return 0 else: nsprefix = bits[ 0 ].lower() # wp:Foo...
(title, site)
7,333
urllib.parse
quote_plus
Like quote(), but also replace ' ' with '+', as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.
def quote_plus(string, safe='', encoding=None, errors=None): """Like quote(), but also replace ' ' with '+', as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'. """ # Check if ' ' in stri...
(string, safe='', encoding=None, errors=None)
7,335
wikitools3.api
resultCombine
Experimental-ish result-combiner thing If the result isn't something from action=query, this will just explode, but that shouldn't happen hopefully?
def resultCombine(type, old, new): """Experimental-ish result-combiner thing If the result isn't something from action=query, this will just explode, but that shouldn't happen hopefully? """ ret = old if type in new["query"]: # Basic list, easy ret["query"][type].extend(new["query"][t...
(type, old, new)
7,340
wikitools3.api
urlencode
Hack of urllib's urlencode function, which can handle utf-8, but for unknown reasons, chooses not to by trying to encode everything as ascii
def urlencode(query, doseq=0): """ Hack of urllib's urlencode function, which can handle utf-8, but for unknown reasons, chooses not to by trying to encode everything as ascii """ if hasattr(query, "items"): # mapping objects query = query.items() else: # it's a bothe...
(query, doseq=0)
7,347
requests_auth_aws_sigv4
AWSSigV4
null
class AWSSigV4(AuthBase): def __init__(self, service, **kwargs): ''' Create authentication mechanism :param service: AWS Service identifier, for example `ec2`. This is required. :param region: AWS Region, for example `us-east-1`. If not provided, it will be set using ...
(service, **kwargs)
7,348
requests_auth_aws_sigv4
__call__
Called to add authentication information to request :param r: `requests.models.PreparedRequest` object to modify :returns: `requests.models.PreparedRequest`, modified to add authentication
def __call__(self, r): ''' Called to add authentication information to request :param r: `requests.models.PreparedRequest` object to modify :returns: `requests.models.PreparedRequest`, modified to add authentication ''' # Create a date for headers and the credential string t = dat...
(self, r)
7,349
requests_auth_aws_sigv4
__init__
Create authentication mechanism :param service: AWS Service identifier, for example `ec2`. This is required. :param region: AWS Region, for example `us-east-1`. If not provided, it will be set using the environment variables `AWS_DEFAULT_REGION` or using boto3, if available. ...
def __init__(self, service, **kwargs): ''' Create authentication mechanism :param service: AWS Service identifier, for example `ec2`. This is required. :param region: AWS Region, for example `us-east-1`. If not provided, it will be set using the environment variables `AWS_DEFAULT_REGION` or ...
(self, service, **kwargs)
7,350
requests.auth
AuthBase
Base class that all auth implementations derive from
class AuthBase: """Base class that all auth implementations derive from""" def __call__(self, r): raise NotImplementedError("Auth hooks must be callable.")
()
7,351
requests.auth
__call__
null
def __call__(self, r): raise NotImplementedError("Auth hooks must be callable.")
(self, r)
7,359
requests_auth_aws_sigv4
sign_msg
Sign message using key
def sign_msg(key, msg): ''' Sign message using key ''' return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
(key, msg)