Django使用密码身份验证设置elasticsearch客户端

时间:2020-04-09 12:06:13

标签: django elasticsearch

我的Django应用程序使用elasticsearch索引多个资源。 现在我想用密码保护我的elasticsearch实例,如果我使用“ curl -u”左右的话,它可以正常工作。无论如何,从elasticsearch_dsl文档中找到https://elasticsearch-dsl.readthedocs.io/en/latest/configuration.html,我不明白我需要做些什么来设置使用密码进行身份验证的elasticsearch,并且我必须将该代码放在哪里?!是smb。也许能够通过向我展示他的配置的一些摘要?

我当前的状态如下:

settingy.py

ELASTICSEARCH_DSL = {
    'default': {
        'hosts': env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT'),
    },
}

ELASTICSEARCH_DSL_SIGNAL_PROCESSOR = 'django_elasticsearch_dsl.signals.RealTimeSignalProcessor'

documents.py

from django_elasticsearch_dsl import Document, Index, fields
from elasticsearch_dsl import analyzer
from App.models import Post


# elasticsearch index
posts = Index('posts')

html_strip = analyzer(
    'html_strip',
    tokenizer="standard",
    filter=["lowercase", "stop", "snowball"],
    char_filter=["html_strip"]
)


@posts.document
class PostDocument(Document):

... more index stuff

根据文档,我必须手动设置一个默认的客户端连接,在此我还可以传递密码和用户名进行身份验证,这对我来说暂时在settings.py上似乎是不可能的。

亲切的问候

1 个答案:

答案 0 :(得分:1)

您可以通过 elasticsearch URL 作为

from urllib.parse import quote_plus as urlquote

elk_base_url = 'elasticsearch://{user_name}:{password}@{host_ip}:{host_port}'
elastic_search_url = elk_base_url.format(user_name='my_username',
                                         password=urlquote('mysecret_password'),
                                         # password may contain special characters
                                         host_ip='my-elastic-host-ip',
                                         host_port=9200)
ELASTICSEARCH_DSL = {
    'default': {
        'hosts': [elastic_search_url]
    },
}

此解决方案已在以下情况下经过测试

  1. Django == 3.0.4
  2. django-elasticsearch-dsl == 7.1.1
  3. logstash == kibana == elasticsearch == 7.6.0

如果您遇到 AuthenticationException(401, '') 例外情况,则意味着您提供的 错误凭据 。请检查 elastic_search_url 的值,并确保值正确。