@films_bp.route('/avg_rating_num_by_avg_rates', methods=['GET']) def avg_rating_num_by_avg_rates(): #返回按年统计的每年电影的平均得分,,返回的json数据格式如下所示 try: conn = pymysql.Connection( host='localhost', port=3306, user='root', passwd='21591314cxk' ) cur = conn.cursor() cur.execute('select rate,rating_num from movie.movieinfo where rating_num > 500') dic = cur.fetchall() conn.commit() cur.close() return jsonify(dict(dic)) except Exception as e: logging.error('Error occurred while retrieving students from the database. Error message: {}'.format(str(e))) return jsonify({"error": str(e)})这段代码只返回一个评分结果对应的数据,一旦查找到一个评分就不会继续查找同样评分对应的数据,而我想获取所有数据,请改正并优化代码。
时间: 2024-01-29 16:02:13 浏览: 173
可以将查询结果按照评分进行分组,然后再遍历每个分组获取对应的评分和评分数量,最后组成字典返回即可。以下是修改后的代码示例:
```
@films_bp.route('/avg_rating_num_by_avg_rates', methods=['GET'])
def avg_rating_num_by_avg_rates():
try:
conn = pymysql.Connection(
host='localhost',
port=3306,
user='root',
passwd='21591314cxk'
)
cur = conn.cursor()
cur.execute('SELECT rate, COUNT(*) as rating_num FROM movie.movieinfo WHERE rating_num > 500 GROUP BY rate')
rows = cur.fetchall()
conn.commit()
cur.close()
result = {}
for row in rows:
result[row[0]] = row[1]
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)})
```
这样修改后,查询结果会按照评分进行分组,返回的字典中每个键值对对应一个评分和该评分对应的数量。
阅读全文