This repository has been archived by the owner on Aug 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
30-ArchivesSpace-API-Workshop.html
77 lines (66 loc) · 2.77 KB
/
30-ArchivesSpace-API-Workshop.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html>
<head>
<link href="css/slides.css" rel="stylesheet" />
</head>
<body>
<nav>
<a id="start-slide" rel="nav" href="00-ArchivesSpace-API-Workshop.html" title="Return to start of presentation">Start</a>
<a id="prev-slide" rel="nav" href="29-ArchivesSpace-API-Workshop.html" title="Previous slide">Prev</a>
<a id="next-slide" rel="nav" href="31-ArchivesSpace-API-Workshop.html" title="Next slide">Next</a>
</nav>
<section><h1>3. Authentication</h1>
<h2>Save the access token returned</h2>
<p>We need to modify our login function to “decode” the JSON
response and return only session value.</p>
<p>In total We’re adding a <em>import json</em>, modifying
our <em>login</em> function and updating the testing in the
closing <em>if</em> block.</p>
<pre><code class="language-python"> #!/usr/bin/env python3
import urllib.request
import urllib.parse
import urllib.error
import json
def login (api_url, username, password):
'''This function logs into the ArchivesSpace REST API returning an acccess token'''
data = urllib.parse.urlencode({'password': password}).encode('utf-8')
req = urllib.request.Request(
url = api_url+'/users/'+username+'/login',
data = data)
try:
response = urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read())
return ""
except urllib.error.URLError as e:
print(e.reason())
return ""
src = response.read().decode('utf-8')
result = json.JSONDecoder().decode(src)
# Session holds the value we want for auth_token
return result['session']
if __name__ == '__main__':
import getpass
api_url = input('ArchivesSpace API URL: ')
username = input('ArchivesSpace username: ')
password = getpass.getpass('ArchivesSpacew password: ')
print('Logging in', api_url)
auth_token = login(api_url, username, password)
print(auth_token)
if auth_token != '':
print('Success!')
else:
print('Ooops! something went wrong')
</code></pre>
<p>Full listing <a href="login.py">login.py</a></p>
<p>This is our first module. It will get reused in <strong>repo.py</strong>, <strong>agent.py</strong>
and <strong>accession.py</strong>. I’ve added some extra handling around <em>urlopen</em>.
This will give us a little more orderly output when something goes wrong
in the http request.</p>
<p>If all goes well you’ll see “Success!” when you run the module.</p>
<p>Up next is working with repositories!</p>
</section>
<script type="text/javascript" src="js/keyboard-nav.js"></script>
</body>
</html>