demo_online.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Within this module we implement a *demo online engine*. Do not look to
  4. close to the implementation, its just a simple example which queries `The Art
  5. Institute of Chicago <https://www.artic.edu>`_
  6. To get in use of this *demo* engine add the following entry to your engines
  7. list in ``settings.yml``:
  8. .. code:: yaml
  9. - name: my online engine
  10. engine: demo_online
  11. shortcut: demo
  12. disabled: false
  13. """
  14. from json import loads
  15. from urllib.parse import urlencode
  16. engine_type = 'offline'
  17. categories = ['general']
  18. disabled = True
  19. timeout = 2.0
  20. categories = ['images']
  21. paging = True
  22. page_size = 20
  23. search_api = 'https://api.artic.edu/api/v1/artworks/search?'
  24. image_api = 'https://www.artic.edu/iiif/2/'
  25. about = {
  26. "website": 'https://www.artic.edu',
  27. "wikidata_id": 'Q239303',
  28. "official_api_documentation": 'http://api.artic.edu/docs/',
  29. "use_official_api": True,
  30. "require_api_key": False,
  31. "results": 'JSON',
  32. }
  33. # if there is a need for globals, use a leading underline
  34. _my_online_engine = None
  35. def init(engine_settings):
  36. """Initialization of the (online) engine. If no initialization is needed, drop
  37. this init function.
  38. """
  39. global _my_online_engine # pylint: disable=global-statement
  40. _my_online_engine = engine_settings.get('name')
  41. def request(query, params):
  42. """Build up the ``params`` for the online request. In this example we build a
  43. URL to fetch images from `artic.edu <https://artic.edu>`__
  44. """
  45. args = urlencode({
  46. 'q' : query,
  47. 'page' : params['pageno'],
  48. 'fields' : 'id,title,artist_display,medium_display,image_id,date_display,dimensions,artist_titles',
  49. 'limit' : page_size,
  50. })
  51. params['url'] = search_api + args
  52. return params
  53. def response(resp):
  54. """Parse out the result items from the response. In this example we parse the
  55. response from `api.artic.edu <https://artic.edu>`__ and filter out all
  56. images.
  57. """
  58. results = []
  59. json_data = loads(resp.text)
  60. for result in json_data['data']:
  61. if not result['image_id']:
  62. continue
  63. results.append({
  64. 'url': 'https://artic.edu/artworks/%(id)s' % result,
  65. 'title': result['title'] + " (%(date_display)s) // %(artist_display)s" % result,
  66. 'content': result['medium_display'],
  67. 'author': ', '.join(result['artist_titles']),
  68. 'img_src': image_api + '/%(image_id)s/full/843,/0/default.jpg' % result,
  69. 'img_format': result['dimensions'],
  70. 'template': 'images.html'
  71. })
  72. return results