You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行含数组的Python代码时出现SyntaxError,求排查解决建议

SyntaxError: invalid syntax when defining playlists list in Flask app

Problem Description

I'm getting a syntax error when running my Python Flask code:

File "/home/ofw/playlister/app.py", line 7
playlists = [
^
SyntaxError: invalid syntax

Here's my app.py code:

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
playlists = [
    {
        'title': 'Cat Videos',
        'description': 'Cats acting weird'
    },
    {
        'title': '80\'s Music',
        'description': 'Don\'t stop believing!'
    }
]
@app.route('/)
def playlists_index():
    """Show all playlists."""
    return render_template('playlists_index.html', playlists=playlists)

I suspect the issue is related to the playlists array. Could you give me some solutions? Thanks in advance.


Solution

Hey there, let's fix this up—there are two key issues causing your syntax error and potential future problems:

  1. Misplaced route decorator
    The @app.route('/') decorator is sitting right above your playlists variable, but decorators in Python are designed to modify functions, not variables. This is the direct cause of the SyntaxError on line 7. You need to move this decorator to sit directly above your playlists_index function, where it belongs.

  2. Unclosed quote in the route definition
    Your second @app.route('/') has a missing closing single quote—it's written as @app.route('/) instead of @app.route('/'). This would throw another syntax error once you fix the first issue, so we'll tackle that too.

Here's the corrected code:

from flask import Flask, render_template
app = Flask(__name__)

# Define your playlists variable here, no decorator needed above it
playlists = [
    {
        'title': 'Cat Videos',
        'description': 'Cats acting weird'
    },
    {
        'title': '80\'s Music',
        'description': 'Don\'t stop believing!'
    }
]

@app.route('/')  # Decorator now correctly targets the function below
def playlists_index():
    """Show all playlists."""
    return render_template('playlists_index.html', playlists=playlists)

To break it down:

  • Decorators like @app.route need to be immediately followed by a function definition—they tell Flask which function should handle requests to that URL path. Putting one above a variable assignment confuses Python's parser, hence the error you saw.
  • Fixing the unclosed quote ensures Flask can properly register the root endpoint without additional syntax issues.

Give this corrected code a run, and your SyntaxError should be resolved. Your playlists will be properly passed to the template when you visit the root URL!

内容的提问来源于stack exchange,提问作者learning_code1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:57:52