elasticsearch 错误:没有找到模块,关于其他文件中的函数,在django应用程序上使用eslatic搜索数据库,使用docker-compose进行dockerize

ekqde3dh  于 2023-08-03  发布在  ElasticSearch
关注(0)|答案(2)|浏览(94)

我试图定义一个视图,查看一个患者的所有文本列表,但出现“ModuleNotFoundError:没有名为'fake_date'的模块“
我的脚本populate_index.py工作正常,我确实用它在ElasticSearch数据库中生成了一个文档列表。
但是现在我想在我的django应用程序中添加这个注解。我不明白我在我的视图中导入了NoteDocument。
views.py:

from django.shortcuts import render
from usersapp.models import Patient
from utils.populate_index import NoteDocument

def patient_texts(request, patient_id):
    # Récupérer le patient en fonction de l'ID fourni
    try:
        patient = Patient.objects.get(id=patient_id)
    except Patient.DoesNotExist:
        return render(request, 'error.html', {'message': 'Patient not found'})

    # Récupérer tous les documents de notes liés au patient
    notes = NoteDocument.search().filter('term', patient_username=patient.username).execute()

    context = {
        'patient': patient,
        'notes': notes
    }
    return render(request, 'patient_texts.html', context)

字符串
populate_index.py:

import os
import sys
import django

# Ajoutez le chemin du répertoire racine de votre projet Django
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'emotiontracking.settings')
django.setup()
from usersapp.models import CustomUser

import csv
from django.utils import timezone
import random
from elasticsearch_dsl import connections, Document, Text, Date, Keyword, Integer
import pickle
from fake_date import generate_fake_date_between
import psycopg2

# Établir une connexion à Elasticsearch
connections.create_connection(hosts=['192.168.1.31:9200'])

# Charger le pipeline pré-entraîné
with open('model/nlp-pipeline-linearsvc.pkl', 'rb') as f:
    pipeline = pickle.load(f)

# Définir le document Elasticsearch pour les notes
class NoteDocument(Document):
    text = Text()
    emotion = Keyword()
    date = Date()
    patient_username = Keyword()

    class Index:
        name = 'notes'

    def save(self, **kwargs):
        return super(NoteDocument, self).save(**kwargs)

def get_user():
    # Connexion à la base de données PostgreSQL
    conn = psycopg2.connect(
        host='db',
        database='postgres',
        user='postgres',
        password='postgres'
    )
    
    # Création d'un curseur pour exécuter des requêtes
    cursor = conn.cursor()
    
    # Exécution de la requête pour récupérer les IDs des utilisateurs patients
    query = """
        SELECT username FROM usersapp_customuser
        WHERE is_patient = false 
    """
    cursor.execute(query)
    
    # Récupération des usernames des utilisateurs
    user_usernames = [str(row[0]) for row in cursor.fetchall()]
    
    # Fermeture du curseur et de la connexion à la base de données
    cursor.close()
    conn.close()
    
    # Retourne un ID d'utilisateur au hasard parmi ceux récupérés
    if user_usernames:
        return random.choice(user_usernames)
    else:
        return None
    

def populate_index(num_rows):
    with open('data/Emotion_final.csv', 'r') as file:
        reader = csv.DictReader(file)
        rows = list(reader)  # Convertir le lecteur en une liste de lignes

        random_rows = random.sample(rows, num_rows)  # Sélectionner un échantillon aléatoire de lignes

        for row in random_rows:
            text = row['Text']
            emotion = pipeline.predict([text])[0]

            # Récupérer la date d'inscription de l'utilisateur
            user_username = get_user()
            user = CustomUser.objects.get(username=user_username)
            date_of_registration = user.date_of_registration

            # Générer une fausse date entre aujourd'hui et la date d'inscription
            today = timezone.now().date()
            fake_date = generate_fake_date_between(date_of_registration, today)

            note = NoteDocument(text=text, emotion=emotion, date=fake_date, patient_username=user_username)
            note.save()

# Appeler la fonction pour remplir l'index avec un nombre spécifié de lignes aléatoires
num_rows_to_populate = 100 # Choisir le nombre de lignes à l'avance
populate_index(num_rows_to_populate)


fake_date.py

from datetime import datetime, timedelta
from faker import Faker
import random
from django.utils import timezone

def generate_fake_date():
    faker = Faker()
    max_date = datetime.now()
    min_date = max_date - timedelta(days=730)  # 2 ans
    return faker.date_between_dates(min_date, max_date)

def generate_fake_date_between(start_date, end_date):
    delta = end_date - start_date
    random_days = random.randint(0, delta.days)
    fake_datetime = start_date + timedelta(days=random_days)
    return fake_datetime


错误消息:

emotiontracking-web-1            | Traceback (most recent call last):
emotiontracking-web-1            |   File "/code/manage.py", line 22, in <module>
emotiontracking-web-1            |     main()
emotiontracking-web-1            |   File "/code/manage.py", line 18, in main
emotiontracking-web-1            |     execute_from_command_line(sys.argv)
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
emotiontracking-web-1            |     utility.execute()
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute
emotiontracking-web-1            |     self.fetch_command(subcommand).run_from_argv(self.argv)
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv
emotiontracking-web-1            |     self.execute(*args, **cmd_options)
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute
emotiontracking-web-1            |     output = self.handle(*args, **options)
emotiontracking-web-1            |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 106, in wrapper
emotiontracking-web-1            |     res = handle_func(*args, **kwargs)
emotiontracking-web-1            |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 100, in handle
emotiontracking-web-1            |     self.check(databases=[database])
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 485, in check
emotiontracking-web-1            |     all_issues = checks.run_checks(
emotiontracking-web-1            |                  ^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks
emotiontracking-web-1            |     new_errors = check(app_configs=app_configs, databases=databases)
emotiontracking-web-1            |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique
emotiontracking-web-1            |     all_namespaces = _load_all_namespaces(resolver)
emotiontracking-web-1            |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces
emotiontracking-web-1            |     url_patterns = getattr(resolver, "url_patterns", [])
emotiontracking-web-1            |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__
emotiontracking-web-1            |     res = instance.__dict__[self.name] = self.func(instance)
emotiontracking-web-1            |                                          ^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 715, in url_patterns
emotiontracking-web-1            |     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
emotiontracking-web-1            |                        ^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__
emotiontracking-web-1            |     res = instance.__dict__[self.name] = self.func(instance)
emotiontracking-web-1            |                                          ^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 708, in urlconf_module
emotiontracking-web-1            |     return import_module(self.urlconf_name)
emotiontracking-web-1            |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module
emotiontracking-web-1            |     return _bootstrap._gcd_import(name[level:], package, level)
emotiontracking-web-1            |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
emotiontracking-web-1            |   File "<frozen importlib._bootstrap_external>", line 940, in exec_module
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
emotiontracking-web-1            |   File "/code/emotiontracking/urls.py", line 21, in <module>
emotiontracking-web-1            |     path('', include("usersapp.urls")),
emotiontracking-web-1            |              ^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/site-packages/django/urls/conf.py", line 38, in include
emotiontracking-web-1            |     urlconf_module = import_module(urlconf_module)
emotiontracking-web-1            |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module
emotiontracking-web-1            |     return _bootstrap._gcd_import(name[level:], package, level)
emotiontracking-web-1            |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
emotiontracking-web-1            |   File "<frozen importlib._bootstrap_external>", line 940, in exec_module
emotiontracking-web-1            |   File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
emotiontracking-web-1            |   File "/code/usersapp/urls.py", line 4, in <module>
emotiontracking-web-1            |     from usersapp import views
emotiontracking-web-1            |   File "/code/usersapp/views.py", line 144, in <module>
emotiontracking-web-1            |     from utils.populate_index import NoteDocument
emotiontracking-web-1            |   File "/code/utils/populate_index.py", line 17, in <module>
emotiontracking-web-1            |     from fake_date import generate_fake_date_between
emotiontracking-web-1            | ModuleNotFoundError: No module named 'fake_date'
emotiontracking-web-1 exited with code 1


的数据
我确实删除了容器et重新启动它们,但我仍然有这个错误

ccgok5k5

ccgok5k51#

问题是fake_date.py位于utils子目录中,但您没有告诉代码在那里查找。
utils.添加到import语句中。

from utils.fake_date import generate_fake_date_between

字符串

oaxa6hgo

oaxa6hgo2#

尝试使用.fake_date而不是fake_date进行相对导入。只需编辑文件populate_index.py,如下所示:

from .fake_date import generate_fake_date_between

字符串

相关问题