Brody Young
Brody Young

Reputation: 23

Flask development server taking extremely long time to start or restart?

Edit: It is directly to do with the "sheet = client.open("Raspi_data")" line. Printed debug after every line at the start. It was not doing this before so I have no clue why it would be doing it now. This is the only line it sticks on. Also, I think some of the original code was lost at some point so if something is broken that may be why

I am running python3 to run a Flask server to essentially moniter some data through html. It is nowhere near finished, however when I reopened the project file to kep working it suddenly takes extremely long (approximitlely 4.5 minutes) to start up. It does start up for the most part, sometimes being slightly slow or just sticking to a blank page with the title "Loading...". This is the python app that is running. It is being started with "Flask run --debug" though starting it via the python script takes just as long. (ps. I know the way it handles downloads is terrible, I need to revise it later.)

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)

(some of the gspread may be commented out to debug, and the restart will not work because it is running on windows until it eventually gets deployed)

I think it may be something with the gspread or oath2client modules, upon commenting them out it does seem to be faster, but I am not too sure about that.

Upvotes: 2

Views: 50

Answers (1)

htrehrthtr
htrehrthtr

Reputation: 98

I think the issue is with the following code segemnet

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")

The best I think to do is, try to create a context manager (https://flask.palletsprojects.com/en/stable/appcontext/) and it will allow the application to not have to initiate everything all over again everytime there is a change in the application.

Hope this helps :)

Upvotes: 0

Related Questions