使用Flask中POST请求的输出执行GET请求

2024-05-14 22:25:17 发布

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

我有一个Flask视图,它可以发布帖子并获取请求 目标是处理POST请求中的数据 并将其用于GET请求

例如,这个AJAX GET请求
$.getJSON({url: '/uploadajax'}).done(result =>console.log(result)); 等待从POST请求返回已处理的数据

我能够通过 声明全局变量result,并在函数中对其进行更改 并将其用作GET请求的返回值

这里的问题:有没有更干净的方法来完成这项任务


result = 0

# ------------upload-file-----------------------------------------#
@flask_class.route('/uploadajax', methods=['POST', 'GET'])
def receave_file():
    if request.method == 'POST':
        uploaded_file = request.files['file']
        # filename = secure_filename(uploaded_file.filename)
        if uploaded_file.filename != "":
            filename = secure_filename(uploaded_file.filename)

            file_ext = os.path.splitext(filename)[1]  # was macht das ?

            if file_ext not in Config.ALLOWED_EXTENSIONS:
                abort(400)
            # file kann auch net gespeichert werden
            uploaded_file.save(os.path.join(flask_class.instance_path, 'uploads', filename))

            # ------------------------------------- #
            df = pd.read_excel(uploaded_file)
            columns = df.columns.to_list()
            global result
            result = json.dumps(columns)

            # return result
            print("shoud return somehting")
           # ---------------------------------------- #
            return '', 204
        # ---------------------------------------- #

   

      
        else:
            return "false" 

    else:
        # GET REQUEST
        if len(result) > 1:
            return result
        else:
            return '', 404
        # return render_template('index.html')


Tags: columns数据pathflaskgetreturnifresult
1条回答
网友
1楼 · 发布于 2024-05-14 22:25:17

是的,有:)

请查看以下代码:

class LocalStore:
    def __call__(self, f: callable):
        f.__globals__[self.__class__.__name__] = self
        return f


#       upload-file                    -#
@flask_class.route('/uploadajax', methods=['POST', 'GET'])
@LocalStore()  # creates store for this unique method only
def receave_file():
    if request.method == 'POST':
        LocalStore.post_headers= request.headers
        LocalStore.post_body = request.body
        LocalStore.post_json = request.get_json()
        LocalStore.post_params = request.params
        LocalStore.answer_to_everything = 42

        print("POST request stored.")
        return jsonify({"response": "Thanks for your POST!"})
    else:
        try:
            print("This is a GET request.")
            print("POST headers were:", LocalStore.post_headers)
            print("POST params were :", LocalStore.post_params)
            print("POST body was    :", LocalStore.post_body)
            print("The answer is    :", LocalStore.answer_to_everything)
            return jsonify({"postHeadersWere": LocalStore.post_headers})
        except AttributeError:
            return jsonify({"response":"You have to make a POST first!"})

我创建了一个特殊的类,它将其引用“注入”到方法的__globals__字典中。如果在方法中键入类名,则它将是对象引用,而不是类引用。请注意这一点

然后,您只需要在应用程序的@LocalStore下面添加@app.route(...),因为存储需要使用以下方法进行路由

我认为这是一种非常优雅的方法,它可以为5种不同的方法保存5个全局变量的定义

相关问题 更多 >

    热门问题