Categories
Python Answers

How to iterate through a list of dictionaries in Jinja template with Python Flask?

Sometimes, we want to iterate through a list of dictionaries in Jinja template with Python Flask.

In this article, we’ll look at how to iterate through a list of dictionaries in Jinja template with Python Flask.

How to iterate through a list of dictionaries in Jinja template with Python Flask?

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop.

For instance, we write

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

to create the parent_list list of dicts.

Then we write

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

in our Jinja2 template to render the parent_list items in a for loop.

And in the for loop, we add another for loop to render the key and value from dict_item which has the dict being looped through in parent_list.

Conclusion

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop.

Categories
Python Answers

How to get value from select tag using Python Flask?

Sometimes, we want to get value from select tag using Python Flask.

In this article, we’ll look at how to get value from select tag using Python Flask.

How to get value from select tag using Python Flask?

To get value from select tag using Python Flask, we can use the request.form propety in our view.

For instance, we write

from flask import Flask, flash, redirect, render_template, \
     request, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template(
        'index.html',
        data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])

@app.route("/test" , methods=['GET', 'POST'])
def test():
    select = request.form.get('comp_select')
    return(str(select))

if __name__=='__main__':
    app.run(debug=True)

to use select = request.form.get('comp_select') in the test view to get the value of the select element with the name attribute set to comp_select.

In our index.html template, we add

<form method="POST" action="{{ url_for('test') }}">
  <select name="comp_select">
    {% for o in data %}
    <option value="{{ o.name }}">{{ o.name }}</option>
    {% endfor %}
  </select>

  <button type="submit" class="btn btn-default">Go</button>
</form>

to add a form with the select element with the name attribute set to comp_select.

The options are rendered from the data list.

Conclusion

To get value from select tag using Python Flask, we can use the request.form propety in our view.

Categories
Python Answers

How to set response headers in Python Flask?

Sometimes, we want to set response headers in Python Flask.

In this article, we’ll look at how to set response headers in Python Flask.

How to set response headers in Python Flask?

To set response headers in Python Flask, we put the headers in the response.headers dict.

For instance, we write

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

to create a response with the flask.Response class by calling it with the response body.

Then we add the Access-Control-Allow-Origin response header with

resp.headers['Access-Control-Allow-Origin'] = '*'

And then we return resp as the response.

Categories
Python Answers

How to start a Python Flask application in separate thread?

Sometimes, we want to start a Python Flask application in separate thread.

In this article, we’ll look at how to start a Python Flask application in separate thread.

How to start a Python Flask application in separate thread?

To start a Python Flask application in separate thread, we set the use_reloader to False when we call app.run.

And then we create a Thread instance with the Flask app by setting the function that calls app.run as the value of the target argument.

For instance, we write

from flask import Flask                                                         
import threading

data = 'hello'
host_name = "0.0.0.0"
port = 23336
app = Flask(__name__)

@app.route("/")
def main():
    return data

if __name__ == "__main__":
    threading.Thread(target=lambda: app.run(host=host_name, port=port, debug=True, use_reloader=False)).start()

to create a threading.Thread instance with the target set to a function that calls app.run with use_reloader set to False to start the app in a separate thread.

Conclusion

To start a Python Flask application in separate thread, we set the use_reloader to False when we call app.run.

And then we create a Thread instance with the Flask app by setting the function that calls app.run as the value of the target argument.

Categories
Python Answers

How to disable caching in Python Flask?

Sometimes, we want to disable caching in Python Flask.

In this article, we’ll look at how to disable caching in Python Flask.

How to disable caching in Python Flask?

To disable caching in Python Flask, we can set the response headers to disable cache.

For instance, we write

@app.after_request
def add_header(r):
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers['Cache-Control'] = 'public, max-age=0'
    return r

to create the add_header function that adds a few headers to the response after each request is done.

We make it run after each request with the @app.after_request decorator.

And then we add the Expires and Cache-Control headers and set their values all to 0 to disable caching.

Conclusion

To disable caching in Python Flask, we can set the response headers to disable cache.