5

I have the following in a flask view function (_I'm using 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'))

I'm getting:

  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'>)"

What am I doing wrong?

davidism
  • 121,510
  • 29
  • 395
  • 339
user1592380
  • 34,265
  • 92
  • 284
  • 515

2 Answers2

7

namedtuple objects don't accept a list of (attribute, type) tuples, they just expect an iterable of attributes (or a single string):

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

Or:

namedtuple('dash_data', 'posting folder')

Refer to the documentation for how to use namedtuple.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • I was looking at https://stackoverflow.com/questions/34269772/type-hints-in-namedtuple . As I reread it , I guess that is for type hinting. – user1592380 Mar 09 '18 at 20:55
  • This is an incorrect answer: see the next answer below. In a nutshell the OP is using the `typing` version that _does_ take a _list_ of `(name,type)` tuples – WestCoastProjects Jun 19 '19 at 20:30
4

maybe you can use NamedTuple from typing module using like follow:

from typing import NamedTuple
dash_data = NamedTuple('dash_data',[('posting', str), ('folder', str)])
新华浦
  • 41
  • 2