Background Worker with Flask

The downside of your approach is that there are many ways it could fail especially around stopping and restarting your flask application. You will have to deal with graceful shutdown to give your worker a chance to finish its current task. Sometime your worker won’t stop on time and might linger while you start another … Read more

Dynamic choices WTForms Flask SelectField

The main idea here is to assign the choices list to the field after instantiation. To do so you need to use argument coerce=int. The coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode(). Correct FormModel: class AddName(FlaskForm): name =StringField(‘Device name’, validators=[InputRequired(),Length(min=4, max=30)]) groupID = … Read more

Delete an uploaded file after downloading it from Flask

There are several ways to do this. send_file and then immediately delete (Linux only) Flask has an after_this_request decorator which could work for this use case: @app.route(‘/files/<filename>/download’) def download_file(filename): file_path = derive_filepath_from_filename(filename) file_handle = open(file_path, ‘r’) @after_this_request def remove_file(response): try: os.remove(file_path) file_handle.close() except Exception as error: app.logger.error(“Error removing or closing downloaded file handle”, error) return … Read more

Passing variables from Flask to JavaScript

The mobiusklein answers is pretty good, but there is “hack” you should consider. Define your Javascript method to receive params and send data as params to your function. main.py @app.route(“https://stackoverflow.com/”) def hello(): data = {‘username’: ‘Pang’, ‘site’: ‘stackoverflow.com’} return render_template(‘settings.html’, data=data) app.js function myFunc(vars) { return vars } settings.html <html> <head> <script type=”text/javascript” {{ url_for(‘static’, … Read more

python flask display image on a html page [duplicate]

I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template. In application.py: from flask import Flask, render_template import os PEOPLE_FOLDER = os.path.join(‘static’, ‘people_photo’) app = Flask(__name__) app.config[‘UPLOAD_FOLDER’] = PEOPLE_FOLDER @app.route(“https://stackoverflow.com/”) @app.route(‘/index’) def … Read more

Form is never valid with WTForms

Flask-WTF adds a CSRF protection field. If it’s not present, the CSRF validation will fail, and the form will be invalid. Use form.hidden_tag() to include any hidden fields in your form (including the CSRF field). <form method=”post”> {{ form.hidden_tag() }} … In general, if a form is not validating, you should check form.errors after calling … Read more