nca3_client.py 2.08 KB
Newer Older
1
2
3
__author__ = 'abuddenberg'

import requests
4
5
import pickle
import json
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

def http_resp(fn):
    def wrapped(*args, **kwargs):
        resp = fn(*args, **kwargs)
        if resp.status_code == 200:
            return resp
        else:
            raise Exception('Status: {code} \n{txt}'.format(code=resp.status_code, txt=resp.text))
    return wrapped


class Nca3Client(object):
    def __init__(self, url, username, password, http_basic_user=None, http_basic_pass=None):
        self.base_url = url
        self.s = requests.Session()
        self.s.auth = (http_basic_user, http_basic_pass)
22
        self.s.headers = {'content-type': 'application/json'}
23
24
25

        self.drupal_user = username
        self.drupal_pass = password
26
27
28
29
30
        self.cookie_jar = '/tmp/cookies'
        try:
            self.s.cookies = pickle.load(open(self.cookie_jar, 'r'))
        except Exception, e:
            pass
31
32
33
34
35
36
37
38
39
40
41
42
43

    def do_login(self):
        url = '{b}/user'.format(b=self.base_url)
        resp = self.s.post(
            url,
            data={
                'name': self.drupal_user,
                'pass': self.drupal_pass,
                'form_id': 'user_login',
                'op': 'Log in'
            },
            allow_redirects=False
        )
44
        pickle.dump(self.s.cookies, open(self.cookie_jar, 'wb'))
45
46
47
48
49
50
51

        return resp

    @http_resp
    def get_all_captions(self):
        url = '{b}/gcis/figure-table-captions'.format(b=self.base_url)

52
        resp = self.s.get(url, verify=False, cookies=self.s.cookies)
53
        return resp
54
55
56
57
58
59
60
61
62
63
64
65
66

    def get_figure(self, nid):
        url = '{b}/gcis/node/{nid}'.format(b=self.base_url, nid=nid)

        return self.s.get(url, verify=False, cookies=self.s.cookies).json()

    def update_figure(self, nid, figure_frag):
        url = '{b}/gcis/node/{nid}'.format(b=self.base_url, nid=nid)
        token_url = '{b}/services/session/token'.format(b=self.base_url)
        token = self.s.get(token_url, verify=False, cookies=self.s.cookies).text

        return self.s.put(url, data=json.dumps(figure_frag), verify=False, cookies=self.s.cookies, headers={'X-CSRF-Token': token})