mongodb.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """MongoDB engine (Offline)
  4. """
  5. import re
  6. from pymongo import MongoClient # pyright: ignore # pylint: disable=import-error
  7. engine_type = 'offline'
  8. # mongodb connection variables
  9. host = '127.0.0.1'
  10. port = 27017
  11. username = ''
  12. password = ''
  13. database = None
  14. collection = None
  15. key = None
  16. # engine specific variables
  17. paging = True
  18. results_per_page = 20
  19. exact_match_only = False
  20. result_template = 'key-value.html'
  21. _client = None
  22. def init(_):
  23. connect()
  24. def connect():
  25. global _client # pylint: disable=global-statement
  26. kwargs = {'port': port}
  27. if username:
  28. kwargs['username'] = username
  29. if password:
  30. kwargs['password'] = password
  31. _client = MongoClient(host, **kwargs)[database][collection]
  32. def search(query, params):
  33. results = []
  34. if exact_match_only:
  35. q = {'$eq': query}
  36. else:
  37. _re = re.compile('.*{0}.*'.format(re.escape(query)), re.I | re.M)
  38. q = {'$regex': _re}
  39. query = _client.find({key: q}).skip((params['pageno'] - 1) * results_per_page).limit(results_per_page)
  40. results.append({'number_of_results': query.count()})
  41. for r in query:
  42. del r['_id']
  43. r = {str(k): str(v) for k, v in r.items()}
  44. r['template'] = result_template
  45. results.append(r)
  46. return results