You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask开发服务器启动或重启耗时极长问题求助

Flask开发服务器启动或重启耗时极长问题求助

Edit: 经过逐行打印调试后发现,问题直接出在 sheet = client.open("Raspi_data") 这一行。之前完全没有这个问题,现在突然出现卡顿,我完全摸不着头脑。而且我怀疑之前代码可能丢了一部分,说不定是这个原因导致的问题。

我用Python3跑一个Flask服务器,本来是想通过HTML页面监控一些数据的,项目还远没做完,但最近重新打开项目继续开发时,服务器启动突然变得超级慢——大概要4.5分钟才能启动起来。大部分时候能启动成功,但有时候会卡在显示“Loading...”的空白页面,加载速度也很慢。

我是用 Flask run --debug 命令启动的,直接运行Python脚本启动速度也一样慢。(PS:我知道现在处理下载的方式很烂,之后会改的)

from flask import Flask, app, render_template, url_for, send_from_directory, abort, send_file
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import time
import os, shutil
import glob


scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('accCredentials.json', scope) 
client = gspread.authorize(creds)
sheet = client.open("Raspi_data")
worksheet = sheet.worksheet("RawData")

app = Flask(__name__)

@app.route("/")
def main():
    return render_template("Index.html")


i = 0

@app.route('/downloads')
def downloadpage():
    global i
    def cleardir():
        folder = 'C:\\webserver\\downloads'
        for filename in os.listdir(folder):
            file_path = os.path.join(folder, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print('Failed to delete %s. Reason: %s' % (file_path, e))
    if i == 0:
        cleardir()
    data = worksheet.get_all_values()
   
    i += 1
    if i > 24:
        i = 1
        cleardir()
        
    txtfilename = ("txtfile" + str(i))
    path = os.path.join('C:\\webserver\\downloads', txtfilename)
    try:
        txtfile = open(path, "x")
        txtfile.write(str(data))
    except FileExistsError:
        exit
    return render_template('downloadpage.html', INPUT_NAME_1 = txtfilename)



@app.route('/downloads/<name>', methods=['GET', 'POST'])
def download_link(name):
    
    try:
        return send_from_directory(
            app.config['downloads'], path=name, as_attachment=True
        )
    
    except FileNotFoundError:
       abort(404)

@app.route('/restartserver')
def restart():
    #os.system("Flask run --debug")
    app.redirect("/")
    return "Currently Unavailibe"

@app.route("/raw")
def raw():
    return (worksheet.get_all_values())

@app.route('/request/variable/counter')
def getcount():
    return "nothing"

if __name__ == "__main__":
    app.run(debug=True)

(调试的时候我把部分gspread代码注释掉了,另外重启功能目前没法用,因为现在是在Windows上跑,之后部署到其他环境再弄)

我怀疑问题可能出在gspread或者oauth2client模块上——把这些模块相关的代码注释掉之后,服务器启动速度确实变快了,但我也不太确定是不是这个原因导致的卡顿。

备注:内容来源于stack exchange,提问作者Brody Young

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:49:31