Flask CDN Integration Guide

Flask is a lightweight, easy to install web framework based on Python, Werkzeug, and Jinja2. This tutorial will guide you through how to configure your Flask application in order to deliver static assets via KeyCDN.

This method currently only supports Flask applications that are using Jinja2 templating language.

How to complete a Flask CDN integration

  1. Before starting the integration process, create a Pull Zone in your KeyCDN dashboard.
  2. In order to use a CDN with Flask, Flask-CDN must be installed. This can be installed using the following methods:
    • pip:
      pip install flask-cdn
    • Github:
      pip install git+git://github.com/wichitacode/flask-cdn.git
    • Easy Install:
      easy_install flask-cdn
  3. Once Flask-CDN is installed, the following snippet must be added to your app.py file. Replace the cdn.yourdomain.com url with your CDN url (e.g flaskcdn-1c6b.kxcdn.com). If you would rather use a custom CDN url here, you may create a Zonealias.
    from flask import Flask
    from flask.ext.cdn import CDN
    app = Flask(__name__)
    app.config['CDN_DOMAIN'] = 'cdn.yourdomain.com'

    Restart your Flask application once the changes have been saved in your app.py file.

  4. All static files associated with your Flask application should be located within a folder called static located in your Flask app’s root directory. Reference your static assets within your Flask templates using the following format:
    {{ url_for('static', filename='keycdn.png') }}
  5. As always, double check that your static assets are indeed being delivered via KeyCDN by viewing the page source and checking the Request url.  flask-cdn

Note that the timestamp is by default set to True when using Flask-CDN. Therefore, it will be appended to the end of the asset’s url. In order to disable the timestamp, add the following snippet in your app.py file under the CDN_DOMAIN section:

app.config['CDN_TIMESTAMP'] = False