A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

647 wiersze
27 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from cookielib import CookieJar
  23. from gzip import GzipFile
  24. from json import loads
  25. from os.path import expanduser
  26. from re import escape as re_escape, match as re_match
  27. from StringIO import StringIO
  28. from time import sleep
  29. from urllib import unquote_plus, urlencode
  30. from urllib2 import build_opener, HTTPCookieProcessor, URLError
  31. from urlparse import urlparse
  32. try:
  33. import oursql
  34. except ImportError:
  35. oursql = None
  36. from earwigbot.wiki import logger
  37. from earwigbot.wiki.category import Category
  38. from earwigbot.wiki.constants import *
  39. from earwigbot.wiki.exceptions import *
  40. from earwigbot.wiki.page import Page
  41. from earwigbot.wiki.user import User
  42. __all__ = ["Site"]
  43. class Site(object):
  44. """
  45. EarwigBot's Wiki Toolset: Site Class
  46. Represents a Site, with support for API queries and returning Pages, Users,
  47. and Categories. The constructor takes a bunch of arguments and you probably
  48. won't need to call it directly, rather tools.get_site() for returning Site
  49. instances, tools.add_site() for adding new ones to config, and
  50. tools.del_site() for removing old ones from config, should suffice.
  51. Public methods:
  52. name -- returns our name (or "wikiid"), like "enwiki"
  53. project -- returns our project name, like "wikipedia"
  54. lang -- returns our language code, like "en"
  55. domain -- returns our web domain, like "en.wikipedia.org"
  56. api_query -- does an API query with the given kwargs as params
  57. sql_query -- does an SQL query and yields its results
  58. get_replag -- returns the estimated database replication lag
  59. namespace_id_to_name -- given a namespace ID, returns associated name(s)
  60. namespace_name_to_id -- given a namespace name, returns associated id
  61. get_page -- returns a Page object for the given title
  62. get_category -- returns a Category object for the given title
  63. get_user -- returns a User object for the given username
  64. """
  65. def __init__(self, name=None, project=None, lang=None, base_url=None,
  66. article_path=None, script_path=None, sql=None,
  67. namespaces=None, login=(None, None), cookiejar=None,
  68. user_agent=None, use_https=False, assert_edit=None,
  69. maxlag=None, search_config=(None, None)):
  70. """Constructor for new Site instances.
  71. This probably isn't necessary to call yourself unless you're building a
  72. Site that's not in your config and you don't want to add it - normally
  73. all you need is tools.get_site(name), which creates the Site for you
  74. based on your config file and the sites database. We accept a bunch of
  75. kwargs, but the only ones you really "need" are `base_url` and
  76. `script_path` - this is enough to figure out an API url. `login`, a
  77. tuple of (username, password), is highly recommended. `cookiejar` will
  78. be used to store cookies, and we'll use a normal CookieJar if none is
  79. given.
  80. First, we'll store the given arguments as attributes, then set up our
  81. URL opener. We'll load any of the attributes that weren't given from
  82. the API, and then log in if a username/pass was given and we aren't
  83. already logged in.
  84. """
  85. # Attributes referring to site information, filled in by an API query
  86. # if they are missing (and an API url can be determined):
  87. self._name = name
  88. self._project = project
  89. self._lang = lang
  90. self._base_url = base_url
  91. self._article_path = article_path
  92. self._script_path = script_path
  93. self._namespaces = namespaces
  94. # Attributes used for API queries:
  95. self._use_https = use_https
  96. self._assert_edit = assert_edit
  97. self._maxlag = maxlag
  98. self._max_retries = 5
  99. # Attributes used for SQL queries:
  100. self._sql_data = sql
  101. self._sql_conn = None
  102. # Attribute used in copyright violation checks (see CopyrightMixin):
  103. self._search_config = search_config
  104. # Set up cookiejar and URL opener for making API queries:
  105. if cookiejar:
  106. self._cookiejar = cookiejar
  107. else:
  108. self._cookiejar = CookieJar()
  109. if not user_agent:
  110. user_agent = USER_AGENT # Set default UA from wiki.constants
  111. self._opener = build_opener(HTTPCookieProcessor(self._cookiejar))
  112. self._opener.addheaders = [("User-Agent", user_agent),
  113. ("Accept-Encoding", "gzip")]
  114. # Get all of the above attributes that were not specified as arguments:
  115. self._load_attributes()
  116. # If we have a name/pass and the API says we're not logged in, log in:
  117. self._login_info = name, password = login
  118. if name and password:
  119. logged_in_as = self._get_username_from_cookies()
  120. if not logged_in_as or name != logged_in_as:
  121. self._login(login)
  122. def __repr__(self):
  123. """Returns the canonical string representation of the Site."""
  124. res = ", ".join((
  125. "Site(name={_name!r}", "project={_project!r}", "lang={_lang!r}",
  126. "base_url={_base_url!r}", "article_path={_article_path!r}",
  127. "script_path={_script_path!r}", "use_https={_use_https!r}",
  128. "assert_edit={_assert_edit!r}", "maxlag={_maxlag!r}",
  129. "sql={_sql_data!r}", "login={0}", "user_agent={2!r}",
  130. "cookiejar={1})"))
  131. name, password = self._login_info
  132. login = "({0}, {1})".format(repr(name), "hidden" if password else None)
  133. cookies = self._cookiejar.__class__.__name__
  134. try:
  135. cookies += "({0!r})".format(self._cookiejar.filename)
  136. except AttributeError:
  137. cookies += "()"
  138. agent = self._opener.addheaders[0][1]
  139. return res.format(login, cookies, agent, **self.__dict__)
  140. def __str__(self):
  141. """Returns a nice string representation of the Site."""
  142. res = "<Site {0} ({1}:{2}) at {3}>"
  143. return res.format(self.name(), self.project(), self.lang(),
  144. self.domain())
  145. def _api_query(self, params, tries=0, wait=5):
  146. """Do an API query with `params` as a dict of parameters.
  147. This will first attempt to construct an API url from self._base_url and
  148. self._script_path. We need both of these, or else we'll raise
  149. SiteAPIError. If self._base_url is protocol-relative (introduced in
  150. MediaWiki 1.18), we'll choose HTTPS if self._user_https is True,
  151. otherwise HTTP.
  152. We'll encode the given params, adding format=json along the way, as
  153. well as &assert= and &maxlag= based on self._assert_edit and _maxlag.
  154. We make the request through self._opener, which has built-in cookie
  155. support via self._cookiejar, a User-Agent (wiki.constants.USER_AGENT),
  156. and Accept-Encoding set to "gzip".
  157. Assuming everything went well, we'll gunzip the data (if compressed),
  158. load it as a JSON object, and return it.
  159. If our request failed for some reason, we'll raise SiteAPIError with
  160. details. If that reason was due to maxlag, we'll sleep for a bit and
  161. then repeat the query until we exceed self._max_retries.
  162. There's helpful MediaWiki API documentation at
  163. <http://www.mediawiki.org/wiki/API>.
  164. """
  165. if not self._base_url or self._script_path is None:
  166. e = "Tried to do an API query, but no API URL is known."
  167. raise SiteAPIError(e)
  168. base_url = self._base_url
  169. if base_url.startswith("//"): # Protocol-relative URLs from 1.18
  170. if self._use_https:
  171. base_url = "https:" + base_url
  172. else:
  173. base_url = "http:" + base_url
  174. url = ''.join((base_url, self._script_path, "/api.php"))
  175. params["format"] = "json" # This is the only format we understand
  176. if self._assert_edit: # If requested, ensure that we're logged in
  177. params["assert"] = self._assert_edit
  178. if self._maxlag: # If requested, don't overload the servers
  179. params["maxlag"] = self._maxlag
  180. data = urlencode(params)
  181. logger.debug("{0} -> {1}".format(url, data))
  182. try:
  183. response = self._opener.open(url, data)
  184. except URLError as error:
  185. if hasattr(error, "reason"):
  186. e = "API query failed: {0}.".format(error.reason)
  187. elif hasattr(error, "code"):
  188. e = "API query failed: got an error code of {0}."
  189. e = e.format(error.code)
  190. else:
  191. e = "API query failed."
  192. raise SiteAPIError(e)
  193. result = response.read()
  194. if response.headers.get("Content-Encoding") == "gzip":
  195. stream = StringIO(result)
  196. gzipper = GzipFile(fileobj=stream)
  197. result = gzipper.read()
  198. try:
  199. res = loads(result) # Parse as a JSON object
  200. except ValueError:
  201. e = "API query failed: JSON could not be decoded."
  202. raise SiteAPIError(e)
  203. try:
  204. code = res["error"]["code"]
  205. info = res["error"]["info"]
  206. except (TypeError, KeyError):
  207. return res
  208. if code == "maxlag":
  209. if tries >= self._max_retries:
  210. e = "Maximum number of retries reached ({0})."
  211. raise SiteAPIError(e.format(self._max_retries))
  212. tries += 1
  213. msg = 'Server says "{0}"; retrying in {1} seconds ({2}/{3})'
  214. logger.info(msg.format(info, wait, tries, self._max_retries))
  215. sleep(wait)
  216. return self._api_query(params, tries=tries, wait=wait*3)
  217. else:
  218. e = 'API query failed: got error "{0}"; server says: "{1}".'
  219. error = SiteAPIError(e.format(code, info))
  220. error.code, error.info = code, info
  221. raise error
  222. def _load_attributes(self, force=False):
  223. """Load data about our Site from the API.
  224. This function is called by __init__() when one of the site attributes
  225. was not given as a keyword argument. We'll do an API query to get the
  226. missing data, but only if there actually *is* missing data.
  227. Additionally, you can call this with `force=True` to forcibly reload
  228. all attributes.
  229. """
  230. # All attributes to be loaded, except _namespaces, which is a special
  231. # case because it requires additional params in the API query:
  232. attrs = [self._name, self._project, self._lang, self._base_url,
  233. self._article_path, self._script_path]
  234. params = {"action": "query", "meta": "siteinfo"}
  235. if not self._namespaces or force:
  236. params["siprop"] = "general|namespaces|namespacealiases"
  237. result = self._api_query(params)
  238. self._load_namespaces(result)
  239. elif all(attrs): # Everything is already specified and we're not told
  240. return # to force a reload, so do nothing
  241. else: # We're only loading attributes other than _namespaces
  242. params["siprop"] = "general"
  243. result = self._api_query(params)
  244. res = result["query"]["general"]
  245. self._name = res["wikiid"]
  246. self._project = res["sitename"].lower()
  247. self._lang = res["lang"]
  248. self._base_url = res["server"]
  249. self._article_path = res["articlepath"]
  250. self._script_path = res["scriptpath"]
  251. def _load_namespaces(self, result):
  252. """Fill self._namespaces with a dict of namespace IDs and names.
  253. Called by _load_attributes() with API data as `result` when
  254. self._namespaces was not given as an kwarg to __init__().
  255. """
  256. self._namespaces = {}
  257. for namespace in result["query"]["namespaces"].values():
  258. ns_id = namespace["id"]
  259. name = namespace["*"]
  260. try:
  261. canonical = namespace["canonical"]
  262. except KeyError:
  263. self._namespaces[ns_id] = [name]
  264. else:
  265. if name != canonical:
  266. self._namespaces[ns_id] = [name, canonical]
  267. else:
  268. self._namespaces[ns_id] = [name]
  269. for namespace in result["query"]["namespacealiases"]:
  270. ns_id = namespace["id"]
  271. alias = namespace["*"]
  272. self._namespaces[ns_id].append(alias)
  273. def _get_cookie(self, name, domain):
  274. """Return the named cookie unless it is expired or doesn't exist."""
  275. for cookie in self._cookiejar:
  276. if cookie.name == name and cookie.domain == domain:
  277. if cookie.is_expired():
  278. break
  279. return cookie
  280. def _get_username_from_cookies(self):
  281. """Try to return our username based solely on cookies.
  282. First, we'll look for a cookie named self._name + "Token", like
  283. "enwikiToken". If it exists and isn't expired, we'll assume it's valid
  284. and try to return the value of the cookie self._name + "UserName" (like
  285. "enwikiUserName"). This should work fine on wikis without single-user
  286. login.
  287. If `enwikiToken` doesn't exist, we'll try to find a cookie named
  288. `centralauth_Token`. If this exists and is not expired, we'll try to
  289. return the value of `centralauth_User`.
  290. If we didn't get any matches, we'll return None. Our goal here isn't to
  291. return the most likely username, or what we *want* our username to be
  292. (for that, we'd do self._login_info[0]), but rather to get our current
  293. username without an unnecessary ?action=query&meta=userinfo API query.
  294. """
  295. domain = self.domain()
  296. name = ''.join((self._name, "Token"))
  297. cookie = self._get_cookie(name, domain)
  298. if cookie:
  299. name = ''.join((self._name, "UserName"))
  300. user_name = self._get_cookie(name, domain)
  301. if user_name:
  302. return user_name.value
  303. name = "centralauth_Token"
  304. for cookie in self._cookiejar:
  305. if not cookie.domain_initial_dot or cookie.is_expired():
  306. continue
  307. if cookie.name != name:
  308. continue
  309. # Build a regex that will match domains this cookie affects:
  310. search = ''.join(("(.*?)", re_escape(cookie.domain)))
  311. if re_match(search, domain): # Test it against our site
  312. user_name = self._get_cookie("centralauth_User", cookie.domain)
  313. if user_name:
  314. return user_name.value
  315. def _get_username_from_api(self):
  316. """Do a simple API query to get our username and return it.
  317. This is a reliable way to make sure we are actually logged in, because
  318. it doesn't deal with annoying cookie logic, but it results in an API
  319. query that is unnecessary in some cases.
  320. Called by _get_username() (in turn called by get_user() with no
  321. username argument) when cookie lookup fails, probably indicating that
  322. we are logged out.
  323. """
  324. params = {"action": "query", "meta": "userinfo"}
  325. result = self._api_query(params)
  326. return result["query"]["userinfo"]["name"]
  327. def _get_username(self):
  328. """Return the name of the current user, whether logged in or not.
  329. First, we'll try to deduce it solely from cookies, to avoid an
  330. unnecessary API query. For the cookie-detection method, see
  331. _get_username_from_cookies()'s docs.
  332. If our username isn't in cookies, then we're probably not logged in, or
  333. something fishy is going on (like forced logout). In this case, do a
  334. single API query for our username (or IP address) and return that.
  335. """
  336. name = self._get_username_from_cookies()
  337. if name:
  338. return name
  339. return self._get_username_from_api()
  340. def _save_cookiejar(self):
  341. """Try to save our cookiejar after doing a (normal) login or logout.
  342. Calls the standard .save() method with no filename. Don't fret if our
  343. cookiejar doesn't support saving (CookieJar raises AttributeError,
  344. FileCookieJar raises NotImplementedError) or no default filename was
  345. given (LWPCookieJar and MozillaCookieJar raise ValueError).
  346. """
  347. try:
  348. self._cookiejar.save()
  349. except (AttributeError, NotImplementedError, ValueError):
  350. pass
  351. def _login(self, login, token=None, attempt=0):
  352. """Safely login through the API.
  353. Normally, this is called by __init__() if a username and password have
  354. been provided and no valid login cookies were found. The only other
  355. time it needs to be called is when those cookies expire, which is done
  356. automatically by api_query() if a query fails.
  357. Recent versions of MediaWiki's API have fixed a CSRF vulnerability,
  358. requiring login to be done in two separate requests. If the response
  359. from from our initial request is "NeedToken", we'll do another one with
  360. the token. If login is successful, we'll try to save our cookiejar.
  361. Raises LoginError on login errors (duh), like bad passwords and
  362. nonexistent usernames.
  363. `login` is a (username, password) tuple. `token` is the token returned
  364. from our first request, and `attempt` is to prevent getting stuck in a
  365. loop if MediaWiki isn't acting right.
  366. """
  367. name, password = login
  368. params = {"action": "login", "lgname": name, "lgpassword": password}
  369. if token:
  370. params["lgtoken"] = token
  371. result = self._api_query(params)
  372. res = result["login"]["result"]
  373. if res == "Success":
  374. self._save_cookiejar()
  375. elif res == "NeedToken" and attempt == 0:
  376. token = result["login"]["token"]
  377. return self._login(login, token, attempt=1)
  378. else:
  379. if res == "Illegal":
  380. e = "The provided username is illegal."
  381. elif res == "NotExists":
  382. e = "The provided username does not exist."
  383. elif res == "EmptyPass":
  384. e = "No password was given."
  385. elif res == "WrongPass" or res == "WrongPluginPass":
  386. e = "The given password is incorrect."
  387. else:
  388. e = "Couldn't login; server says '{0}'.".format(res)
  389. raise LoginError(e)
  390. def _logout(self):
  391. """Safely logout through the API.
  392. We'll do a simple API request (api.php?action=logout), clear our
  393. cookiejar (which probably contains now-invalidated cookies) and try to
  394. save it, if it supports that sort of thing.
  395. """
  396. params = {"action": "logout"}
  397. self._api_query(params)
  398. self._cookiejar.clear()
  399. self._save_cookiejar()
  400. def _sql_connect(self, **kwargs):
  401. """Attempt to establish a connection with this site's SQL database.
  402. oursql.connect() will be called with self._sql_data as its kwargs.
  403. Any kwargs given to this function will be passed to connect() and will
  404. have precedence over the config file.
  405. Will raise SQLError() if the module "oursql" is not available. oursql
  406. may raise its own exceptions (e.g. oursql.InterfaceError) if it cannot
  407. establish a connection.
  408. """
  409. if not oursql:
  410. e = "Module 'oursql' is required for SQL queries."
  411. raise SQLError(e)
  412. args = self._sql_data
  413. for key, value in kwargs.iteritems():
  414. args[key] = value
  415. if "read_default_file" not in args and "user" not in args and "passwd" not in args:
  416. args["read_default_file"] = expanduser("~/.my.cnf")
  417. self._sql_conn = oursql.connect(**args)
  418. def name(self):
  419. """Returns the Site's name (or "wikiid" in the API), like "enwiki"."""
  420. return self._name
  421. def project(self):
  422. """Returns the Site's project name in lowercase, like "wikipedia"."""
  423. return self._project
  424. def lang(self):
  425. """Returns the Site's language code, like "en" or "es"."""
  426. return self._lang
  427. def domain(self):
  428. """Returns the Site's web domain, like "en.wikipedia.org"."""
  429. return urlparse(self._base_url).netloc
  430. def api_query(self, **kwargs):
  431. """Do an API query with `kwargs` as the parameters.
  432. See _api_query()'s documentation for details.
  433. """
  434. return self._api_query(kwargs)
  435. def sql_query(self, query, params=(), plain_query=False, dict_cursor=False,
  436. cursor_class=None, show_table=False):
  437. """Do an SQL query and yield its results.
  438. If `plain_query` is True, we will force an unparameterized query.
  439. Specifying both params and plain_query will cause an error.
  440. If `dict_cursor` is True, we will use oursql.DictCursor as our cursor,
  441. otherwise the default oursql.Cursor. If `cursor_class` is given, it
  442. will override this option.
  443. If `show_table` is True, the name of the table will be prepended to the
  444. name of the column. This will mainly affect a DictCursor.
  445. Example:
  446. >>> query = "SELECT user_id, user_registration FROM user WHERE user_name = ?"
  447. >>> params = ("The Earwig",)
  448. >>> result1 = site.sql_query(query, params)
  449. >>> result2 = site.sql_query(query, params, dict_cursor=True)
  450. >>> for row in result1: print row
  451. (7418060L, '20080703215134')
  452. >>> for row in result2: print row
  453. {'user_id': 7418060L, 'user_registration': '20080703215134'}
  454. See _sql_connect() for information on how a connection is acquired.
  455. <http://packages.python.org/oursql> has helpful documentation on the
  456. oursql module.
  457. This may raise SQLError() or one of oursql's exceptions
  458. (oursql.ProgrammingError, oursql.InterfaceError, ...) if there were
  459. problems with the query.
  460. """
  461. if not self._sql_conn:
  462. self._sql_connect()
  463. if not cursor_class:
  464. if dict_cursor:
  465. cursor_class = oursql.DictCursor
  466. else:
  467. cursor_class = oursql.Cursor
  468. with self._sql_conn.cursor(cursor_class, show_table=show_table) as cur:
  469. cur.execute(query, params, plain_query)
  470. for result in cur:
  471. yield result
  472. def get_replag(self):
  473. """Return the estimated database replication lag in seconds.
  474. Requires SQL access. This function only makes sense on a replicated
  475. database (e.g. the Wikimedia Toolserver) and on a wiki that receives a
  476. large number of edits (ideally, at least one per second), or the result
  477. may be larger than expected.
  478. """
  479. query = """SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(rc_timestamp) FROM
  480. recentchanges ORDER BY rc_timestamp DESC LIMIT 1"""
  481. result = list(self.sql_query(query))
  482. return result[0][0]
  483. def namespace_id_to_name(self, ns_id, all=False):
  484. """Given a namespace ID, returns associated namespace names.
  485. If all is False (default), we'll return the first name in the list,
  486. which is usually the localized version. Otherwise, we'll return the
  487. entire list, which includes the canonical name.
  488. For example, returns u"Wikipedia" if ns_id=4 and all=False on enwiki;
  489. returns [u"Wikipedia", u"Project", u"WP"] if ns_id=4 and all=True.
  490. Raises NamespaceNotFoundError if the ID is not found.
  491. """
  492. try:
  493. if all:
  494. return self._namespaces[ns_id]
  495. else:
  496. return self._namespaces[ns_id][0]
  497. except KeyError:
  498. e = "There is no namespace with id {0}.".format(ns_id)
  499. raise NamespaceNotFoundError(e)
  500. def namespace_name_to_id(self, name):
  501. """Given a namespace name, returns the associated ID.
  502. Like namespace_id_to_name(), but reversed. Case is ignored, because
  503. namespaces are assumed to be case-insensitive.
  504. Raises NamespaceNotFoundError if the name is not found.
  505. """
  506. lname = name.lower()
  507. for ns_id, names in self._namespaces.items():
  508. lnames = [n.lower() for n in names] # Be case-insensitive
  509. if lname in lnames:
  510. return ns_id
  511. e = "There is no namespace with name '{0}'.".format(name)
  512. raise NamespaceNotFoundError(e)
  513. def get_page(self, title, follow_redirects=False):
  514. """Returns a Page object for the given title (pagename).
  515. Will return a Category object instead if the given title is in the
  516. category namespace. As Category is a subclass of Page, this should not
  517. cause problems.
  518. Note that this doesn't do any direct checks for existence or
  519. redirect-following - Page's methods provide that.
  520. """
  521. prefixes = self.namespace_id_to_name(NS_CATEGORY, all=True)
  522. prefix = title.split(":", 1)[0]
  523. if prefix != title: # Avoid a page that is simply "Category"
  524. if prefix in prefixes:
  525. return Category(self, title, follow_redirects)
  526. return Page(self, title, follow_redirects)
  527. def get_category(self, catname, follow_redirects=False):
  528. """Returns a Category object for the given category name.
  529. `catname` should be given *without* a namespace prefix. This method is
  530. really just shorthand for get_page("Category:" + catname).
  531. """
  532. prefix = self.namespace_id_to_name(NS_CATEGORY)
  533. pagename = ':'.join((prefix, catname))
  534. return Category(self, pagename, follow_redirects)
  535. def get_user(self, username=None):
  536. """Returns a User object for the given username.
  537. If `username` is left as None, then a User object representing the
  538. currently logged-in (or anonymous!) user is returned.
  539. """
  540. if not username:
  541. username = self._get_username()
  542. return User(self, username)