请问为什么下列代码会报错,请修改并优化: @staticmethod def good_actors(): actors_info = {} @films_bp.route('/good_actors', methods=['GET']) def good_actors(): try: result = FilmInfo.good_actors() #直接调用Fileinfo类中构建的静态方法good_actors() logging.info('获得各年份电影数量序列') return jsonify(result) except Exception as e: logging.error('Error occurred while retrieving students from the database. Error message: {}'.format(str(e))) return jsonify({"error": str(e)}) # 查询满足条件的电影信息 films = FilmInfo.query.all() for film in films: actors_str = film.actor.strip("[]") # 去除方括号和单引号 actors = [actor.strip("'") for actor in actors_str.split(",")] # 统计演员参与的电影数量 for actor in actors: info = actors_info.get(actor, {'total_films': 0, 'best_films': 0, 'worst_films': 0, 'average_films': 0}) info['total_films'] += 1 actors_info[actor] = info # 判断电影评分并更新好片、烂片和一般片数量 if film.rate is not None: for actor in actors: info = actors_info.get(actor, {'total_films': 0, 'best_films': 0, 'worst_films': 0, 'average_films': 0}) if film.rate >= 8.5: info['best_films'] += 1 elif film.rate < 6: info['worst_films'] += 1 else: info['average_films'] += 1 actors_info[actor] = info # 计算好片占比并排序 good_actors = sorted(actors_info.items(), key=lambda x: x[1]['best_films'] / x[1]['total_films'], reverse=True)[:10] return good_actors
时间: 2024-02-14 10:06:07 浏览: 74
这段代码会报错的原因是,定义了两个同名的函数good_actors(),一个是FilmInfo类中的静态方法,另一个是films_bp蓝图中的视图函数。这会导致视图函数覆盖了静态方法,导致程序无法正确执行。另外,在视图函数中查询了所有电影信息,这可能会导致性能问题。
可以将FilmInfo类中的静态方法名称修改为其他名称,如get_good_actors()。然后在视图函数中调用该方法,获取演员信息。同时,可以通过在查询时指定只查询演员信息和评分信息来优化查询性能。最终代码如下:
```
@films_bp.route('/good_actors', methods=['GET'])
def get_good_actors():
try:
actors_info = {}
# 查询演员参与的电影数量
films = db.session.query(FilmInfo.actor, FilmInfo.rate).filter(FilmInfo.actor != None).all()
for film in films:
actors_str = film.actor.strip('[]')
# 去除方括号和单引号
actors = [actor.strip("'") for actor in actors_str.split(',')]
# 统计演员参与的电影数量
for actor in actors:
info = actors_info.get(actor, {'total_films': 0, 'best_films': 0, 'worst_films': 0, 'average_films': 0})
info['total_films'] += 1
actors_info[actor] = info
# 判断电影评分并更新好片、烂片和一般片数量
if film.rate is not None:
for actor in actors:
info = actors_info.get(actor, {'total_films': 0, 'best_films': 0, 'worst_films': 0, 'average_films': 0})
if film.rate >= 8.5:
info['best_films'] += 1
elif film.rate < 6:
info['worst_films'] += 1
else:
info['average_films'] += 1
actors_info[actor] = info
# 计算好片占比并排序
good_actors = sorted(actors_info.items(), key=lambda x: x[1]['best_films'] / x[1]['total_films'], reverse=True)[:10]
return jsonify(good_actors)
except Exception as e:
logging.error('Error occurred while retrieving students from the database. Error message: {}'.format(str(e)))
return jsonify({"error": str(e)})
```
注意,在查询演员信息时,使用了filter()方法指定只查询演员不为空的电影信息,并且只查询演员和评分两个字段,以提高查询性能。
阅读全文