Categories
Python Answers

How to create multiple forms in a single page using Python Flask and WTForms?

Sometimes, we want to create multiple forms in a single page using Python Flask and WTForms.

In this article, we’ll look at how to create multiple forms in a single page using Python Flask and WTForms.

How to create multiple forms in a single page using Python Flask and WTForms?

To create multiple forms in a single page using Python Flask and WTForms, we can create form classes and then use them in our views.

For instance, we write

class Form1(Form):
    name = StringField('name')
    submit1 = SubmitField('submit')

class Form2(Form):
    name = StringField('name')
    submit2 = SubmitField('submit')

to create 2 form classes.

Then in our view file, we write

form1 = Form1()
form2 = Form2()

# ...

def view():
    if form1.submit1.data and form1.validate(): 
        # ...
    if form2.submit2.data and form2.validate():
        # ...

to create the form instances.

And then we get the data from each form from the submit field for each form.

And we call validate to validate each form’s values.

Conclusion

To create multiple forms in a single page using Python Flask and WTForms, we can create form classes and then use them in our views.

Categories
Python Answers

How to create dynamic URLs in Python Flask with url_for()?

Sometimes, we want to create dynamic URLs in Python Flask with url_for().

In this article, we’ll look at how to create dynamic URLs in Python Flask with url_for().

How to create dynamic URLs in Python Flask with url_for()?

To create dynamic URLs in Python Flask with url_for(), we can call url_for with the name of the view function and the URL parameter values.

For instance, if we have

@app.route('/<variable>/add', methods=['GET', 'POST'])
def add(variable):
  # ...

@app.route('/<variable>/remove', methods=['GET', 'POST'])
def remove(variable):
  # ...

to add 2 view functions.

Then we can create URLs for the view functions with

url_for('add', variable=foo)
url_for('remove', variable=foo)

We call url_for with the view function name and the variable URL parameter value to return the URLs for the routes.

Conclusion

To create dynamic URLs in Python Flask with url_for(), we can call url_for with the name of the view function and the URL parameter values.

Categories
Python Answers

How to implement server push in Python Flask framework?

Sometimes, we want to implement server push in Python Flask framework.

In this article, we’ll look at how to implement server push in Python Flask framework.

How to implement server push in Python Flask framework?

To implement server push in Python Flask framework, we can send server-sent events.

To do this, we can use the flask-sse package.

We install it by running

pip install flask-sse

Then we use it by writing

from flask import Flask
from flask_sse import sse

app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.register_blueprint(sse, url_prefix='/stream')

@app.route('/send')
def send_message():
    sse.publish({"message": "Hello!"}, type='greeting')
    return "Message sent!"

to call sse.publish with a dict with the content to send.

The dict will be sent as JSON to the client.

And then in the client, we writer

const source = new EventSource("{{ url_for('sse.stream') }}");
source.addEventListener('greeting', (event) =>{
    const data = JSON.parse(event.data);
    // ...
}, false);

to create a new EventSource object.

And then we call addEventListener with 'greeting' to listen for greeting type messages.

In the callback, we get the data sent from the server from event.data as a JSON string.

Conclusion

To implement server push in Python Flask framework, we can send server-sent events.

To do this, we can use the flask-sse package.

Categories
Python Answers

How to redirect to a URL in Python Flask?

Sometimes, we want to redirect to a URL in Python Flask.

In this article, we’ll look at how to redirect to a URL in Python Flask.

How to redirect to a URL in Python Flask?

To redirect to a URL in Python Flask, we can call the redirect function

For instance, we write

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

to call redirect in our hello view function with the URL and the response code for the redirect.

Conclusion

To redirect to a URL in Python Flask, we can call the redirect function

Categories
Python Answers

How to return image stored in database with Python Flask?

Sometimes, we want to return image stored in database with Python Flask.

In this article, we’ll look at how to return image stored in database with Python Flask.

How to return image stored in database with Python Flask?

To return image stored in database with Python Flask, we can use the make_response function.

For instance, we write

@app.route('/images/<int:pid>.jpg')
def get_image(pid):
    image_binary = read_image(pid)
    response = make_response(image_binary)
    response.headers.set('Content-Type', 'image/jpeg')
    response.headers.set(
        'Content-Disposition', 'attachment', filename='%s.jpg' % pid)
    return response

to call make_response on the image_binary image.

Then we call response.headers.set to add a new response headers for the file.

And then we return the response with the image as the body and the headers.

Conclusion

To return image stored in database with Python Flask, we can use the make_response function.