| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 | # SPDX-License-Identifier: AGPL-3.0-or-later# lint: pylint"""MongoDB_ is a document based database program that handles JSON like data.Before configuring the ``mongodb`` engine, you must install the dependencypymongo_.Configuration=============In order to query MongoDB_, you have to select a ``database`` and a``collection``.  Furthermore, you have to select a ``key`` that is going to besearched.  MongoDB_ also supports the option ``exact_match_only``, so configureit as you wish.Example=======Below is an example configuration for using a MongoDB collection:.. code:: yaml  # MongoDB engine  # Required dependency: pymongo  - name: mymongo    engine: mongodb    shortcut: md    exact_match_only: false    host: '127.0.0.1'    port: 27017    enable_http: true    results_per_page: 20    database: 'business'    collection: 'reviews'  # name of the db collection    key: 'name'            # key in the collection to search forImplementations==============="""import retry:    from pymongo import MongoClient  # type: ignoreexcept ImportError:    # import error is ignored because the admin has to install pymongo manually    # to use the engine    passengine_type = 'offline'# mongodb connection variableshost = '127.0.0.1'port = 27017username = ''password = ''database = Nonecollection = Nonekey = None# engine specific variablespaging = Trueresults_per_page = 20exact_match_only = Falseresult_template = 'key-value.html'_client = Nonedef init(_):    connect()def connect():    global _client  # pylint: disable=global-statement    kwargs = {'port': port}    if username:        kwargs['username'] = username    if password:        kwargs['password'] = password    _client = MongoClient(host, **kwargs)[database][collection]def search(query, params):    results = []    if exact_match_only:        q = {'$eq': query}    else:        _re = re.compile('.*{0}.*'.format(re.escape(query)), re.I | re.M)        q = {'$regex': _re}    query = _client.find({key: q}).skip((params['pageno'] - 1) * results_per_page).limit(results_per_page)    results.append({'number_of_results': query.count()})    for r in query:        del r['_id']        r = {str(k): str(v) for k, v in r.items()}        r['template'] = result_template        results.append(r)    return results
 |