如何每10分钟刷新一次我的csv文件,Flask,Python

whlutmcx  于 5个月前  发布在  Python
关注(0)|答案(2)|浏览(70)

我试图创建一个'简单'的网站,关于投注。

  • 用户输入他想要转换的金额。
  • 该网站为他提供了最好的游戏投注,以及每个投注的赌注。

我正在用Python和Flask实现这个网站。我已经创建了从投注网站中提取数据的代码,并从中创建了一个CSV文件。
我关心的是:我怎么能自动刷新我的csv文件每10分钟,不管是否有一个请求或没有?
这是我创建应用程序的Flask文件:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
import time
import threading

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
   app = Flask(__name__)
   app.config['SECRET_KEY']="abcjzllkk"
   
   
   from .views import views
   from .auth import auth
   
   app.register_blueprint(views, url_prefix="/")
   app.register_blueprint(auth, url_prefix="/")
   
   return app

字符串
谢谢你的回答!

o4tp2gmn

o4tp2gmn1#

最简单的答案是创建一个单独的进程来监控并按设定的时间表抓取CSV,Web服务器应该是一个完全独立的进程,只读取结果CSV文件。
看看Python Celery,APPManager,甚至是一个简单的cron作业来自动化你的scraper。
唯一需要跟踪的是CSV更新时的文件锁定。你可以使用数据库来解决这个问题,因为你已经有了SQLAlchemy,你可以使用SQLite,但老实说,在一个低流量的网站上,你应该不会有任何问题,而且对于某人来说,重新加载或尝试两次比做任何更复杂的事情要快。

1cklez4t

1cklez4t2#

要每隔10分钟自动刷新CSV文件,您可以使用在后台运行的单独线程,独立于用户请求触发刷新过程。您可以通过在Python中添加线程模块来实现这一点。

from flask import Flask
import threading
import time

# Function to refresh the CSV file
def refresh_csv_file():
    while True:
        # Your code to refresh the CSV file goes here
        # This could involve scraping data and updating the CSV file
        print("Refreshing CSV file...")
        
        # Simulating the wait for 10 minutes before the next refresh
        time.sleep(600)  # 600 seconds = 10 minutes

# Function to create the Flask app
def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = "abcjzllkk"

    # Your other configurations, blueprints, etc.
    # ...

    # Start the thread for refreshing the CSV file
    refresh_thread = threading.Thread(target=refresh_csv_file)
    refresh_thread.daemon = True  # Set as daemon so it stops when the main app stops
    refresh_thread.start()

    return app

字符串

相关问题