Flask:用POST方法存储值,用GET方法检索

2024-10-04 05:24:22 发布

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

我已经用烧瓶工作了很久了。你知道吗

我有一个输出,只是一个不断增加或减少的数字,我想用flask POST方法捕获它,并立即检索。你知道吗

我创建了一个应用程序,用于使用相同的上下文检索GET方法中的最新文章:

cumulative = ['x']
@app.route('/xxx', methods=['GET', 'POST'])
def refresh():
    aexample = request.get_json()
    cumulative.append(aexample)
    return str(cumulative[1]['thing2'])

它可以工作,但如果刷新页面,有时会在日志中出现此错误:

TypeError: 'NoneType' object is not subscriptable

在此行中:

cumulative.append(aexample)

我试过使用:

cumulative[0] = aexample

但这不起作用,它说的价值是“无”。这就是为什么我让它增量(只是为了测试的目的)。你知道吗

所有这些都让我觉得,将最新的POST值存储在列表中并不是明智的做法。你知道吗

我一直在考虑使用某种缓存,发布的值每分钟都在变化,我只想检索最新发布的值。我对永久存储这些值不感兴趣。你知道吗

有什么好办法吗?你知道吗


Tags: 方法app应用程序flaskget烧瓶文章数字
2条回答

可能是由于GET请求中缺少请求json而导致错误(即cumulative[1]None,因此无法获取['thing2'])。你知道吗

要在请求之间持久化,并且相信您的数据大小不会太大,您可以将其存储在^{}。你知道吗

否则,您可能需要查看一些更具可伸缩性的内容,如Redis

好的,首先感谢@新西兰迪伦因为我在请求中指出了我的错误。你知道吗

最后我实现了我想要的,我为两个请求创建了条件,这是flask上的代码:

# 'Some Kind of Real Time Stuff'
cumulative = ['x']
@app.route('/xxx', methods=['GET', 'POST'])
def refresh():
    aexample = request.get_json()
    if flask.request.method == 'POST':
        cumulative[0] = str(aexample)
        return 'data received'
    if flask.request.method == 'GET':
        return str(cumulative[0])

[ Using CURL to send data ] Now, sending data to the method:

curl -XPOST -H "Content-Type: application/json" http://someProject/xxx -d '{"thing2":"sdpofkdsofk"}'

[ Apache - Log ]The POST were received successfully:

myapacheserver:80 76.5.153.20 - - [23/Jul/2019:11:02:40 -0400] "POST /xxx HTTP/1.1" 200 182 "-" "curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3"

[ Apache - Log ] GET works! presenting the latest value:

myapacheserver:80 76.220.156.100 - - [23/Jul/2019:11:03:52 -0400] "GET /xxx HTTP/1.1" 200 327 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"

这将显示在http://myapacheserver/xxx页上:

{'thing2': 'sdpofkdsofk'}

是的,我将dict存储为一个字符串,但它是有效的,稍后我将处理数据类型。你知道吗

相关问题 更多 >