Categories
Python Answers

How to fix Python Flask throwing ‘working outside of request context’ when starting sub thread?

Sometimes, we want to fix Python Flask throwing ‘working outside of request context’ when starting sub thread.

In this article, we’ll look at how to fix Python Flask throwing ‘working outside of request context’ when starting sub thread.

How to fix Python Flask throwing ‘working outside of request context’ when starting sub thread?

To fix Python Flask throwing ‘working outside of request context’ when starting sub thread, we can wrap our request code in with app.test_request_context().

For instance, we write

@app.route('/my_endpoint', methods=['POST'])
def my_endpoint_handler():
    def handle_sub_view(req):
        with app.test_request_context():
            from flask import request
            request = req
            # ...
    thread.start_new_thread(handle_sub_view, (request))
    return "hello"

to call app.test_request_context() to get the request context in the handle_sub_view function.

Then we import request inside the block with

from flask import request

And then we do what we want with it.

Then we use

thread.start_new_thread(handle_sub_view, (request))

to start a new thread.

Conclusion

To fix Python Flask throwing ‘working outside of request context’ when starting sub thread, we can wrap our request code in with app.test_request_context().

Categories
Python Answers

How to insert many-to-many data with Python Flask and SQLAlchemy?

Sometimes, we want to insert many-to-many data with Python Flask and SQLAlchemy.

In this article, we’ll look at how to insert many-to-many data with Python Flask and SQLAlchemy.

How to insert many-to-many data with Python Flask and SQLAlchemy?

To insert many-to-many data with Python Flask and SQLAlchemy, we can append the data with append.

For instance, we write

association_table = db.Table('association', db.Model.metadata,
    db.Column('left_id', db.Integer, db.ForeignKey('left.id')),
    db.Column('right_id', db.Integer, db.ForeignKey('right.id'))
)

class Parent(db.Model):
    __tablename__ = 'left'
    id = db.Column(db.Integer, primary_key=True)
    children = db.relationship("Child",
                    secondary=association_table)

class Child(db.Model):
    __tablename__ = 'right'
    id = db.Column(db.Integer, primary_key=True)


p = Parent()
c = Child()
p.children.append(c)
db.session.add(p)
db.session.commit()

to create the association_table that creates a many to many relationship between Parent and Child.

Then we create a Parent and Child instance with

p = Parent()
c = Child()

Next, we create a link between p and c with

p.children.append(c)

Then we commit the operation with

db.session.add(p)
db.session.commit()

Conclusion

To insert many-to-many data with Python Flask and SQLAlchemy, we can append the data with append.

Categories
Python Answers

How to cast Python Flask form value to int?

Sometimes, we want to cast Python Flask form value to int.

In this article, we’ll look at how to cast Python Flask form value to int.

How to cast Python Flask form value to int?

To cast Python Flask form value to int, we can use the int function.

For instance, we write

personId = int(request.form['personId'])

to call int with the input value of the field with name personId into an integer.

We can also call request.form.get with the type argument to do the same thing.

For instance, we write

personId = request.form.get('personId', type=int)

to get the same input field value and convert it to an int by setting the type argument to int.

Conclusion

To cast Python Flask form value to int, we can use the int function.

Categories
Python Answers

How to get the root path of a Python Flask application?

Sometimes, we want to get the root path of a Python Flask application.

In this article, we’ll look at how to get the root path of a Python Flask application.

How to get the root path of a Python Flask application?

To get the root path of a Python Flask application, we can use the app.instance_path property.

For instance, we write

filename = os.path.join(app.instance_path, 'my_folder', 'my_file.txt')

to get the Flask app instance’s folder with app.instance_path.

Conclusion

To get the root path of a Python Flask application, we can use the app.instance_path property.

Categories
Python Answers

How to upload an image in Python Flask?

Sometimes, we want to upload an image in Python Flask.

In this article, we’ll look at how to upload an image in Python Flask.

How to upload an image in Python Flask?

To upload an image in Python Flask, we can get the uploaded file from request.files in our view.

For instance, we write

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

to get the uploaded file from the form data entry with key file with

file = request.files['file']

We check if the file isn’t selected with

if file.filename == ''

Then we save the file to disk with

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

Conclusion

To upload an image in Python Flask, we can get the uploaded file from request.files in our view.