Support

Find answers, guides, and tutorials to supercharge your content delivery.

Flask CDN Integration

Updated on January 6, 2023

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 cdn.yourdomain.com with your CDN URL (e.g flaskcdn-hexid.kxcdn.com). If you would rather use a custom CDN URL, you can create a Zone Alias.

    from flask import Flask
    from flask.ext.cdn import CDN
    
    app = Flask(__name__)
    app.config['CDN_DOMAIN'] = 'cdn.yourdomain.com'
    CDN(app)
    

    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 named 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 through KeyCDN by viewing the page source and checking the Request URL.

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

Supercharge your content delivery 🚀

Try KeyCDN with a free 14 day trial, no credit card required.

Get started
KeyCDN uses cookies to make its website easier to use. Learn more