在 API 为 运行 in Python 时更新 DataFrame

Updating DataFrame while API is running in Python

所以我正在尝试创建一个 API,它会在请求时不断地从 CSV 和 returns 中读取有关它的信息。到目前为止,我已经创建了一个 flask API 可以正确读取 CSV 文件一次并且 returns。但是,我似乎无法让它不断更新。我的工作代码是这样的。

app = flask.Flask(__name__)
app.config["DEBUG"] = True


dfchat = pd.read_csv(path)
escaper = None

# for now, this is just to make sure the program keeps running even if there is an error
def escape_route():
    global escaper
    while escaper != "Y":
        escaper = str(input("Exit now? Enter \'Y\': \n")).strip()
    os._exit(os.X_OK)
    
def sample_function(dfchat):

    @app.route('/sample_text', methods=['GET'])
    def sample_endpoint():
        # this function filters dfchat and returns whatever

def main():
    global dfchat
    escape_route_thread = threading.Thread(target = escape_route)
    escape_route_thread.start()
    sample_function(dfchat)
    app.run()


main()

我已经尝试创建另一个线程来更新 CSV 文件:

def retrieve_database():
    global dfchat
    while True:
        time.sleep(0.1)
        dfchat = pd.read_csv(path)

连同:

escape_route_thread = threading.Thread(target = retrieve_database)
escape_route_thread.start()

在主函数中。

但是在 API 启动时无法更新 dfchat 数据框。我已经单独测试了线程,它确实更新了 return 更新的数据框。 到目前为止,据我了解,一旦 API 运行,python 代码就无法更改 API 本身。

所以, 有没有办法用 python 更新 运行 API?

我只要求 python,因为我无法手动输入 link(如“/refresh”)来执行此操作。必须由 python.

完成

我是不是漏掉了什么?

非常感谢您的帮助!

编辑:

我还尝试为每个 API 调用更新 csv 文件。但这确实有效:

def sample_function():

    dfchat = pd.read_csv(path)
    @app.route('/sample_text', methods=['GET'])
    def sample_endpoint():
        # this function filters dfchat and returns whatever

所以我意识到解决方案非常简单。一般来说,我是 CS 和 API 的新手,所以我没有意识到 @app.route 在 Flask 中是如何工作的。 @app.route 之外无法更改路由,但更新路由内的变量确实有效。我不小心在 @app.route.

之外不断更新 dfchat
def sample_function():

  # instead of putting dfchat here
  @app.route('/sample_text', methods=['GET'])
  def sample_endpoint():
      dfchat = pd.read_csv(path) # it should go here.
      # this function filters dfchat and returns whatever

谢谢 yco 帮助我实现这一点。

在脚本的根目录定义的代码(在您的示例中是 dfchat 定义)在您启动 flask 服务器时执行一次。

在每次 API 调用此路由时执行 Flask 应用程序路由内的代码(用 @app.route(...) 修饰的函数)。

from flask import Flask

app = Flask(__name__)

path = "path/to/your/csv/file.csv"

@app.route('/sample_text', methods=['GET'])
def sample_endpoint():
  dfchat = pd.read_csv(path)
  # do what you have to do with the DF

另请注意,Flask 会在不停止 API 的情况下处理错误,并且有很好的文档可以帮助您:https://flask.palletsprojects.com/en/2.0.x/quickstart/#a-minimal-application