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

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

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)
23
        # self.s.headers = {'content-type': 'application/json'}
24
25
26

        self.drupal_user = username
        self.drupal_pass = password
27
28
29
30
31
        self.cookie_jar = '/tmp/cookies'
        try:
            self.s.cookies = pickle.load(open(self.cookie_jar, 'r'))
        except Exception, e:
            pass
32
33
34

    def do_login(self):
        url = '{b}/user'.format(b=self.base_url)
35
36
37
        form = BeautifulSoup(self.s.get(url).text).find('form', id='user-login')
        form_build_id = form.find_all('input', attrs={'name': 'form_build_id'})

38
39
40
41
42
43
        resp = self.s.post(
            url,
            data={
                'name': self.drupal_user,
                'pass': self.drupal_pass,
                'form_id': 'user_login',
44
                'form_build_id': form_build_id,
45
46
47
48
                'op': 'Log in'
            },
            allow_redirects=False
        )
49

50
        pickle.dump(self.s.cookies, open(self.cookie_jar, 'wb'))
51
52
53
54
55
56
57

        return resp

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

58
        resp = self.s.get(url, verify=False, headers={'content-type': 'application/json'}, cookies=self.s.cookies)
59
        return resp
60
61
62
63

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

64
        return self.s.get(url, verify=False, headers={'content-type': 'application/json'}, cookies=self.s.cookies).json()
65
66
67
68
69
70

    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

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

73