1

我正在尝试创建一个网站,允许用户创建自己的“观看”列表,还可以从创建的列表中随机选择一个标题,使用 API 显示电影的情节、流派和 IMDb 评级。我在尝试运行此函数时遇到了“NoneType”对象不可下标”错误消息,但不知道如何克服它。以下是我的代码的相关部分:

应用程序.py

import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, imdb

app = Flask(__name__)

app.config["TEMPLATES_AUTO_RELOAD"] = True

@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response
    
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

db = SQL("sqlite:///project.db")
    @app.route("/select", methods=["GET", "POST"])
    @login_required
    def select():

        if request.method == "POST":
            """Randomly pick a movie to watch"""
            
            therearemovies = db.execute("SELECT uniqueid FROM movies WHERE id=:id", id=session["user_id"])
            
            if therearemovies:
                chosen = db.execute("SELECT * FROM movies WHERE id=:id ORDER BY RANDOM() LIMIT 1", id=session["user_id"])
                
                for uniqueindex in chosen:
                    suggestion = uniqueindex["title"]
                    
                    **info = imdb(suggestion)
                    plot = info["plot"]
                    genre = info["genre"]
                    rating = info["rating"]**
                    
                    return render_template("select.html", suggestion=suggestion, plot=plot, genre=genre, rating=rating)
            
            else:
                return apology("You don't have any movies in your list")
                
        else:
            return render_template("/")

助手.py:

import os
import requests
import urllib.parse
    
def imdb(title):
try:
    response=requests.get(f"http://www.omdbapi.com/?t={urllib.parse.quote_plus(title)}&apikey=12345678")
    response.raise_for_status()
except requests.RequestException:
    return None

try:
    data = response.json()
    return 
    {
        "plot": data["plot"],
        "genre": data["genre"],
        "rating": data["imdbRating"]
    }
except (KeyError, TypeError, ValueError):
    return None

错误信息:

File "/home/ubuntu/finalproject/helpers.py", line 32, in decorated_function
    return f(*args, **kwargs)
File "/home/ubuntu/finalproject/application.py", line 126, in select
    plot = info["plot"]
TypeError: 'NoneType' object is not subscriptable
4

0 回答 0