本文介绍了Django + Heroku + MongoDB Atlas(Djongo)= DatabaseError无例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题的单行说明

每当我在heroku上部署的django应用尝试访问MongoDB Atlas集群以提交表单或检查管理员登录名时,都会引发类似附件的错误.

其他详细信息

heroku版本上的错误可重现此处

我认为这与heroku与MongoDB Atlas集群的交互方式有关,因为当我在本地运行构建时,我能够使应用程序成功读取并进行修改,从而在数据库中进行了不同的记录./p>

我已启用了从所有IP地址到我的Atlas群集的流量,从我的Heroku应用程序和配置变量中删除了默认的Heroku PostrgreSQL数据库,并将我自己的数据库IP存储为配置变量.

任何帮助将不胜感激.

Python脚本

 #模型脚本从django.db导入模型RawRequest(models.Model)类:内容= models.CharField(max_length = 130)标识符= models.CharField(max_length = 30) 
 #视图脚本从django.shortcuts导入渲染从django.shortcuts导入重定向从django.urls导入反向从django.http导入HttpResponse从django.views.generic导入CreateView从.models导入RawRequest#在这里创建您的视图.def索引(请求):返回HttpResponse("euler-calc终端GUI")def土豆(要求):返回HttpResponse("potato")类RequestView(CreateView):型号= RawRequest字段=('内容','标识符')def get_success_url(self):返回反向('potato') 
 "eulercalc项目的Django设置.由django-admin startproject使用Django 3.0.5生成.有关此文件的更多信息,请参见https://docs.djangoproject.com/zh-CN/3.0/topics/settings/有关设置及其值的完整列表,请参见https://docs.djangoproject.com/zh-CN/3.0/ref/settings/"导入操作系统导入django_heroku#像这样在项目内部构建路径:os.path.join(BASE_DIR,...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__ file__)))#快速启动开发设置-不适合生产#参见https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/#安全警告:对生产中使用的秘密密钥保密!SECRET_KEY =#一个秘密#安全警告:不要在生产中打开调试的情况下运行!调试=正确ALLOWED_HOSTS = []#应用定义INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','crispy_forms','终端',]CRISPY_TEMPLATE_PACK ='bootstrap4'MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF ='eulercalc.urls'模板= [{'BACKEND':'django.template.backends.django.DjangoTemplates','DIRS':[],'APP_DIRS':是的,'选项': {'context_processors':['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},},]WSGI_APPLICATION ='eulercalc.wsgi.application'#数据库#https://docs.djangoproject.com/zh-CN/3.0/ref/settings/#databases数据库= {'默认': {'ENGINE':'djongo','NAME':'euler-calc','客户': {'主机':str(os.environ.get('MONGODB_URL')),'authMechanism':'SCRAM-SHA-1'}}}#密码验证#https://docs.djangoproject.com/zh-CN/3.0/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [{'NAME':'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},{'NAME':'django.contrib.auth.password_validation.MinimumLengthValidator',},{'NAME':'django.contrib.auth.password_validation.CommonPasswordValidator',},{'NAME':'django.contrib.auth.password_validation.NumericPasswordValidator',},]#国际化#https://docs.djangoproject.com/en/3.0/topics/i18n/LANGUAGE_CODE ='en-us'TIME_ZONE ='UTC'USE_I18N =真USE_L10N =真USE_TZ =真#静态文件(CSS,JavaScript,图像)#https://docs.djangoproject.com/zh/3.0/howto/static-files/STATIC_URL ='/静态/'#激活Django-Heroku.django_heroku.settings(locals()) 

追踪

 环境:请求方法:POST要求网址:https://euler-calc.herokuapp.com/Django版本:2.2.12的Python版本:3.6.10已安装的应用程序:['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','crispy_forms','终端']已安装的中间件:("whitenoise.middleware.WhiteNoiseMiddleware",'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware')追溯:文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在解析中842.返回处理程序(自己,声明)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在_insert中907.query = InsertQuery(self,self.db,self.connection_properties,sm,self._params)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在__init__中339. super().__ init __(* args)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在__init__中61. self.parse()文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在解析中409. self._fill_values(statement)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在_fill_values中367.提高SQLDecodeError上面的异常()是以下异常的直接原因:文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/cursor.py"在执行56. params)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在__init__中769. self._query = self.parse()文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py"在解析中864.从e提高exe上面的异常(失败的SQL:插入"terminal_rawrequest"(内容",标识符")值(%(0)s,%(1)s))参数:['2 + 2','heroku']版本:1.3.2)是以下异常的直接原因:文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py"在_execute中84.返回self.cursor.execute(sql,params)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/cursor.py"在执行59.从e提高db_exe上面的异常()是以下异常的直接原因:文件"/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py"在内部34. response = get_response(请求)文件"/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py"在_get_response中115. response = self.process_exception_by_middleware(e,request)文件"/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py"在_get_response中113. response = wrapd_callback(request,* callback_args,** callback_kwargs)文件"/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py"鉴于71. return self.dispatch(request,* args,** kwargs)文件"/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py"在派遣中97.返回处理程序(请求,* args,** kwargs)文件"/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py"在后172. return super().post(request,* args,** kwargs)文件"/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py"在后142.返回self.form_valid(form)文件"/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py"在form_valid125. self.object = form.save()文件"/app/.heroku/python/lib/python3.6/site-packages/django/forms/models.py"在保存458. self.instance.save()文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py"在保存741.force_update= force_update,update_fields = update_fields)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py"在save_base中779. force_update,使用,update_fields,文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py"在_save_table中870. result = self._do_insert(cls._base_manager,使用,字段,update_pk,原始)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py"在_do_insert中908.using = using,raw = raw)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py"在manager_method中82. return getattr(self.get_queryset(),name)(* args,** kwargs)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py"在_insert中1186. return query.get_compiler(using = using).execute_sql(return_id)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py"在execute_sql中1375. cursor.execute(sql,params)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py"在执行99. return super().execute(sql,params)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py"在执行67. return self._execute_with_wrappers(sql,params,many = False,executor = self._execute)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py"在_execute_with_wrappers中76. return executor(sql,params,many,context)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py"在_execute中84.返回self.cursor.execute(sql,params)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py"在__出口__89.从exc_value提高dj_exc_value.with_traceback(traceback)文件"/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py"在_execute中84.返回self.cursor.execute(sql,params)文件"/app/.heroku/python/lib/python3.6/site-packages/djongo/cursor.py"在执行59.从e提高db_exe异常类型://处的DatabaseError异常值: 
解决方案

事实证明,我忘记将sqlparse添加到我的requirements.txt中,因此heroku无法将Djongo的SQL解析运行到noSQL中.根据此问题,看来0.2.4版是最要使用的稳定版本.

requirements.txt

  django == 2.2.12djongo == 1.3.2gunicorn == 19.9.0django-heroku == 0.3.1django-crispy-forms == 1.9.0dnspython == 1.16.0sqlparse == 0.2.4 

One line description of the issue

Whenever my django app deployed on heroku tries to access my MongoDB Atlas cluster to submit a form or check an admin login it throws something like the attached error.

Extra Details

Error reproducible on heroku build here

I think that this is error has to do with how heroku interacts with my MongoDB Atlas cluster, as I am able to get the app to successfully read and make modifications do different records in my database when I run the build locally.

I have enabled traffic from all IP addresses to my Atlas cluster, removed the default Heroku PostrgreSQL database from my Heroku app and the config variables, and stored my own database IP as a config var.

Any help would be greatly appreciated.

Python script


    # Model Script
    from django.db import models
    
    class RawRequest(models.Model):
        content = models.CharField(max_length=130)
        identifier = models.CharField(max_length=30)



    # Views Script
    from django.shortcuts import render
    from django.shortcuts import redirect
    from django.urls import reverse
    from django.http import HttpResponse
    from django.views.generic import CreateView
    from .models import RawRequest
    
    
    # Create your views here.
    def index(request):
        return HttpResponse("euler-calc terminal GUI")
    
    def potato(request):
        return HttpResponse("potato")
    
    class RequestView(CreateView):
            model = RawRequest
            fields = ('content', 'identifier')
            def get_success_url(self):
                return reverse('potato')


    """
    Django settings for eulercalc project.
    
    Generated by 'django-admin startproject' using Django 3.0.5.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/3.0/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.0/ref/settings/
    """
    
    import os
    import django_heroku
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = # a secret
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'crispy_forms',
        'terminal',
    ]
    
    CRISPY_TEMPLATE_PACK = 'bootstrap4'
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'eulercalc.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'eulercalc.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
    
    DATABASES = {
            'default': {
                'ENGINE': 'djongo',
                'NAME': 'euler-calc',
                'CLIENT': {
                    'host': str(os.environ.get('MONGODB_URL')),
                    'authMechanism': 'SCRAM-SHA-1'
                }
            }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/3.0/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.0/howto/static-files/
    
    STATIC_URL = '/static/'
    
    # Activate Django-Heroku.
    django_heroku.settings(locals())

Traceback

Environment:


Request Method: POST
Request URL: https://euler-calc.herokuapp.com/

Django Version: 2.2.12
Python Version: 3.6.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'terminal']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in parse
  842.                 return handler(self, statement)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in _insert
  907.         query = InsertQuery(self, self.db, self.connection_properties, sm, self._params)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in __init__
  339.         super().__init__(*args)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in __init__
  61.         self.parse()

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in parse
  409.         self._fill_values(statement)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in _fill_values
  367.                 raise SQLDecodeError

The above exception () was the direct cause of the following exception:

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/cursor.py" in execute
  56.                 params)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in __init__
  769.         self._query = self.parse()

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/sql2mongo/query.py" in parse
  864.                 raise exe from e

The above exception (FAILED SQL: INSERT INTO "terminal_rawrequest" ("content", "identifier") VALUES (%(0)s, %(1)s)
Params: ['2 + 2', 'heroku']
Version: 1.3.2) was the direct cause of the following exception:

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/cursor.py" in execute
  59.             raise db_exe from e

The above exception () was the direct cause of the following exception:

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  142.             return self.form_valid(form)

File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py" in form_valid
  125.         self.object = form.save()

File "/app/.heroku/python/lib/python3.6/site-packages/django/forms/models.py" in save
  458.             self.instance.save()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py" in save_base
  779.                 force_update, using, update_fields,

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py" in _do_insert
  908.                                using=using, raw=raw)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1375.                 cursor.execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  99.             return super().execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "/app/.heroku/python/lib/python3.6/site-packages/djongo/cursor.py" in execute
  59.             raise db_exe from e

Exception Type: DatabaseError at /
Exception Value:
解决方案

As it turns out, I forgot to add sqlparse to my requirements.txt and, therefore, heroku was unable to run Djongo's parsing of SQL into noSQL. Based on this issue it seems like version 0.2.4 is the most stable version to use.

requirements.txt

django==2.2.12
djongo==1.3.2
gunicorn==19.9.0
django-heroku==0.3.1
django-crispy-forms==1.9.0
dnspython==1.16.0
sqlparse==0.2.4

这篇关于Django + Heroku + MongoDB Atlas(Djongo)= DatabaseError无例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:22