【问题标题】:perform GET Request with output from POST Request in Flask使用 Flask 中 POST 请求的输出执行 GET 请求
【发布时间】:2020-10-15 14:42:56
【问题描述】:

我有这个接受 POST 和 GET 请求的 Flask View 目标是对来自 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')

【问题讨论】:

    标签: python ajax flask


    【解决方案1】:

    是的,有:)

    看看下面的代码:

    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__ 字典中。如果在方法中键入类名,它将是对象引用,而不是类引用。请注意这一点!

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

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

    【讨论】:

    • 正如我正确理解的那样,您的代码确实将函数返回保存到类属性中。问题是我的 View 函数有两个返回,一个用于 POST,另一个用于 GET 请求,因此如果在 POST 请求之前有 GET 请求,则此方法无法正常工作,除非我将函数拆分为两个函数
    • 不,它不保存返回值,它保存你想要的任何东西。我已经对其进行了一些编辑,因此您可以更好地理解它。您可以将 POST 请求的内容(以及您想要的所有其他内容)保存在本地存储中,并在以后的请求(POST 或 GET 或其他)中访问它们。看看编辑后的版本现在是否适合你:)
    猜你喜欢
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2014-11-26
    • 2020-08-28
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    相关资源
    最近更新 更多