Coverage for bib/views.py: 17%
47 statements
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-10 15:48 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-10 15:48 +0000
1import requests
2from django.shortcuts import render
3from django.contrib.auth.decorators import login_required
5from .models import Book
7# following line has to match the settings-file you are using
8from django.conf import settings
11def sync_zotero(request):
12 """renders a simple template with a button to trigger sync_zotero_action function"""
13 return render(request, "bib/synczotero.html")
16@login_required
17def sync_zotero_action(request):
18 """fetches the last n items form zoter and syncs it with the bib entries in defc-db"""
19 root = "https://api.zotero.org/users/"
20 params = "{}/collections/{}/items/top?v=3&key={}".format(
21 settings.Z_USER_ID, settings.Z_COLLECTION, settings.Z_API_KEY
22 )
23 url = root + params + "&sort=dateModified&limit=25"
24 books_before = len(Book.objects.all())
25 try:
26 r = requests.get(url)
27 error = "No errors from ZoteroAPI"
28 except: # noqa
29 error = "aa! errors! The API didn´t response with a proper json-file"
31 response = r.json()
32 failed = []
33 saved = []
34 for x in response:
35 try:
36 x["data"]["creators"][0]
37 try:
38 x["data"]["creators"][0]["name"]
39 name = x["data"]["creators"][0]["name"]
40 except: # noqa
41 firstname = x["data"]["creators"][0]["firstName"]
42 lastname = x["data"]["creators"][0]["lastName"]
43 name = "{}, {}".format(lastname, firstname)
44 except: # noqa
45 name = "no name provided"
47 NewBook = Book(
48 zoterokey=x["data"]["key"],
49 item_type=x["data"]["itemType"],
50 author=name,
51 title=x["data"]["title"],
52 short_title=x["data"]["shortTitle"],
53 )
55 try:
56 NewBook.save()
57 saved.append(x["data"])
58 except: # noqa
59 failed(x["data"])
60 books_after = len(Book.objects.all())
61 context = {}
62 context["error"] = error
63 context["saved"] = saved
64 context["failed"] = failed
65 context["books_before"] = [books_before]
66 context["books_after"] = [books_after]
67 return render(request, "bib/synczotero_action.html", context)