Skip to content

Samples

daremiyo edited this page Sep 30, 2020 · 6 revisions

Generate an XLSX Report of Accessions for the Last Fiscal Year

from asnake.aspace import ASpace
from openpyxl import Workbook

repo = ASpace().repositories(2)

# authenticates the session
auth = requests.post('{baseURL}/users/{user}/login?password={password}&expiring=false'.format(**dictionary)).json()
session = auth["session"]
headers = {'X-ArchivesSpace-Session':session}

# The Parameters of the Fiscal Year
dateStart = "2017-06-30"
dateEnd = "2018-07-01"

#make a new spreadsheet
wb = Workbook()
ws = wb.active

# Spreadsheet Header
ws.append(["Accession ID", "Accession Date", "Collection ID", "Title", "Extent", "Extent Type", "Content Description"])

# Loop though all accessions
for accession in repo.accessions:
        
    # The date of the accession
    accessionDate = accession.accession_date
    
    # Check if accession falls within the fiscal year
    if accessionDate > dateStart and accessionDate < dateEnd:
        
        # start a row to add for an accession
        row = []
        
        # Accession ID
        if "id_1" in dir(accession):
            accessionID = accession.id_0 + "." + accession.id_1
        else:
            accessionID = accession.id_0
        row.append(accessionID)
        
        # print ID and title to console
        if "title" in dir(accession):
            print (accessionID + " - " + accession.title)
        else:
            print (accessionID + " - ")
        
        # Accession Date
        row.append(accession.accession_date)
        
        # Collection ID
        if len(accession.related_resources) > 0:
            collectionList = []
            for collection in accession.related_resources:
                collectionList.append(collection.id_0)
            row.append(", ".join(collectionList))
        else:
            row.append("")
        
        # Title
        if "title" in dir(accession):
            row.append(accession.title)
        else:
            row.append("")
            
        # Extents
        if len(accession.extents) > 0:
            extentNumber = []
            extentType = []
            for extent in accession.extents:
                extentNumber.append(extent.number)
                extentType.append(extent.extent_type)
            row.append(", ".join(extentNumber))
            row.append(", ".join(extentType))
        else:
            row.append("")
            row.append("")
        
        # Content Description
        if "content_description" in dir(accession):
            row.append(accession.content_description)
        else:
            row.append("")
            
        
        # Add the row to the worksheet           
        ws.append(row)

# Save the Spreadsheet
wb.save("accessionsFY2017.xlsx")

Change a File Title

#!/usr/bin/env python

# imports python modules
import json
from asnake.aspace import ASpace
import asnake.logging as logging

logging.setup_logging(filename='output.log', filemode="w")
logger = logging.get_logger()

# authenticates ASpace session; baseURL refers to ASpace IP address
aspace = ASpace(
    baseurl='http://localhost:4567',
    username='admin',
    password='admin'
)
# points to ASpace repository
repo = aspace.repositories(2)

# function to change title
def change_file_title():
    # 1167735 refers to the archival objects' URI
    file = repo.archival_objects(1167737)
    # prints the title of the file level archival object
    print(file.title)
    file_level_json = file.json()
    file_level_json["title"] = "new title"
    # posts changes to ASpace
    changetitle = aspace.client.post(file.uri, json=file_level_json)
    logger.info("Changed file title from " + file_level_json["title"] + " to new title")

# runs the function defined above
change_file_title()

Delete Resource Records from a CSV file

#!/usr/bin/env python

# imports python modules
import os
import json
from asnake.aspace import ASpace
import asnake.logging as logging
import csv

logging.setup_logging(filename='output.log', filemode="w")
logger = logging.get_logger()

# authenticates ASpace session; baseURL refers to ASpace IP address
aspace = ASpace(
    baseurl='http://localhost:4567',
    username='admin',
    password='admin'
)

repo = aspace.repositories(2)
# logging takes several arguments, provides defaults, etc

# expects a csv file with a row title "resource_id"
def delete_resources(data):
    # opens and reads csv file
    with open(data, newline='') as data:
        reader = csv.DictReader(data)
        for row in reader:
            try:
                uri = "/repositories/2/resources/"
                resource_id = str(row['resource_id'])
                delete = aspace.client.delete(uri + resource_id)
                logger.info("Deleted resource" + resource_id)
                print("deleted resource " + resource_id)
            except:
                pass

# csv title
data = "resources.csv"

delete_resources(data)

Write a List of Folder Titles from a Resource Record to a CSV file

#!/usr/bin/env python

# imports python modules
import json
from asnake.aspace import ASpace
import os
import csv

# authenticates ASpace session; baseURL refers to ASpace IP address
aspace = ASpace(
    baseurl='http://localhost:4567',
    username='admin',
    password='admin'
)

repo = aspace.repositories(2)
# refers to collection with identifier 102
collection = repo.resources(102)

# creates csv file called "folder_titles with a header called folder_title"
def folder_titles_csv(csvName):
    fieldnames = ['folder_title']
    with open(csvName, 'w', newline='') as outputFile:
        writer = csv.DictWriter(outputFile, fieldnames=fieldnames)
        writer.writeheader()
        get_folder_titles(writer)

# gets folder titles from collection and writes them to csv
def get_folder_titles(writer):
    for series in collection.tree.children:
        for folder in series.children:
            print(format(folder.title.split('/')[-1]))
            writer.writerow({"folder_title": folder.title})

csvName = "folder_titles.csv"

# runs script
folder_titles_csv(csvName)

Get All Notes on an Archival Object

#!/usr/bin/env python

#Imports python modules
import os
import json
from asnake.aspace import ASpace
import asnake.logging as logging

#Sets up logging
logging.setup_logging(filename='get_notes_logfile.log')
#Sets up logger
logger = logging.get_logger("script_log")

#Authenticates ASpace session; baseURL refers to ASpace IP address
aspace = Aspace(
                baseurl='http://localhost:4567'.
                username='admin',
                password='admin',
)

#Gets repository
repo = apsace.repositories(2)

#Gets archival object
#Put archival object Ref ID in ()
ao = repo.archival_objects(a244724ae9fc152a3abaad21989abc36)

#Prints title of archival object
#File is the object's level
print(file.title)

#Gets note type for each note on archival object and appends to list
def get_ao_notes(ao)
    if ao.get("notes"):
        note_list = []
        for n in ao.get("notes"):
            if n.get("type") in ["bioghist", "scopecontent", "relatedmaterial", "separatedmaterial", "phystech", "processinfo", "otherfindaid", "originalsloc", "fileplan", "arrangement"]:
                if n.get("jsonmodel_type") not in ["note_definedlist"]:
                    note_list.append(n.get("subnotes")[0].get("content").replace('\n', ' ').strip())
        return " | ".join(note_list)
    else:
        return ""