ValueError: Type names and field names must be valid identifiers: namedtuple

ValueError: Type names and field names must be valid identifiers: namedtuple

我在 flask 视图函数中有以下内容(_我正在使用 python 3.6):

@login_required
@main.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
    if request.method =='POST':
        dash_data = namedtuple('dash_data',[('posting', str), ('folder', str)])
        print(request.form.get('posting'))

        posted_data= dash_data(posting=request.form.get('posting'),folder=request.form.get('folder'))

我得到:

  Traceback (most recent call last):
  File "...\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "...\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "...\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "...\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "...\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "...\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "...\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "...\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "...\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "...\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "E:\ENVS\r3\posterizer2\app\main\views.py", line 387, in cl_dash
    Cl_dash_data = namedtuple('cl_dash_data',[('posting', str), ('folder', str)])
  File "...\lib\collections\__init__.py", line 403, in namedtuple
    'identifiers: %r' % name)
ValueError: Type names and field names must be valid identifiers: "('posting', <class 'str'>)"

我做错了什么?

namedtuple 对象不接受 (attribute, type) 元组列表,它们只需要一个可迭代的属性(或单个字符串):

namedtuple('dash_data', ('posting', 'folder'))

或:

namedtuple('dash_data', 'posting folder')

参考the documentation如何使用namedtuple

也许你可以使用 NamedTuple from typing 模块 使用如下:

from typing import NamedTuple
dash_data = NamedTuple('dash_data',[('posting', str), ('folder', str)])