在Django 2 python“ urls”文件中循环导入 - python

我已使用Django框架请求登录API,但URL模式的“循环导入”错误导致错误。任何人,请给我们一个关于问题的解决方案。

错误日志写入日志文件:

[Sun Mar 10 20:30:47.407794 2019] [wsgi:error] [pid 21457:tid 139659590813440] Internal Server Error: /ai_chat_bot/users/login
[Sun Mar 10 20:30:47.407814 2019] [wsgi:error] [pid 21457:tid 139659590813440] Traceback (most recent call last):
[Sun Mar 10 20:30:47.407816 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 542, in url_patterns
[Sun Mar 10 20:30:47.407818 2019] [wsgi:error] [pid 21457:tid 139659590813440]     iter(patterns)
[Sun Mar 10 20:30:47.407819 2019] [wsgi:error] [pid 21457:tid 139659590813440] TypeError: 'module' object is not iterable
[Sun Mar 10 20:30:47.407821 2019] [wsgi:error] [pid 21457:tid 139659590813440] 
[Sun Mar 10 20:30:47.407822 2019] [wsgi:error] [pid 21457:tid 139659590813440] During handling of the above exception, another exception occurred:
[Sun Mar 10 20:30:47.407823 2019] [wsgi:error] [pid 21457:tid 139659590813440] 
[Sun Mar 10 20:30:47.407825 2019] [wsgi:error] [pid 21457:tid 139659590813440] Traceback (most recent call last):
[Sun Mar 10 20:30:47.407826 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
[Sun Mar 10 20:30:47.407828 2019] [wsgi:error] [pid 21457:tid 139659590813440]     response = get_response(request)
[Sun Mar 10 20:30:47.407829 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__
[Sun Mar 10 20:30:47.407831 2019] [wsgi:error] [pid 21457:tid 139659590813440]     response = self.process_request(request)
[Sun Mar 10 20:30:47.407832 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/middleware/common.py", line 60, in process_request
[Sun Mar 10 20:30:47.407834 2019] [wsgi:error] [pid 21457:tid 139659590813440]     if self.should_redirect_with_slash(request):
[Sun Mar 10 20:30:47.407835 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/middleware/common.py", line 78, in should_redirect_with_slash
[Sun Mar 10 20:30:47.407837 2019] [wsgi:error] [pid 21457:tid 139659590813440]     not is_valid_path(request.path_info, urlconf) and
[Sun Mar 10 20:30:47.407838 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/base.py", line 157, in is_valid_path
[Sun Mar 10 20:30:47.407840 2019] [wsgi:error] [pid 21457:tid 139659590813440]     resolve(path, urlconf)
[Sun Mar 10 20:30:47.407841 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/base.py", line 24, in resolve
[Sun Mar 10 20:30:47.407843 2019] [wsgi:error] [pid 21457:tid 139659590813440]     return get_resolver(urlconf).resolve(path)
[Sun Mar 10 20:30:47.407844 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 498, in resolve
[Sun Mar 10 20:30:47.407845 2019] [wsgi:error] [pid 21457:tid 139659590813440]     for pattern in self.url_patterns:
[Sun Mar 10 20:30:47.407856 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
[Sun Mar 10 20:30:47.407858 2019] [wsgi:error] [pid 21457:tid 139659590813440]     res = instance.__dict__[self.name] = self.func(instance)
[Sun Mar 10 20:30:47.407859 2019] [wsgi:error] [pid 21457:tid 139659590813440]   File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 549, in url_patterns
[Sun Mar 10 20:30:47.407861 2019] [wsgi:error] [pid 21457:tid 139659590813440]     raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
[Sun Mar 10 20:30:47.407863 2019] [wsgi:error] [pid 21457:tid 139659590813440] django.core.exceptions.ImproperlyConfigured: The included URLconf 'AI_Chatbot_Server.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

“ AI_Chatbot_Server.urls”文件的源代码:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # chatbot app url list
    path('ai_chat_bot/', include("apps.chatbot.urls")),
    path('ai_chat_bot/users/', include("apps.users.urls")),
    path('ai_chat_bot/weather/', include("apps.weather.urls")),
]

更新1:

用户模块网址:

from django.urls import path
from .controller import login_controller

urlpatterns = [
    path('login', login_controller.LoginController.login, name='login'),
]

Chatbot模块网址:

from django.urls import path
from .controller import chatbot_main_controller

urlpatterns = [
    path('get_question/', chatbot_main_controller.ChatBotMainController.get_question, name="get_question"),
]

天气模块网址:

from django.urls import path

from ..weather.controller import weather_info_controller

urlpatterns = [
    path('get_weather_info/', weather_info_controller.WeatherInfoController.get_weather_info, name="get_weather_info"),
]

更新2:

我有用户,聊天机器人和天气模块的共享文件夹结构:

    .
├─.idea
├─AI_Chatbot_Server
│  └─settings
├─apps
│  ├─chatbot
│  │  ├─ai_models
│  │  │  ├─cnn
│  │  │  │  └─temp
│  │  │  ├─estimator
│  │  │  ├─multiclass_cnn
│  │  │  │  └─temp
│  │  │  ├─multiclass_dnn
│  │  │  │  └─temp
│  │  │  └─tensorflow
│  │  ├─ai_model_handler
│  │  ├─common
│  │  ├─config
│  │  ├─controller
│  │  ├─data_processor
│  │  ├─emoji
│  │  │  ├─common
│  │  │  ├─controller
│  │  │  ├─model
│  │  │  ├─repository
│  │  │  ├─serializer
│  │  │  └─service
│  │  ├─evaluation
│  │  │  ├─controller
│  │  │  ├─model
│  │  │  ├─repository
│  │  │  ├─serializer
│  │  │  └─service
│  │  ├─keyword
│  │  │  ├─common
│  │  │  ├─controller
│  │  │  ├─helper
│  │  │  ├─logic
│  │  │  ├─models
│  │  │  ├─repository
│  │  │  ├─serializer
│  │  │  └─service
│  │  ├─models
│  │  ├─repository
│  │  ├─serializer
│  │  ├─service
│  │  ├─utils
│  │  └─validation
│  ├─common
│  ├─users
│  │  ├─common
│  │  ├─controller
│  │  ├─json
│  │  ├─model
│  │  ├─repository
│  │  ├─serializer
│  │  └─service
│  └─weather
│      ├─common
│      ├─controller
│      └─service
├─common
└─static
    ├─data
    └─resources
        └─images
            └─emoji

更新3:
我已经添加了登录控制器,请检查一下。

import logging
from json.decoder import JSONDecodeError

from django.core.exceptions import ObjectDoesNotExist
from django.db.utils import IntegrityError
from django.http import JsonResponse
from rest_framework.decorators import api_view

from ..common.http_code import HttpCode
from ..common.http_message import HttpMessage
from ..common.user_constant import UserConstant
from ..common.utility import Utility
from ..json.response import Response
from ..service.login_service import LoginService
from ..service.login_service import LoginService as loginService


class LoginController:
    logger = logging.getLogger('LoginController')

    @api_view(['POST'])
    def login(request):
        LoginController.logger.info("LoginController.login : START")
        http_status_code = HttpCode.HTTP_ZERO
        post_data = None
        responseData = None
        # check valid json format & added json format exception
        try:
            post_data = Utility.convertRequestBodyToJson(request)
        except JSONDecodeError as ex:
            responseData = Response.preparedResponse(UserConstant.ERROR, str(ex.args), None)
            LoginController.logger.error(UserConstant.JSON_PARSE_ERROR + str(ex))
            http_status_code = HttpCode.HTTP_BAD_REQUEST

        # check request param
        if post_data != None:
            username = post_data['username']
            password = post_data['password']

            # check valid user & password
            try:
                try:
                    valid_user = loginService.check_username(username)
                except ObjectDoesNotExist:
                    valid_user = None

                if valid_user != None:
                    decoded_password = loginService.decoded_password(valid_user)
                    if decoded_password == password:
                        # save user access with token
                        user_access = loginService.set_user_access(valid_user)
                        if user_access != None:
                            loginService.save_user_access(user_access)
                            user_role = loginService.get_user_role(valid_user)
                            login_service = LoginService()
                            # process user_access_history data
                            # login_service.process_user_access_history(valid_user.username, user_access.token)
                            if user_role != None:
                                # prepare the user response object
                                users = {'id': valid_user.id, 'username': valid_user.username,
                                         'token': user_access.token, 'role': user_role.name,
                                         'user_image_url': valid_user.user_image_url}
                                # added common method for prepare response object
                                responseData = Response.preparedResponse(UserConstant.SUCCESS,
                                                                         UserConstant.USER_AUTHENTICATION_SUCCESSFUL,
                                                                         users)
                                http_status_code = HttpCode.HTTP_OK
                    else:
                        responseData = Response.preparedResponse(UserConstant.ERROR,
                                                                 UserConstant.INCORRECT_USER_PASSWORD, None)
                        http_status_code = HttpCode.HTTP_UNAUTHORIZED
                else:
                    responseData = Response.preparedResponse(UserConstant.ERROR, UserConstant.USER_AUTHENTICATION_FAIL,
                                                             None)
                    http_status_code = HttpCode.HTTP_UNAUTHORIZED

            except IntegrityError as ex:
                responseData = Response.preparedResponse(UserConstant.ERROR, str(ex.args), None)
                LoginController.logger.error(UserConstant.DATABASE_ERROR + str(ex))
                http_status_code = HttpCode.HTTP_INTERNAL_SERVER_ERROR
            except Exception as ex:
                LoginController.logger.error(UserConstant.ERROR + str(ex))
                responseData = Response.preparedResponse(UserConstant.ERROR, HttpMessage.INTERNAL_SERVER_ERROR, None)
                http_status_code = HttpCode.HTTP_INTERNAL_SERVER_ERROR
        LoginController.logger.info("LoginController.login : END")
        return JsonResponse(status=http_status_code, data=responseData, safe=False)

参考方案

让我从文档中搜索与circular import相关的问题
https://docs.djangoproject.com/en/2.0/search/?q=circular+import

在下面,我列出了所有内容,并尝试给出循环导入的负责任的事情。
由于您尚未共享完整的代码,因此请仔细阅读文档并重新构建代码
根据文件建议。希望这会有所帮助。

1.设定

https://docs.djangoproject.com/en/2.0/ref/settings/#message-level

  如果您在设置文件中覆盖MESSAGE_LEVEL并依赖于任何内置常量,则必须直接导入常量模块,以避免可能的循环导入,例如:

from django.contrib.messages import constants as message_constants
MESSAGE_LEVEL = message_constants.DEBUG

https://docs.djangoproject.com/en/2.0/ref/settings/#message-tags

  如果您在设置文件中覆盖MESSAGE_TAGS并依赖于任何内置常量,则必须直接导入常量模块,以避免可能的循环导入,例如:

from django.contrib.messages import constants as message_constants
MESSAGE_TAGS = {message_constants.INFO: ''}

2编码风格

https://docs.djangoproject.com/en/2.0/internals/contributing/writing-code/coding-style/#imports

您可以运行“ isort -rc”命令来组织导入。

3翻译

https://docs.djangoproject.com/en/2.0/topics/i18n/translation/#how-django-discovers-language-preference

  如果您定义了自定义LANGUAGES设置(如上一个项目符号中所述),则可以将语言名称标记为翻译字符串-但使用gettext_lazy()而不是gettext()可以避免循环导入。
  
  这是一个示例设置文件:

from django.utils.translation import gettext_lazy as _
LANGUAGES = [
    ('de', _('German')),
    ('en', _('English')),
]

4 Django 1.7发行说明

https://docs.djangoproject.com/en/2.0/releases/1.7/#django-utils-module-loading-import-by-path

5模型领域参考

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'production.Manufacturer',
        on_delete=models.CASCADE,
    )

  在解决两个应用程序之间的循环导入依赖关系时,这种称为惰性关系的引用可能会很有用。

https://docs.djangoproject.com/en/2.0/ref/models/fields/#foreignkey

6.模型信号

https://docs.djangoproject.com/en/2.0/ref/signals/

7.在Django中自定义身份验证

https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project

8.高级测试主题

https://docs.djangoproject.com/en/2.0/topics/testing/advanced/#controlling-creation-order-for-test-databases

9.迁移

https://docs.djangoproject.com/en/2.0/topics/migrations/#squashing-migrations

可能还有其他问题,但可能会有所帮助。

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

TypeError:'str'对象不支持项目分配,带有json文件的python - python

以下是我的代码import json with open('johns.json', 'r') as q: l = q.read() data = json.loads(l) data['john'] = '{}' data['john']['use…