8 """Object representing connection with the server.
9 It is pushed around internally and is considered private.
11 def __init__(self
, pod
, username
='', password
=''):
13 :param pod: The complete url of the diaspora pod to use.
15 :param username: The username used to log in.
17 :param password: The password used to log in.
21 self
.session
= requests
.Session()
22 self
._token
_regex
= re
.compile(r
'content="(.*?)"\s+name="csrf-token')
23 self
._setlogin
(username
, password
)
25 def get(self
, string
):
26 """This method gets data from session.
27 Performs additional checks if needed.
30 To obtain 'foo' from pod one should call `_sessionget('foo')`.
32 :param string: URL to get without the pod's URL and slash eg. 'stream'.
35 return self
.session
.get('{0}/{1}'.format(self
.pod
, string
))
37 def post(self
, string
, data
, headers
={}, params
={}):
38 """This method posts data to session.
39 Performs additional checks if needed.
42 To post to 'foo' one should call `_sessionpost('foo', data={})`.
44 :param string: URL to post without the pod's URL and slash eg. 'status_messages'.
46 :param data: Data to post.
47 :param headers: Headers (optional).
49 :param params: Parameters (optional).
52 string
= '{0}/{1}'.format(self
.pod
, string
)
53 if headers
and params
:
54 request
= self
.session
.post(string
, data
=data
, headers
=headers
, params
=params
)
55 elif headers
and not params
:
56 request
= self
.session
.post(string
, data
=data
, headers
=headers
)
57 elif not headers
and params
:
58 request
= self
.session
.post(string
, data
=data
, params
=params
)
60 request
= self
.session
.post(string
, data
=data
)
63 def delete(self
, string
, data
, headers
={}):
64 """This method lets you send delete request to session.
65 Performs additional checks if needed.
67 :param string: URL to use.
69 :param data: Data to use.
70 :param headers: Headers to use (optional).
73 string
= '{0}/{1}'.format(self
.pod
, string
)
75 request
= self
.session
.delete(string
, data
=data
, headers
=headers
)
77 request
= self
.session
.delete(string
, data
=data
)
80 def _setlogin(self
, username
, password
):
81 """This function is used to set data for login.
83 It should be called before _login() function.
85 self
.username
, self
.password
= username
, password
86 self
.login_data
= {'user[username]': self
.username
,
87 'user[password]': self
.password
,
88 'authenticity_token': self
.getToken()}
91 """This function is used to connect to the pod and log in.
93 r
= self
.post('users/sign_in',
95 headers
={'accept': 'application/json'})
96 if r
.status_code
!= 201:
97 raise Exception('{0}: Login failed.'.format(r
.status_code
))
100 """This function gets a token needed for authentication in most cases
102 :returns: string -- token used to authenticate
104 r
= self
.get('stream')
105 token
= self
._token
_regex
.search(r
.text
).group(1)