(Django)AttributError:' Connection#39;对象没有属性n#39; _connection__connection N#39;

时间:2014-05-12 10:15:24

标签: python django exception attributes

我尝试了几天才能理解这个错误:

AttibutError:'Connection'对象没有属性'_Connection__connection'

这是追溯

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 115, in get_response
      response = callback(request, *callback_args, **callback_kwargs)
    File "/***/****/web/gestion/views.py", line 33, in index
      context_instance=RequestContext(request))
    File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py", line 29, in render_to_response
      return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 177, in render_to_string
      return t.render(context_instance)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 140, in render
      return self._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 134, in _render
      return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 830, in render
      bit = self.render_node(node, context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 844, in render_node
      return node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 124, in render
      return compiled_parent._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 134, in _render
      return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 830, in render
      bit = self.render_node(node, context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 844, in render_node
      return node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 34, in render
      output = self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 830, in render
      bit = self.render_node(node, context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 844, in render_node
      return node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 63, in render
      result = block.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 830, in render
      bit = self.render_node(node, context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 844, in render_node
      return node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 156, in render
      return self.render_template(self.template, context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 138, in render_template
      output = template.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 140, in render
      return self._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 134, in _render
      return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 830, in render
      bit = self.render_node(node, context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 844, in render_node
      return node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 148, in render
      values = list(values)
    File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 3052, in __iter__
      row = self.fetchone()
    File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 3251, in fetchone
      self.cursor, self.context)
    File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1820, in _handle_dbapi_exception
      self.dialect.is_disconnect(e, self.__connection, cursor)
  AttributeError: 'Connection' object has no attribute '_Connection__connection'

view.py

def index(request):
    """ Give principal information for an admin
    """
    # Get all machines
    liste_mac = Database().list_company_machines(1)

    # Get all users
    list_users = Database().list_company_users(1)

    return render_to_response("gestion/index.html",
                          {"nom_ent": "test", "machines": liste_mac, "users": list_users},
                          context_instance=RequestContext(request))

模板

{% extends "base.html" %}
{% block content %}
<div class="center">
    <p style="margin-bottom: 10px;"><img src="{{ STATIC_URL }}graphic/intrinsec.png" /></p>
    <div class="tab-content">
        <h5> {{nom_ent}} </h5>
    </div>

    <div class="tab-content">
        <div class="tab-pane fade in active" id="Users">
            {% include "gestion/user/index.html" %} <- here i use the list_user var
        </div>
        <div class="tab-pane fade" id="Groups">
            {% include "gestion/group/index.html" %}
        </div>
        <div class="tab-pane fade" id="Templates">
            {% include "gestion/machine/index.html" %} <- here i use the list_mac var
        </div>
    </div>
</div>
{% endblock %}

settings.py

import os

DEBUG = True
# TEMPLATE_DEBUG = DEBUG

os.chdir("/cuckoo/web")

# Cuckoo path.
CUCKOO_PATH = os.path.join(os.getcwd(), "..")

# Database settings. We don't need it.
DATABASES = {}

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# Disabling time zone support and using local time for web interface and storage.
# See: https://docs.djangoproject.com/en/1.5/ref/settings/#time-zone
USE_TZ = False
TIME_ZONE = None

...

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(os.getcwd(), 'static'),
)

CUCKOO_FILE_UPLOAD_TEMP_DIR = (
    os.path.join(os.getcwd(), 'tmp_uploads'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    #'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Cuckoo headers.
    "web.headers.CuckooHeaders",
)

FILE_UPLOAD_HANDLERS = (
    'web.upload.CuckooTemporaryFileUploadHandler',
)

ROOT_URLCONF = 'web.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'web.wsgi.application'

TEMPLATE_DIRS = (
    "templates"
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    #'django.contrib.sites',
    #'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    #'debug_toolbar',
    'gestion',
    'authentication'
)

LOGIN_REDIRECT_URL = "/"

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

# Hack to import local settings.
try:
    LOCAL_SETTINGS
except NameError:
    try:
        from local_settings import *
    except ImportError:
        pass

使用debug pdb工具测试时,两个函数(list_company_machines,list_company_users)都有效。但当我一步一步地在视图的最后一条指令上设置断点时,它会向我发送错误:/

Django告诉我错误是从view.py返回索引,但我不明白为什么?

此外,我没有在traceback中修改文件中的任何内容(base.py,...)!

感谢您的建议。

EvrardD

###########

编辑:

借口我忘了给出在DB中获取数据的2个函数:

def list_company_machines(self, id_company=1):
    """Lists virtual machines.
    :param id_company:
    :return: list of virtual machines
    """
    #pdb.set_trace()
    engine = self.engine.connect()
    machines = engine.execute(text("SELECT m.* FROM machines m, machines_companies x WHERE m.id = x.machines_id AND x.companies_id = {}".format(id_company)))
    engine.close()
    return machines

def list_company_users(self, id_company=1):
    """List all info about every user in a specifique company
    :param id_company: id of the company
    """
    engine = self.engine.connect()
    user = engine.execute(text("SELECT * FROM users WHERE company_id == {}".format(id_company)))
    engine.close()
    return user

0 个答案:

没有答案