Skip to content
Advertisement

Python Flask cookie consent

I want to set a banner that asks for permission to store cookies on my website(because GDPR). I’ve tried like this: HTML:

{% block cookies %}
        {% if cookies_check %}
        {% else %}
          <div class="fixed-bottom p-4" id="cookie-consent-container">
              <div class="toast bg-dark text-white w-100 mw-100" role="alert">
                  <div class="toast-body p-4 d-flex flex-column">
                      <h4>Cookie Warning</h4>
                      <p>
                      This website stores data such as cookies to enable site functionality including analytics and personalization. By using this website, you automatically accept that we use cookies. 
                      </p>
                      <div class="ml-auto">
                        <button type="button" class="btn btn-outline-light mr-3" id="btnDeny">
                            Deny
                        </button>
                        <button type="button" class="btn btn-light" id="btnAccept">
                            Accept
                        </button>
                      </div>
                  </div>
              </div>
          </div>
          <script>
            var fn = function () {
                document.cookie = "cookie_consent=true";
                document.getElementById('cookie-consent-container').hidden = true;
            };
            document.getElementById('btnAccept').onclick = fn;
          </script>
        {% endif %}
      {% endblock cookies %}

and jinja2

@app.context_processor
def inject_template_scope():
    injections = dict()
    print(injections)

    def cookies_check():
        value = request.cookies.get('cookie_consent')
        print(value)
        return value == 'true'
    injections.update(cookies_check=cookies_check)

    return injections

The prints are for debugging. The problem is that the list is always empty and the banner is never showing. What should I do to make this work? Does that mean that the site is not generating any cookie to begin with? If so how can I add a cookie when the site is loaded?

Advertisement

Answer

A cookie can be added,read,deleted using document.cookie

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

By default cookie delete after browser is closed.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement