标签归档:uwsgi

uWSGI的意义是什么?

问题:uWSGI的意义是什么?

我正在研究WSGI规范,并试图弄清楚像uWSGI这样的服务器是如何适应图片的。我了解WSGI规范的重点是将Web服务器(如nginx)与Web应用程序(如您使用Flask编写的东西)分开。我不明白uWSGI是做什么的。为什么Nginx无法直接调用我的Flask应用程序?Flask不能直接对它说WSGI吗?uWSGI为什么需要介入它们之间?

WSGI规范有两个方面:服务器和Web应用程序。uWSGI在哪一边?

I’m looking at the WSGI specification and I’m trying to figure out how servers like uWSGI fit into the picture. I understand the point of the WSGI spec is to separate web servers like nginx from web applications like something you’d write using Flask. What I don’t understand is what uWSGI is for. Why can’t nginx directly call my Flask application? Can’t flask speak WSGI directly to it? Why does uWSGI need to get in between them?

There are two sides in the WSGI spec: the server and the web app. Which side is uWSGI on?


回答 0

好吧,我想我现在明白了。

为什么Nginx无法直接调用我的Flask应用程序?

因为nginx不支持WSGI规范。从技术上讲,nginx可以根据需要实施该WSGI规范,而实际上并没有。

在这种情况下,我们需要一个能够实现规范的Web服务器,这正是该uWSGI服务器的作用。

请注意,这uWSGI是一个完整的http服务器,可以单独运行并且运行良好。我已经以这种身份多次使用它,并且效果很好。如果您需要超高的静态内容吞吐量,则可以选择停留nginxuWSGI服务器前。完成后,他们将通过称为的低级协议进行通信uwsgi

“什么事?!又叫uwsgi ?!” 你问。是的,令人困惑。当您引用时,uWSGI您正在谈论的是http服务器。当您谈论uwsgi(全部小写)时,您所谈论的是是该uWSGI 服务器用来与其他服务器进行通讯二进制协议nginx。他们在这个名字上取了一个坏名字。

对于任何有兴趣的人,我都写了一篇有关它的博客文章,其中包含更多细节,一些历史和一些示例。

Okay, I think I get this now.

Why can’t nginx directly call my Flask application?

Because nginx doesn’t support the WSGI spec. Technically nginx could implement the WSGI spec if they wanted, they just haven’t.

That being the case, we need a web server that does implement the spec, which is what the uWSGI server is for.

Note that uWSGI is a full fledged http server that can and does work well on its own. I’ve used it in this capacity several times and it works great. If you need super high throughput for static content, then you have the option of sticking nginx in front of your uWSGI server. When you do, they will communicate over a low level protocol known as uwsgi.

“What the what?! Another thing called uwsgi?!” you ask. Yeah, it’s confusing. When you reference uWSGI you are talking about an http server. When you talk about uwsgi (all lowercase) you are talking about a binary protocol that the uWSGI server uses to talk to other servers like nginx. They picked a bad name on this one.

For anyone who is interested, I wrote a blog article about it with more specifics, a bit of history, and some examples.


回答 1

在这种情况下,NGINX仅用作反向代理和渲染 静态文件而不动态文件,它接收请求并将它们代理到应用服务器(即UWSGI)。

UWSGI服务器负责使用WSGI接口加载Flask应用程序。实际上,您可以使UWSGI直接侦听来自Internet的请求,并根据需要删除NGINX,尽管它通常在反向代理之后使用。

文档

uWSGI支持几种与Web服务器集成的方法。它也能够自己处理HTTP请求。

简单来说,WSGI只是一个接口规范,它告诉您应该实现哪些方法以在服务器和应用程序之间传递请求和响应。当使用Flask或Django之类的框架时,由框架本身来处理。

换句话说,WSGI本质上是python应用程序(Flask,Django等)和Web服务器(UWSGI,Gunicorn等)之间的契约。好处是您可以轻松更改Web服务器,因为您知道它们符合WSGI规范,而这实际上是目标之一,如PEP-333中所述

Python目前拥有各种各样的Web应用程序框架,如Zope的,堂吉诃德,Webware的,SkunkWeb,PSO和扭曲网站-仅举几个1。对于新的Python用户而言,如此众多的选择可能是一个问题,因为通常来说,他们对Web框架的选择将限制他们对可用Web服务器的选择,反之亦然。

NGINX in this case only works as a reverse proxy and render static files not the dynamic files, it receives the requests and proxies them to the application server, that would be UWSGI.

The UWSGI server is responsible for loading your Flask application using the WSGI interface. You can actually make UWSGI listen directly to requests from the internet and remove NGINX if you like, although it’s mostly used behind a reverse proxy.

From the docs:

uWSGI supports several methods of integrating with web servers. It is also capable of serving HTTP requests by itself.

WSGI is just an interface specification, in simple terms, it tells you what methods should be implemented for passing requests and responses between the server and the application. When using frameworks such as Flask or Django, this is handled by the framework itself.

In other words, WSGI is basically a contract between python applications (Flask, Django, etc) and web servers (UWSGI, Gunicorn, etc). The benefit is that you can change web servers with little effort because you know they comply with the WSGI specification, which is actually one of the goals, as stated in PEP-333.

Python currently boasts a wide variety of web application frameworks, such as Zope, Quixote, Webware, SkunkWeb, PSO, and Twisted Web — to name just a few 1. This wide variety of choices can be a problem for new Python users, because generally speaking, their choice of web framework will limit their choice of usable web servers, and vice versa.


回答 2

传统的Web服务器无法理解或无法运行Python应用程序。这就是WSGI服务器出现的原因。另一方面,Nginx支持反向代理来处理请求并传递Python WSGI服务器的响应。

该链接可能会对您有所帮助:https : //www.fullstackpython.com/wsgi-servers.html

A traditional web server does not understand or have any way to run Python applications. That’s why WSGI server come in. On the other hand Nginx supports reverse proxy to handle requests and pass back responses for Python WSGI servers.

This link might help you: https://www.fullstackpython.com/wsgi-servers.html


回答 3

简而言之,可以想像一下您在Nginx Web服务器上运行CGI或PHP应用程序的情况。您将使用像php-fpm这样的相应处理程序来运行这些文件,因为Web服务器以其本机格式不会呈现这些格式。

In simple terms, just think of an analogy where you are running a CGI or PHP application with Nginx web server. You will use the respective handlers like php-fpm to run these files since the webserver, in its native form doesn’t render these formats.


错误:“字典更新序列元素#0的长度为1;在Django 1.4上需要2

问题:错误:“字典更新序列元素#0的长度为1;在Django 1.4上需要2

我在django 1.4上收到一条错误消息:

字典更新序列元素#0的长度为1;2个为必填项

[编辑]

当我尝试使用模板标签时发生了这种情况:`{%for v in values%}:

dictionary update sequence element #0 has length 1; 2 is required

Request Method:     GET
Request URL:    ...
Django Version:     1.4.5
Exception Type:     ValueError
Exception Value:    

dictionary update sequence element #0 has length 1; 2 is required

Exception Location:     /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21
Python Executable:  /usr/bin/uwsgi-core
Python Version:     2.7.3
Python Path:    

['/var/www/',
 '.',
 '',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/pymodules/python2.7']

Server time:    sam, 13 Jul 2013 16:15:45 +0200
Error during template rendering

In template /var/www/templates/app/index.html, error at line 172
dictionary update sequence element #0 has length 1; 2 is required

172     {% for product in products %}

Traceback Switch to copy-and-paste view

/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response

                            response = callback(request, *callback_args, **callback_kwargs)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view

                    return view_func(request, *args, **kwargs)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner

                return func(request, *args, **kwargs)

    ...
 Local vars
./app/views.py in index

            context_instance=RequestContext(request))

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response

        return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string

            return t.render(context_instance)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                return self._render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

            return compiled_parent._render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

                result = block.nodelist.render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render

            len_values = len(values)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__

            return len(self.object_list)

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__

                    self._result_cache = list(self.iterator())

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator

                        obj = model(*row[index_start:aggregate_start])

    ...
 Local vars
/usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__

                    setattr(self, field.attname, val)

    ...
 Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__

                value = self.field._attribute_class(value, self.field, obj)

    ...
 Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__

            super(HStoreDictionary, self).__init__(value, **params)

    ...
 Local vars

当我尝试访问hstore queryset时,也会发生这种情况:

[编辑]

Traceback (most recent call last):
File "manage.py", line 14, in <module>
    execute_manager(settings)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
    utility.execute()

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)

File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle
    item_id = tmp[0].id,

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__
    return list(qs)[0]

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__
    self._result_cache.extend(self._iter)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator
    obj = model(*row[index_start:aggregate_start])

File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__
    setattr(self, field.attname, val)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__
    value = self.field._attribute_class(value, self.field, obj)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__
    super(HStoreDictionary, self).__init__(value, **params)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

代码是:

tmp = Item.objects.where(HE("kv").contains({'key':value}))

if tmp.count() > 0:

    item_id = tmp[0].id,

我只是在尝试获取价值。我不理解“更新顺序”消息。当我使用游标而不是hstore queryset时,该函数有效。错误也来自模板渲染。我刚刚重新启动uwsgi,一切正常,但是稍后又返回了错误。

[编辑]

有人知道吗?

I have an error message on django 1.4:

dictionary update sequence element #0 has length 1; 2 is required

[EDIT]

It happened when I tried using a template tag like: `{% for v in values %}:

dictionary update sequence element #0 has length 1; 2 is required

Request Method:     GET
Request URL:    ...
Django Version:     1.4.5
Exception Type:     ValueError
Exception Value:    

dictionary update sequence element #0 has length 1; 2 is required

Exception Location:     /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21
Python Executable:  /usr/bin/uwsgi-core
Python Version:     2.7.3
Python Path:    

['/var/www/',
 '.',
 '',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/pymodules/python2.7']

Server time:    sam, 13 Jul 2013 16:15:45 +0200
Error during template rendering

In template /var/www/templates/app/index.html, error at line 172
dictionary update sequence element #0 has length 1; 2 is required

172     {% for product in products %}

Traceback Switch to copy-and-paste view

/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response

                            response = callback(request, *callback_args, **callback_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view

                    return view_func(request, *args, **kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner

                return func(request, *args, **kwargs)

    ...
▶ Local vars
./app/views.py in index

            context_instance=RequestContext(request))

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response

        return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string

            return t.render(context_instance)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                return self._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

            return compiled_parent._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

                result = block.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render

            len_values = len(values)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__

            return len(self.object_list)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__

                    self._result_cache = list(self.iterator())

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator

                        obj = model(*row[index_start:aggregate_start])

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__

                    setattr(self, field.attname, val)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__

                value = self.field._attribute_class(value, self.field, obj)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__

            super(HStoreDictionary, self).__init__(value, **params)

    ...
▶ Local vars

It happens too when I try to access on a hstore queryset:

[edit]

Traceback (most recent call last):
File "manage.py", line 14, in <module>
    execute_manager(settings)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
    utility.execute()

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)

File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle
    item_id = tmp[0].id,

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__
    return list(qs)[0]

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__
    self._result_cache.extend(self._iter)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator
    obj = model(*row[index_start:aggregate_start])

File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__
    setattr(self, field.attname, val)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__
    value = self.field._attribute_class(value, self.field, obj)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__
    super(HStoreDictionary, self).__init__(value, **params)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

the code is:

tmp = Item.objects.where(HE("kv").contains({'key':value}))

if tmp.count() > 0:

    item_id = tmp[0].id,

I’m just trying to access the value. I don’t understand the “update sequence” message. When I use a cursor instead of hstore queryset, the function works. The error comes on template rendering too. I just restarted uwsgi and everything works well, but the error comes back later.

[edit]

Has someone an idea?


回答 0

刚遇到这个问题。我不知道是不是碰到了您的代码,但是对我而言,根本原因是因为我忘记name=url(或path在Django 2.0+中)函数调用的最后一个参数。

例如,以下函数引发问题中的错误:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')

但是这些实际上有效:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')

回溯之所以无济于事,是因为Django在内部希望将给定的位置参数解析为关键字 arguments kwargs,并且由于字符串是可迭代的,因此非典型代码路径开始展开。始终name=在您的网址上使用!

Just ran into this problem. I don’t know if it’s the same thing that hit your code, but for me the root cause was because I forgot to put name= on the last argument of the url (or path in Django 2.0+) function call.

For instance, the following functions throw the error from the question:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')

But these actually work:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')

The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs, and since a string is an iterable, an atypical code path begins to unfold. Always use name= on your urls!


回答 1

我在弄乱字符串和字典时遇到了这个错误。

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required

因此,您实际上要做的是从字符串中获取字典:

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}

或者出于安全考虑,我们可以使用literal_eval

from ast import literal_eval

I got this error when I was messing around with string and dictionary.

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required

So what you actually got to do to get dict from string is:

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}

Or in matter of security we can use literal_eval

from ast import literal_eval

回答 2

尝试执行以下操作时,将引发问题错误:

>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

除非显示完整的追溯代码,否则很难说出代码中的原因。

Error in your question is raised when you try something like following:

>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

It’s hard to tell where is the cause in your code unless you show your code, full traceback.


回答 3

当我忘记将关键字参数名称传递给url()函数时,我遇到了上述问题。

错误代码

 url(r"^testing/$", views.testing, "testing")

代码无错误

url(r"^testing/$", views.testing, name="testing")

所以最后我以这种方式消除了上面的错误。您的情况可能有所不同。因此,请在urls.py中检查您的网址格式。

I faced the above mentioned problem when I forgot to pass a keyword argument name to url() function.

Code with error

 url(r"^testing/$", views.testing, "testing")

Code without error

url(r"^testing/$", views.testing, name="testing")

So finally I removed the above error in this way. It might be something different in your case. So check your url patterns in urls.py.


回答 4

解”

将关键字参数名称(其值作为视图名称)传递给例如homehome-view等。url()的功能。

引发错误»

url(r'^home$', 'common.views.view1', 'home'),

正确”

url(r'^home$', 'common.views.view1', name='home'),

Solution»

Pass a keyword argument name with value as your view name e.g home or home-view etc. to url() function.

Throws Error»

url(r'^home$', 'common.views.view1', 'home'),

Correct»

url(r'^home$', 'common.views.view1', name='home'),


回答 5

这是重现的错误。

>>> d = {}
>>> d.update([(1,)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 
>>> d
{}
>>> 
>>> d.update([(1, 2)])
>>> d
{1: 2}
>>> 
>>> d.update('hello_some_string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>  
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 

如果给定序列,并且任何元素长度为1且需要两个,那么我们将得到这种错误。参见上面的代码。第一次给序列赋予元组,其长度为1,那么我们得到了错误并且字典没有更新。第二次我给内部元组添加了两个元素,字典得到了更新。

Here is the reproduced error.

>>> d = {}
>>> d.update([(1,)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 
>>> d
{}
>>> 
>>> d.update([(1, 2)])
>>> d
{1: 2}
>>> 
>>> d.update('hello_some_string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>  
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 

If you give the sequence and any element length is 1 and required two then we will get this kind of error. See the above code. First time I gave the sequence with tuple and it’s length 1, then we got the error and dictionary is not updated. second time I gave inside tuple with with two elements, dictionary got updated.


回答 6

我遇到了同样的问题,发现这是由于参数错误造成的。在中views.py,我使用了:

return render(request, 'demo.html',{'items', items})    

但我发现了问题:{'items', items}。进行更改以{'items': items}解决问题。

I got the same issue and found that it was due to wrong parameters. In views.py, I used:

return render(request, 'demo.html',{'items', items})    

But I found the issue: {'items', items}. Changing to {'items': items} resolved the issue.


回答 7

就我而言,我get_context_data的观点之一是return render(self.request, 'es_connection_error.html', {'error':error});在try / catch块中返回而不是返回context

In my case, my get_context_data in one of my views was returning return render(self.request, 'es_connection_error.html', {'error':error}); in a try/catch block instead of returning context


回答 8

错误应该与参数有关。请验证params是否为字典对象。如果只是参数列表/元组,则仅使用一个*(*params)而不是两个*(**params)。这会将列表/元组爆炸为适当数量的参数。

或者,如果参数来自代码的其他部分作为JSON文件,请这样做json.loads(params),因为JSON对象有时表现为字符串,因此您需要使用来自字符串的负载(负载)将其作为JSON。

super(HStoreDictionary, self).__init__(value, **params)

希望这可以帮助!

The error should be with the params. Please verify that the params is a dictionary object. If it is just a list/tuple of arguments use only one * (*params) instead of two * (**params). This will explode the list/tuple into the proper amount of arguments.

Or, if the params is coming from some other part of code as a JSON file, please do json.loads(params), because the JSON objects sometimes behave as string and so you need to make it as a JSON using load from string (loads).

super(HStoreDictionary, self).__init__(value, **params)

Hope this helps!


回答 9

尝试使用错误类型的参数调用update方法时遇到此问题。预期的结果是:

{'foo': True}

通过的是:

{'foo': "True"}

确保您检查传递的所有参数均为预期类型。

I encountered this issue when trying to invoke the update method with a parameter of a wrong type. The expected dict was:

{'foo': True}

The one that was passed was:

{'foo': "True"}

make sure you check all the parameters you pass are of the expected type.


回答 10

您发送的参数不正确;它应该是dictionary object

  • 错误: func(a=r)

  • 正确: func(a={'x':y})

You are sending one parameter incorrectly; it should be a dictionary object:

  • Wrong: func(a=r)

  • Correct: func(a={'x':y})


回答 11

我也有类似的问题。解决方法很简单。只是不要尝试在值中输入NULL或None值,否则您可能必须使用类似这样的东西
dic.update([(key,value)])

I too had a similar type of problem . The solution is simple . just dont try to enter NULL or None value in values or u might have to use Something like this
dic.update([(key,value)])