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.

Categories
Python Answers

How to fix TypeError: ObjectId(”) is not JSON serializable with Pymongo?

Sometimes, we want to fix TypeError: ObjectId(”) is not JSON serializable with Pymongo.

In this article, we’ll look at how to fix TypeError: ObjectId(”) is not JSON serializable with Pymongo.

How to fix TypeError: ObjectId(”) is not JSON serializable with Pymongo?

To fix TypeError: ObjectId(”) is not JSON serializable with Pymongo, we can use the json_util module from Pymongo.

For instance, we write

def parse_json(data):
    return json.loads(json_util.dumps(data))

to create the parse_json function.

that calls json_util.dumps on the data returned by Pymongo.

Then we call json.loads to parse the JSON string returned as a dict.

Conclusion

To fix TypeError: ObjectId(”) is not JSON serializable with Pymongo, we can use the json_util module from Pymongo.