14

Djangoアプリケーションでこのエラーが発生しますが、発生するのは1日1回以下であり、デバッグが非常に困難です。

Environment:

Request Method: POST

Django Version: 1.3.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'fimedlabs',
 'data',
 'djcelery']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'fimedlabs.auth.userMiddleWare')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  178.                 response = middleware_method(request, response)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/sessions/middleware.py" in process_response
  36.                 request.session.save()
File "/usr/local/lib/python2.6/dist-packages/django/contrib/sessions/backends/db.py" in save
  57.             session_data = self.encode(self._get_session(no_load=must_create)),
File "/usr/local/lib/python2.6/dist-packages/django/contrib/sessions/backends/base.py" in encode
  93.         pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)

Exception Type: PicklingError at /
Exception Value: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

私はこれに対する答えを試しました:

どのオブジェクト属性のピクルスが失敗したかを知る方法は?

実際のエラーに自分自身を追加して、Djangoエラーの内容が役に立たないかどうかを確認します。

このエラーの問題を引き起こしているオブジェクトをどこに印刷して、Djangoエラーページに表示されるようにできますか?

ありがとう!〜マット

編集:私がキャッシュに保存している唯一のオブジェクトは、コードを持つユーザーオブジェクトです:

class user(object):
username = str()
userid = uuid.UUID(int=0)

client = models.Client()
clientid = uuid.UUID(int=0)
clientname = ''

data = models.User()
accesslevel = models.AccessLevel()

active = False
client_active = False
isFimed = False
isFimedAdmin = False
isClientAdmin = False
isFimedManager = False
mysettingsform = None
viewingas = False

menu = []

_exists = False
_authenticated = False

def __str__(self):
    return str(self.__dict__.copy())

def __getstate__(self):
    return self.__dict__.copy()

def __setstate__(self, dict):
    self.__dict__ = dict

def __init__(self, username=None):
    if username:
        self.initialize(username)

def initialize(self, username):
    self.username = username
    model = models.User.objects.filter(username=username).all()
    if len(model) == 1:
        model = model[0]
        self.data = model
        self._exists = True
        self.userid = self.data.id
        self.active = self.data.active
        self.isFimed = self.data.isFimed()
        self.isFimedAdmin = self.data.isFimedAdmin()
        self.isClientAdmin = self.data.isClientAdmin()
        self.isFimedManager = self.data.isFimedManager()
        self.mysettingsform = UserFormSelf(initial={"id":model.id, "username":model.username, "name":model.name, "email":model.email, "phone":model.phone})

        self.accesslevel = models.AccessLevel.objects.filter(id=self.data.accesslevel_id)[:1][0].level
        cli = self.data.client
        self.client = cli
        self.clientid = cli.id
        self.clientname = cli.name
        if cli.active:
            self.client_active = True

        model.lastlogin = datetime.datetime.now()
        model.save()

        self.menu = getMenu(self.data)
    else:
        self._exists = False

def authenticate(self, password):
    self._authenticated = False
    if (self.active == False or self.client_active == False):
        return False
    if self._exists:
        import hashlib
        hash = hashlib.md5('%s%s' % (str(password), self.data.pwsalt)).hexdigest()
        if hash == self.data.pwhash:
            self._authenticated = True
            return True
    return False

def updateUser(self):
    self.initialize(models.User.objects.filter(id=self.userid).get().username)

def mkContext(self):
    c = Context()
    c['menu'] = self.menu
    c['user'] = self
    c['language'] = language
    c['colors'] = colors
    c["isFimed"] = self.isFimed
    c["isFimedAdmin"] = self.isFimedAdmin
    c["isClientAdmin"] = self.isClientAdmin
    c["isFimedManager"] = self.isFimedManager
    c["mysettingsform"] = self.mysettingsform
    return c

編集:Werkzeug後のWSGIファイル:

import django.core.handlers.wsgi
djangoapplication = django.core.handlers.wsgi.WSGIHandler()
def application(environ, start_response):
    if 'SCRIPT_NAME' in environ:
        del environ['SCRIPT_NAME']
    return djangoapplication(environ, start_response)
# The following lines enable the werkzeug debugger
import django.views.debug
def null_technical_500_response(request, exc_type, exc_value, tb):
    raise exc_type, exc_value, tb
django.views.debug.technical_500_response = null_technical_500_response
from werkzeug.debug import DebuggedApplication
application = DebuggedApplication(application, evalex=True)
4

4 に答える 4

10

私の場合(Django関連ではありません)、この例外はmultiprocessing.Pool.map、ラムダがターゲット関数として渡されたときにスローされました。名前付き関数を作成し、必要なコンテキストデータ構造をinitargs(クロージャーではなく)パラメーターを介して渡すことで、問題が解決しました。

要約すると、例外をトリガーした悪いユースケースは次のとおりです。

import multiprocessing as mp
context = some_object
pool = mp.Pool()
worker_func = lambda x: work(x, context)
results = pool.map(worker_func, data_list)
于 2013-11-21T19:43:49.687 に答える
6

このエラーの問題を引き起こしているオブジェクトをどこに印刷して、Djangoエラーページに表示されるようにできますか?

簡単な答え-再コンパイルせずcPickleに、あなたはできません。

長い答え:これは例外を発生させるコードの一部です:

root $ grep -Hra "attribute lookup" /usr/lib64/ 2>/dev/null | grep -a failed
/usr/lib64/python2.7/lib-dynload/cPickle.so:H�H���P0H�5zM H�=1��M��H��H�ZM �����H�=�1�H���M��H��H��M �����H�4M H�5~H���H���������H�M H�5tH���H���������H��L H�5�H���qH�����d���H�M H�5NH���SH�����F���H�dM H�5bH���5H�����(���H�=X1��O��H�HC H�5I H�=U1�A��H��L �vH��H��I�������H���RK��H�=.H����J��H�5$H��H��H�D$�G��H�D$H��tH�H��H��H��gH�DL�ttH�qH�5nH�=kH��1��XK��H�5bH��H��I����F��H�5\L��H���F��H��tH�EH��H��H�E��M�������I�$H��H��I�$�t���I�DL���P0�d���f�H�EH��H��H�E�F���H�H���P0�7���@H�|$H��P0�����H�H���P0�����H�H���P0�k�����UH��SH�H�H: H���tH�;: H���H�H���u�H�[��H��M��H��attribute deletion is not supportedunsupported pickle protocol: %dargument must have 'read' and 'readline' attributespickle protocol %d asked for; the highest available protocol is %dargument must have 'write' attributeGlobal and instance pickles are not supported.Attempt to getvalue() a non-list-based picklerUnexpected data in internal listBINSTRING pickle has negative byte countno int where int expected in memoCan't pickle %s: import of module %s failedCan't pickle %s: attribute lookup %s.%s failedCan't pickle %s: it's not the same object as %s.%sCan't pickle %s: extension code %s isn't an integerCan't pickle %s: extension code %ld is out of rangecould not convert string to intLONG pickle has negative byte countcould not convert string to floatBINUNICODE pickle has negative byte countunregistered extension code %ld_inverted_registry[%ld] isn't a 2-tuple of stringsA load persistent id instruction was encountered,

よく見ると、「

Can't pickle %s: attribute lookup %s.%s failed

static int save_global(Picklerobject *self, PyObject *args, PyObject *name)これで、Pythonソースをダウンロードすると、次の関数で例外を発生させる原因となるコードを簡単に見つけることができます./Modules/cPickle.c

klass = PyObject_GetAttrString(mod, name_str);
if (klass == NULL) {
    cPickle_ErrFormat(PicklingError,
                      "Can't pickle %s: attribute lookup %s.%s "
                      "failed",
                      "OSS", args, module, global_name);
    goto finally;
}

したがって、このエラーをデバッグするためにできる最善の方法は、文字列を別の方法でフォーマットすることです(おそらくPyString_AS_STRING((PyStringObject *)name)、Pythonの変更バージョンを提供、再コンパイル、およびインストールします。

ええ、私はそれがあまりにも悪いことを知っています。私自身も同じ問題を抱えていました。

于 2012-08-09T12:54:41.937 に答える
1

のようなものを使用してdjango-extensions、werkzeugデバッガーをインストールします。各スタックフレームを操作できるようになります。その時点で、セッションdictのすべてのキーと値を選択してみることができます。

于 2012-06-06T17:57:04.700 に答える
1

ユーザーオブジェクトを保存している場合は、このバグの影響を受ける可能性があります: https ://code.djangoproject.com/ticket/16563

とは言うものの、最善の策は、/ usr / local / lib / python2.6 / dist-packages / django / contrib / sessions / backends/base.pyの93行目にあるDjangoソースコードを変更することです。発生します。

session_dictをログに記録するだけです。ほとんどの場合、何が悪いのかは本当に明白です。(実際、トレースバックにローカル変数が表示されている場合は、すでにこれがあります)

于 2012-11-09T07:59:22.480 に答える