关于python:ValueError:类型名称和字段名称必须是有效的标识符:namedtuple

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

我在flask view函数中有以下内容(我使用的是python 3.6):

1
2
3
4
5
6
7
8
@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'))

我得到:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  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
3\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)元组的列表,它们只希望属性(或单个字符串)不可重复:

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

或:

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

有关如何使用namedtuple的信息,请参阅文档。


也许你可以使用输入模块中的name-duple使用like follow:

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