mongodb.py 2.3 KB

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