Skip to content
This repository has been archived by the owner on Feb 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #9 from Abbe98/new
Browse files Browse the repository at this point in the history
1.3.0
  • Loading branch information
Abbe98 committed Jun 3, 2020
2 parents 0775ae9 + 1baa99b commit eb7d3e9
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 21 deletions.
13 changes: 5 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# SOCH UGC

SOCH UGC is a Python library for accessing and writing data to the [User Generated Content API](https://www.raa.se/hitta-information/k-samsok/anvandargenererat-innehall-ugc-hubben/) that is a part of the Swedish Open Cultural Heritage (SOCH/K-Samsök) API.
SOCH UGC is a Python library for accessing and writing data to the [User Generated Content API](https://ugc.kulturarvsdata.se/UGC-hub/) that is a part of the Swedish Open Cultural Heritage (SOCH/K-Samsök) API.

## Install SOCH UGC

Expand All @@ -13,8 +13,9 @@ pip install sochugc
```python
from sochugc import UGC

# the endpoint defaults to http://ugc.kulturarvsdata.se/
ugc = UGC('<API-KEY>', endpoint='http://lx-ra-ugchubtest:8080/')
# the endpoint defaults to https://ugc.kulturarvsdata.se/
# the key parameter is only needed for write actions
ugc = UGC(endpoint='http://localhost:8080/', key='<API-KEY>')

# get the total number of user generated items
ugc.get_total_items_count()
Expand All @@ -23,13 +24,9 @@ ugc.get_total_items_count()
ugc.get_item(679)

# Searching all items or items tied to a specific URI
# to search all items and not only ones connected to an specific URI omit the uri parameter
# to search all items and not only ones connected to a specific URI omit the uri parameter
ugc.search_items(uri='http://kulturarvsdata.se/raa/bbr/21400000440954', offset=0, limit=100)

#
# Writing data is not available for everyone
#

# deleting an item using its id
ugc.delete_item(679)

Expand Down
4 changes: 3 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from setuptools import setup, find_packages
from os import path

version = '1.2.0'
version = '1.3.0'
repo = 'soch-ugc-py'

this_directory = path.abspath(path.dirname(__file__))
Expand Down Expand Up @@ -30,6 +30,8 @@
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3 :: Only',
'Intended Audience :: Developers',
'Intended Audience :: Education'
Expand Down
47 changes: 35 additions & 12 deletions sochugc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ksamsok import KSamsok

class UGC:
def __init__(self, key: str, endpoint: str = 'http://ugc.kulturarvsdata.se/') -> None:
def __init__(self, endpoint: str = 'https://ugc.kulturarvsdata.se/', key: str = None) -> None:
self.endpoint = endpoint + 'UGC-hub/'
self.key = key

Expand All @@ -19,6 +19,7 @@ def __init__(self, key: str, endpoint: str = 'http://ugc.kulturarvsdata.se/') ->
self.relation_types = list([
'sameAs',
'isDescribedBy',
'describes',
'visualizes',
'hasPart',
'isPartOf',
Expand All @@ -41,17 +42,14 @@ def __init__(self, key: str, endpoint: str = 'http://ugc.kulturarvsdata.se/') ->
'mentions'
])

# so that the user get endpoint/key errors early
self.get_total_items_count()

def get_total_items_count(self) -> str:
url = '{}api?x-api={}&method=retrieve&scope=count&objectUri=all&format=json'.format(self.endpoint, self.key)
url = '{}api?method=retrieve&scope=count&objectUri=all&format=json'.format(self.endpoint)
data = self.make_get_request(url)

return data['response']['relations']['numberOfRelations']

def get_item(self, item_id: Union[int, str]) -> Union[Dict, bool]:
url = '{}api?x-api={}&method=retrieve&objectUri=all&contentId={}&scope=single&format=json'.format(self.endpoint, self.key, item_id)
url = '{}api?method=retrieve&objectUri=all&contentId={}&scope=single&format=json'.format(self.endpoint, item_id)
data = self.make_get_request(url)

if data['response']['relations'][0]['id'] is 0:
Expand All @@ -60,7 +58,7 @@ def get_item(self, item_id: Union[int, str]) -> Union[Dict, bool]:
return data['response']['relations'][0]

def search_items(self, uri: str = 'all', offset: int = 0, limit: int = 50) -> List:
url = '{}api?x-api={}&method=retrieve&scope=all&objectUri={}&selectFrom={}&maxCount={}&format=json'.format(self.endpoint, self.key, uri, offset, limit)
url = '{}api?method=retrieve&scope=all&objectUri={}&selectFrom={}&maxCount={}&format=json'.format(self.endpoint, uri, offset, limit)
data = self.make_get_request(url)

return data['response']['relations']
Expand All @@ -69,11 +67,14 @@ def delete_item(self, item_id: Union[int, str]) -> bool:
url = '{}api?x-api={}&method=delete&objectId={}&format=json'.format(self.endpoint, self.key, item_id)
data = self.make_get_request(url)

if not self.key:
raise ValueError('This action requires an API key.')

if data['response']['result'] == 'SUCCESS':
return True
return False

def create_item_relation(self, kulturarvsdata_uri: str, relation: str, target: str, user: str) -> bool:
def create_item_relation(self, kulturarvsdata_uri: str, relation: str, target: str, user: str, comment: str = None) -> bool:
kulturarvsdata_uri = self.soch.formatUri(kulturarvsdata_uri, 'rawurl')
if not kulturarvsdata_uri:
raise ValueError('{} is not an valid Kulturarvsdata URI.'.format(kulturarvsdata_uri))
Expand All @@ -84,7 +85,14 @@ def create_item_relation(self, kulturarvsdata_uri: str, relation: str, target: s
if not self.valid_relation_target(target):
raise ValueError('{} is not a valid target.'.format(target))

if not self.key:
raise ValueError('This action requires an API key.')

url = '{}api?x-api={}&method=insert&scope=relationAll&objectUri={}&user={}&relationType={}&relatedTo={}&format=json'.format(self.endpoint, self.key, kulturarvsdata_uri, user, relation, target)

if comment:
url = '{}&comment={}'.format(url, comment)

data = self.make_get_request(url)

if data['response']['result'] == 'SUCCESS':
Expand All @@ -106,7 +114,22 @@ def valid_relation_target(self, target: str) -> bool:
if target.startswith('http://www.wikidata.org/entity/Q'):
return True

if target.startswith('http://data.europeana.eu/item/'):
if target.startswith('http://commons.wikimedia.org/entity/M'):
return True

if target.startswith('http://kulturnav.org/'):
return True

if target.startswith('http://viaf.org/viaf/'):
return True

if target.startswith('http://vocab.getty.edu/ulan/'):
return True

if target.startswith('http://iconclass.org/'):
return True

if target.startswith('http://data.europeana.eu/'):
return True

if re.match(r'^https:\/\/libris\.kb\.se\/.{14,17}$', target):
Expand All @@ -121,11 +144,11 @@ def make_get_request(self, url: str) -> Dict:
r = requests.get(url, headers = self.headers)

# note UGC always returns 200 codes for now.
if r.status_code is not 200:
raise ValueError('Could not access endpoint.')
if r.status_code is 401:
raise PermissionError('Bad API key.')

data = r.json()
if 'error' in data['response']:
raise ValueError('Bad API key.')
raise Exception('Unknown error: {}'.format(data['response']['error']))

return data

0 comments on commit eb7d3e9

Please sign in to comment.