]> code.communitydata.science - rises_declines_wikia_code.git/blob - mediawiki_dump_tools/Mediawiki-Utilities/mw/api/session.py
Initial commit
[rises_declines_wikia_code.git] / mediawiki_dump_tools / Mediawiki-Utilities / mw / api / session.py
1 import logging
2
3 from ..util import api
4 from .collections import (DeletedRevisions, Pages, RecentChanges, Revisions,
5                           SiteInfo, UserContribs, Users)
6 from .errors import APIError, AuthenticationError, MalformedResponse
7
8 logger = logging.getLogger("mw.api.session")
9
10 DEFAULT_USER_AGENT = "MediaWiki-Utilities"
11 """
12 The default User-Agent to be sent with requests to the API.
13 """
14
15 class Session(api.Session):
16     """
17     Represents a connection to a MediaWiki API.
18
19     Cookies and other session information is preserved.
20
21     :Parameters:
22         uri : str
23             The base URI for the API to use.  Usually ends in "api.php"
24         user_agent : str
25             The User-Agent to be sent with requests.  Will raise a warning if
26             left to default value.
27     """
28
29     def __init__(self, uri, *args, user_agent=DEFAULT_USER_AGENT, **kwargs):
30         """
31         Constructs a new :class:`Session`.
32         """
33
34         if user_agent == DEFAULT_USER_AGENT:
35             logger.warning("Sending requests with default User-Agent.  "  +
36                            "Set 'user_agent' on api.Session to quiet this " +
37                            "message.")
38
39         if 'headers' in kwargs:
40             kwargs['headers']['User-Agent'] = str(user_agent)
41         else:
42             kwargs['headers'] = {'User-Agent': str(user_agent)}
43
44         super().__init__(uri, *args, **kwargs)
45
46         self.pages = Pages(self)
47         """
48         An instance of :class:`mw.api.Pages`.
49         """
50
51         self.revisions = Revisions(self)
52         """
53         An instance of :class:`mw.api.Revisions`.
54         """
55
56         self.recent_changes = RecentChanges(self)
57         """
58         An instance of :class:`mw.api.RecentChanges`.
59         """
60
61         self.site_info = SiteInfo(self)
62         """
63         An instance of :class:`mw.api.SiteInfo`.
64         """
65
66         self.user_contribs = UserContribs(self)
67         """
68         An instance of :class:`mw.api.UserContribs`.
69         """
70
71         self.users = Users(self)
72         """
73         An instance of :class:`mw.api.Users`.
74         """
75
76         self.deleted_revisions = DeletedRevisions(self)
77         """
78         An instance of :class:`mw.api.DeletedRevisions`.
79         """
80
81     def login(self, username, password, token=None):
82         """
83         Performs a login operation.  This method usually makes two requests to
84         API -- one to get a token and one to use the token to log in.  If
85         authentication fails, this method will throw an
86         :class:`.errors.AuthenticationError`.
87
88         :Parameters:
89             username : str
90                 Your username
91             password : str
92                 Your password
93
94         :Returns:
95             The response in a json :py:class:`dict`
96         """
97
98         doc = self.post(
99             {
100                 'action': "login",
101                 'lgname': username,
102                 'lgpassword': password,
103                 'lgtoken': token, # If None, we'll be getting a token
104             }
105         )
106
107
108         try:
109             if doc['login']['result'] == "Success":
110                 return doc
111             elif doc['login']['result'] == "NeedToken":
112
113                 if token is not None:
114                     # Woops.  We've been here before.  Better error out.
115                     raise AuthenticationError(doc)
116                 else:
117                     token = doc['login']['token']
118                     return self.login(username, password, token=token)
119             else:
120                 raise AuthenticationError(doc)
121
122         except KeyError as e:
123             raise MalformedResponse(e.message, doc)
124
125
126     def request(self, type, params, **kwargs):
127         params.update({'format': "json"})
128
129         doc = super().request(type, params, **kwargs).json()
130
131         if 'error' in doc:
132             raise APIError(doc)
133
134         return doc

Community Data Science Collective || Want to submit a patch?