mongodb.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """MongoDB_ is a document based database program that handles JSON like data.
  3. Before configuring the ``mongodb`` engine, you must install the dependency
  4. pymongo_.
  5. Configuration
  6. =============
  7. In order to query MongoDB_, you have to select a ``database`` and a
  8. ``collection``. Furthermore, you have to select a ``key`` that is going to be
  9. searched. MongoDB_ also supports the option ``exact_match_only``, so configure
  10. it as you wish.
  11. Example
  12. =======
  13. Below is an example configuration for using a MongoDB collection:
  14. .. code:: yaml
  15. # MongoDB engine
  16. # Required dependency: pymongo
  17. - name: mymongo
  18. engine: mongodb
  19. shortcut: md
  20. exact_match_only: false
  21. host: '127.0.0.1'
  22. port: 27017
  23. enable_http: true
  24. results_per_page: 20
  25. database: 'business'
  26. collection: 'reviews' # name of the db collection
  27. key: 'name' # key in the collection to search for
  28. Implementations
  29. ===============
  30. """
  31. import re
  32. try:
  33. from pymongo import MongoClient # type: ignore
  34. except ImportError:
  35. # import error is ignored because the admin has to install pymongo manually
  36. # to use the engine
  37. pass
  38. engine_type = 'offline'
  39. # mongodb connection variables
  40. host = '127.0.0.1'
  41. port = 27017
  42. username = ''
  43. password = ''
  44. database = None
  45. collection = None
  46. key = None
  47. # engine specific variables
  48. paging = True
  49. results_per_page = 20
  50. exact_match_only = False
  51. result_template = 'key-value.html'
  52. _client = None
  53. def init(_):
  54. connect()
  55. def connect():
  56. global _client # pylint: disable=global-statement
  57. kwargs = {'port': port}
  58. if username:
  59. kwargs['username'] = username
  60. if password:
  61. kwargs['password'] = password
  62. _client = MongoClient(host, **kwargs)[database][collection]
  63. def search(query, params):
  64. results = []
  65. if exact_match_only:
  66. q = {'$eq': query}
  67. else:
  68. _re = re.compile('.*{0}.*'.format(re.escape(query)), re.I | re.M)
  69. q = {'$regex': _re}
  70. query = _client.find({key: q}).skip((params['pageno'] - 1) * results_per_page).limit(results_per_page)
  71. results.append({'number_of_results': query.count()})
  72. for r in query:
  73. del r['_id']
  74. r = {str(k): str(v) for k, v in r.items()}
  75. r['template'] = result_template
  76. results.append(r)
  77. return results