Django rest框架/simplejson错误__init__()得到一个意外的关键字参数

时间:2021-07-24 06:21:19

I've found this issue with django-rest-framework TypeError at /rest/events/ __init__() got an unexpected keyword argument 'iterable_as_array'

我在/rest/events/ __init__()中发现了这个与django-rest-framework类型错误有关的问题,得到了一个意想不到的关键字参数“iterable_as_array”

error tracelog:

错误tracelog:

Environment:


Request Method: GET
Request URL: http://www.kenyabuzz.com/rest/events/

Django Version: 1.5.5
Python Version: 2.7.9
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'django.contrib.messages',
 'django.contrib.markup',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.redirects',
 'django.contrib.humanize',
 'autocomplete_light',
 'memcache_status',
 'djangorestframework',
 'haystack',
 'lamusoftware.generic',
 'mptt',
 'bootstrapform',
 'sorl.thumbnail',
 'south',
 'oauth2client',
 'articles',
 'banners',
 'common',
 'directory',
 'events',
 'galleries',
 'marketplace',
 'movies',
 'pages',
 'profiles',
 'search',
 'stats',
 'minidetector',
 'mobile',
 'reports',
 'favorites',
 'braces',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook',
 'widget_tweaks',
 'wordofmouth',
 'ckeditor',
 'django_mobile',
 'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
 'minidetector.Middleware',
 'mobileesp.middleware.MobileDetectionMiddleware',
 'kb.middleware.log_ip_middleware.SetRemoteAddrFromForwardedFor',
 'kb.middleware.log_ip_middleware.RedirectMovie')


Traceback:
File "/home/kbuzz/lib/python2.7/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/kbuzz/lib/python2.7/django/utils/decorators.py" in _wrapped_view
  91.                     response = view_func(request, *args, **kwargs)
File "/home/kbuzz/lib/python2.7/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)
File "/home/kbuzz/lib/python2.7/django/views/decorators/csrf.py" in wrapped_view
  77.         return view_func(*args, **kwargs)
File "/home/kbuzz/webapps/django/lib/python2.7/djangorestframework/views.py" in dispatch
  246.         return self.final(request, response, *args, **kwargs)
File "/home/kbuzz/webapps/django/lib/python2.7/djangorestframework/views.py" in final
  199.         return self.render(response)
File "/home/kbuzz/webapps/django/lib/python2.7/djangorestframework/mixins.py" in render
  251.             content = renderer.render(response.cleaned_content, media_type)
File "/home/kbuzz/webapps/django/lib/python2.7/djangorestframework/renderers.py" in render
  325.         content = self._get_content(self.view, self.view.request, obj, media_type)
File "/home/kbuzz/webapps/django/lib/python2.7/djangorestframework/renderers.py" in _get_content
  227.         content = renderers[0](view).render(obj, media_type)
File "/home/kbuzz/webapps/django/lib/python2.7/djangorestframework/renderers.py" in render
  113.         return json.dumps(obj, cls=DateTimeAwareJSONEncoder, indent=indent, sort_keys=sort_keys)
File "/home/kbuzz/lib/python2.7/simplejson/__init__.py" in dumps
  397.         **kw).encode(obj)

Exception Type: TypeError at /rest/events/
Exception Value: __init__() got an unexpected keyword argument 'iterable_as_array'

I checked online for similar issues and found suggestions that the issue would be solved with the latest update. I've upgraded to 3.3.1 but this didn't solve the issue. I checked the source of the error simplejson and there's a report of a similar issue from 10 days ago. This issue started after I started upgrading all the django apps to the latest version.

我在网上查询了类似的问题,发现有建议说这个问题可以通过最新的更新来解决。我已经升级到3.3.1,但这并不能解决问题。我检查了simplejson错误的来源,有一个10天前类似问题的报告。这个问题开始于我将所有django应用程序升级到最新版本之后。

The error log doesn't trace it to the views but the class handling it below might be improved to resolve the issue.

错误日志没有将它跟踪到视图,但是处理它的类可以改进以解决这个问题。

class SearchListModelView(PaginatorMixin, View):
    django_model = None
    #permissions = (IsAuthenticated,)

    def get(self, request, *args, **kwargs):

        sqs = SearchQuerySet()
        filtered = False
        parent = None

        filter_data = dict(request.GET.items())

        # Not able to get named args from kwargs. Empty for some reason.
        # This will have to do for now
        slugs = request.path.strip('/').split('/')
        if len(slugs) == 4:
            dm = slugs[-1]
            # __exact is also returning 'restaurants-bars' for 'restaurants'
            # 'uniquerestaurantsunique' is a workaround for all slug search
            slug = 'unique%sunique' % slugs[-2]
            parent_dm = slugs[-3]

            sqs_parent = SearchQuerySet().filter(django_ct=slug_to_django_model(parent_dm), slug__exact=slug)
            sr_id = None
            for sr in sqs_parent:
                sr_id = sr.pk
            if sr_id:
                if parent_dm == dm:
                    fil= 'parent__exact'
                elif parent_dm == 'venues':
                    fil = 'venue__exact'
                else:
                    fil = parent_dm + '__exact'
                sqs = sqs.filter(**{fil:sr_id})
                filtered = True

        # Filter on django model
        if self.django_model is None:
            self.django_model = self._resource.django_model
        if self.django_model:
            sqs = sqs.filter(django_ct=self.django_model)
            filtered = True

        valid_fields = self._resource.fields

        valid_index_fields = []

        # If no model (free text) use common.category
        if self.django_model:
            search_index = connections['default'].get_unified_index().get_index(get_model(*self.django_model.split('.')))
            valid_index_fields = search_index.fields

        # Check to ensure that each filter key is a valid field in the model

        free_text = False

        for filter_key,value in filter_data.iteritems():
            filter_args = filter_key.split("__")
            if len(filter_args) == 2:
                key, op = filter_args[0], filter_args[1]
            else:
                key, op = filter_key, None
            if key in valid_fields and key in valid_index_fields:
                if op == 'in':
                    value = value.split(',')
                if isinstance(value, list):
                    value_items = []
                    for item in value:
                        value_items.append(convert_string_into_object(item, valid_index_fields[key]))
                    value = value_items
                else:
                    value = convert_string_into_object(value, valid_index_fields[key])
                if filter_key == 'slug__exact':
                    value = 'unique%sunique' % value
                    sqs = sqs.filter(slug__exact=value)
                else:
                    sqs = sqs.filter(**{ filter_key:value })
                filtered = True
            elif key == 'django_ct' and op:
                print key, op, value
                sqs = sqs.filter(django_ct__in=value.split(','))
                filtered = True
            elif key == 'content':
                sqs = sqs.filter(content=AutoQuery(value))
                filtered = True
                free_text = True

        # Do not allow all data to be returned
        if not filtered:
            del sqs
            return []

        if self.django_model == 'movies.show':
            #print 'sqs.all(): ', sqs.all()
            movies = list(set([show.movie for show in sqs.all()]))
            #print 'movies: ', movies
            sqs = SearchQuerySet().filter(django_ct='movies.movie', i__in=movies)

        # For the API sorting is required on some models
        if self._resource and self._resource.sortorder and not free_text:
            sqs = sqs.order_by(*self._resource.sortorder)
        return sqs.all() 

1 个解决方案

#1


1  

Simplejson 3.3.1 was released before the fix was merged. You need to either wait or use the current master branch for simplejson.

Simplejson 3.3.1在合并修复之前发布。您需要等待或使用simplejson的当前主分支。

#1


1  

Simplejson 3.3.1 was released before the fix was merged. You need to either wait or use the current master branch for simplejson.

Simplejson 3.3.1在合并修复之前发布。您需要等待或使用simplejson的当前主分支。