Categories
Python Answers

How to enable CORS in Python Flask?

Sometimes, we want to enable CORS in Python Flask.

In this article, we’ll look at how to enable CORS in Python Flask.

How to enable CORS in Python Flask?

To enable CORS in Python Flask, we can use the CORS class.

For instance, w write

from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello"

to create an app with CORS enabled.

We enable CORS on the app with cors = CORS(app).

And then we enable CORS our view function with the @cross_origin() decorator.

Conclusion

To enable CORS in Python Flask, we can use the CORS class.

Categories
Python Answers

How to fix Bad Request Error when submitting form in a Python Flask app?

Sometimes, we want to fix Bad Request Error when submitting form in a Python Flask app.

In this article, we’ll look at how to fix Bad Request Error when submitting form in a Python Flask app.

How to fix Bad Request Error when submitting form in a Python Flask app?

To fix Bad Request Error when submitting form in a Python Flask app, we use the request.form dict to get the form values with keys that match one of the name attribute of an input element.

For instance, we write

<input name="question_field" placeholder="question one">

to add an input with name set to question_field.

Then we write

request.form['question_field']

in our view function to get the value of the input with name attribute set to question_field.

Conclusion

To fix Bad Request Error when submitting form in a Python Flask app, we use the request.form dict to get the form values with keys that match one of the name attribute of an input element.

Categories
Python Answers

How to add a background thread to Python Flask?

Sometimes, we want to add a background thread to Python Flask.

In this article, we’ll look at how to add a background thread to Python Flask.

How to add a background thread to Python Flask?

To add a background thread to Python Flask, we can use the flask_apscheduler package.

To install it, we run

pip install Flask-APScheduler

Then we run it by writing

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
    JOBS = [
        {
            'id': 'job1',
            'func': 'jobs:job1',
            'args': (1, 2),
            'trigger': 'interval',
            'seconds': 10
        }
    ]

    SCHEDULER_API_ENABLED = True


def job1(a, b):
    print(str(a), str(b))

if __name__ == '__main__':
    app = Flask(__name__)
    app.config.from_object(Config())

    scheduler = APScheduler()
    scheduler.init_app(app)
    scheduler.start()

    app.run()

to call app.config.from_object to add the job config in the Config instance.

Next, we create the scheduler APScheduler instance.

And then we call init_app with app to add the scheduler to the app.

Then we call start to start the scheduler.

Categories
Python Answers

How to read file data without saving it in Python Flask?

Sometimes, we want to read file data without saving it in Python Flask.

In this article, we’ll look at how to read file data without saving it in Python Flask.

How to read file data without saving it in Python Flask?

To read file data without saving it in Python Flask, we can access the file from request.files.

For instance, we write

@app.route('/upload/', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files["file"]                    
        if file:
            df = pd.read_excel(files_excel["file"])

to get the file with request.files["file"]

Then we can do what we want with the file without saving it.

Conclusion

To read file data without saving it in Python Flask, we can access the file from request.files.

Categories
Python Answers

How to serve multiple clients using just Python Flask app.run() as standalone?

Sometimes, we want to serve multiple clients using just Python Flask app.run() as standalone.

In this article, we’ll look at how to serve multiple clients using just Python Flask app.run() as standalone.

How to serve multiple clients using just Python Flask app.run() as standalone?

To serve multiple clients using just Python Flask app.run() as standalone, to set the threaded argument to False.

For instance, we write

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to call app.run with threaded set to False and `proceses set to 3 to spawn 3 processes.

Conclusion

To serve multiple clients using just Python Flask app.run() as standalone, to set the threaded argument to False.