所以我正在嘗試創建一個不斷從 CSV 讀取并在請求時回傳有關它的資訊的 API。到目前為止,我已經創建了一個燒瓶 API,它讀取 CSV 檔案一次并正確回傳。但是,我似乎無法讓它不斷更新。我的作業代碼是這樣的。
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 資料框。我已經單獨測驗了執行緒,它確實更新并回傳了更新的資料框。據我目前了解,一旦 API 運行,python 代碼就無法更改 API 本身。
那么, 有沒有辦法只用 python 更新正在運行的 API?
I'm asking for just python because I will not be able to manually enter a link like "/refresh" to do this. It has to be done by python.
Am I missing something?
Thank you very much for helping!
Edit:
I also tried to update the csv file for every API call. But that does but work either:
def sample_function():
dfchat = pd.read_csv(path)
@app.route('/sample_text', methods=['GET'])
def sample_endpoint():
# this function filters dfchat and returns whatever
uj5u.com熱心網友回復:
在腳本根目錄定義的代碼(如dfchat您的示例中的定義)在您啟動燒瓶服務器時執行一次。
Flask 應用程式路由(用 裝飾的函式@app.route(...))內的代碼在對該路由的每次 API 呼叫時執行。
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
uj5u.com熱心網友回復:
所以我意識到解決方案非常簡單。我一般是 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幫助我意識到這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444731.html
標籤:python html multithreading dataframe api
