Flask返回重复列表

2024-10-01 15:41:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个flask应用程序后端(get),它返回一个counter元素(list)。当提交几次相同的请愿书时,它会不断添加每个元素

flask get返回应该只返回这个请求的值,而不是那些存储在本地内存中的值。Devicedict1为每个id包含一个fields:destination、产地、票价、忠诚程序等。 Mydict8包含每个deviceid的所有记录,以及出售给这个deviceid的所有票。例如,mydict8[2][12]-包含本次购买的源站,mydict8[3][12]-包含本次购买的另一个源站等。我存储目的地和源站,然后在devicedict3中,返回顶部元组(origin,destination)以及get请求发送的每个deviceid的计数器

from flask import Flask, jsonify, abort
import csv
from flask import make_response
from collections import Counter
devicedict1 = collections.defaultdict(list)
devicedict3= collections.defaultdict(list)
mydict8 = []
with open('Salida1.csv', newline='', mode='r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    # rows1 = list(csv_reader)
    # print(len(rows1))
    line_count = 0
    count = 0
    for row in csv_reader:
        key = row[20]
        devicedict1[key].append(row)
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1

app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'El usuario no ha dado su permiso para dar su ID y por lo tanto esta vacio el ID'}), 404)
@app.errorhandler(401)
def not_found(error):
    return make_response(jsonify({'error': 'El formato del  ID es incorrecto'}), 401)   

@app.route('/todo/api/v1.0/destinos/<string:destino>', methods=['GET'])
def get_destinos(destino):
count2 = len(devicedict1[destino])
            for i in range(0, count2):
                mydict8.append(devicedict1[destino][i])
            for i in range(0, len(mydict8)):
                devicedict3[i].append(mydict8[i][12])
                devicedict3[i].append( mydict8[i][13])
            n = 3
            return (str(Counter(map(tuple, devicedict3.values())).most_common(n)))
if __name__ == '__main__':
    app.run(port=50000, host='0.0.0.0')

所以当我这样做的时候,回报应该是如下的

curl -i http://10.3.4.38:50000/todo/api/v1.0/destinos/4ff70ad8e2e74f49
[(('3001', '1471'), 8), (('1471', '3001'), 5), (('3001', '1966'), 4)]

但是我重复了第二次这个操作,我得到了以下副本:

curl -i http://10.3.4.38:50000/todo/api/v1.0/destinos/4ff70ad8e2e74f49
[(('3001', '1471', '3001', '1471'), 8), (('3001', '1471'), 8), (('1471', '3001', '1471', '3001'), 5)]

我希望每次询问服务器时都能得到相同的答案,而在第二个请愿书中,我丢失了第三个元组值:

('3001', '1966')

Tags: csvimportappflaskgetcounterrorlist
1条回答
网友
1楼 · 发布于 2024-10-01 15:41:00

在函数中,每次都要附加到相同的外部列表:

for i in range(0, count2):
    mydict8.append(devicedict1[destino][i])

for i in range(0, len(mydict8)):
    devicedict3[i].append(mydict8[i][12])
    devicedict3[i].append( mydict8[i][13])

这将修改应用程序的全局状态,这不是您想要的。而是初始化函数内部的列表并删除外部初始化:

def get_destinos(destino):
    # this is the same as the for loop with range above
    mydict8 = devicedict1[destino][0:count2])
    devicedict3 = collections.defaultdict(list)
    ...

我可能会选择比mydict8(这是一个列表…)和devicedict3更好的名称,因此它们代表了它们在函数中的实际含义

相关问题 更多 >

    热门问题