Putting it all together, next you need to update the if block to match what’s below (also make sure that you’re still importing your newly created login module).
#!/usr/bin/env python3
import urllib.request
import urllib.parse
import urllib.error
import json
# Here's our own login module
import login
def create_repo(api_url, auth_token, name, repo_code, org_code = '', image_url = '', url = ''):
'''This function sends a create request to the ArchivesSpace REST API'''
data = json.JSONEncoder().encode({
'jsonmodel_type': 'repository',
'name': name,
'repo_code': repo_code,
'org_code': org_code,
'image_url': image_url,
'url': url
}).encode('utf-8')
req = urllib.request.Request(
url = api_url+'/repositories',
data = None,
headers = {'X-ArchivesSpace-Session': auth_token})
try:
response = urllib.request.urlopen(req, data)
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')
return json.JSONDecoder().decode(src)
if __name__ == '__main__':
import getpass
# Test login
print("Testing login()")
api_url = input('ArchivesSpace API URL: ')
username = input('ArchivesSpace username: ')
password = getpass.getpass('ArchivesSpace password: ')
print('Logging in', api_url)
auth_token = login.login(api_url, username, password)
print("auth token", auth_token)
if auth_token != '':
print('Success!')
else:
print('Ooops! something went wrong')
sys.exit(1)
# Test create_repo
print('Testing create_repo()')
print('Create your first repository')
name = input('Repo name: ')
repo_code = input('Repo code: ')
repo = create_repo(api_url, auth_token, name, repo_code)
print(json.dumps(repo, indent=4))
print('Create a second repository')
name = input('Repo name: ')
repo_code = input('Repo code: ')
repo = create_repo(api_url, auth_token, name, repo_code)
print(json.dumps(repo, indent=4))
Full listing repo.py