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

标签 python ajax flask

我有这个 Flask View,它接受 POST 和 GET 请求 目标是对来自 POST 请求的数据做一些事情 并将其用于 GET 请求

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

我能够通过以下方式将数据传递给 AJAX 调用 声明全局变量 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')

最佳答案

是的,有:)

看看下面的代码:

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!"})

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

然后你只需要添加 @LocalStore under 你的应用程序的 @app.route(...) 因为商店需要用方法路由...

我认为这是一种非常优雅的方式,可以为您节省 5 个不同方法的 5 个全局变量的定义

关于python - 在 Flask 中使用 POST 请求的输出执行 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64374107/

相关文章:

python - 有向图 - SQLAlchemy ORM

python - 无法在 opencv (Python 2.7) 中播放视频

javascript - jQuery remove 仅适用于 AJAX 调用后的第二次点击

python - wtforms SelectField 始终返回 None

python - 在 AWS 中存储从 Pandas 导出的 Excel 文件

python - 如何在 Jupyter Notebook 中绘图后抑制文本输出

javascript - jQuery 查找返回空字符串

ajax - CORS 和 Chrome

python - 具有 "dynamic"模式的 flask-sqlalchemy 跨数据库

单变量的 Python 箱线图