Serving Static Files

In addition to handling dynamic requests, applications often need to serve additional static files such as JavaScript, images, and CSS. The flexible environment allows you to decide how to serve static content for your application. You can serve static content directly from your application, host it on a GCP option like Cloud Storage, or use a third-party content delivery network (CDN).

Serving files from App Engine

Serving files from your app is typically straightforward, however, there are a couple drawbacks that you should consider:

  • Requests for static files can use resources that otherwise would be used for dynamic requests.
  • Depending on your configuration, serving files from your app can result in response latency, which can also affect when new instances are created for handling the load.

Tip: In production environments, it's generally best practice to serve your static content separately from your app, either in GCP or externally using a third-party CDN.

Example of serving static files with your app

Most web frameworks include support for serving static files. In this sample, the app uses Flask's built-in ability to serve files in ./static directory from the /static URL.

The app includes a view that renders the template. Flask automatically serves everything in the ./static directory without additional configuration.

import logging

from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')
def hello():
    return render_template('index.html')


@app.errorhandler(500)
def server_error(e):
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500


if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)

The template rendered by the view includes a stylesheet located at /static/main.css.

<!doctype html>
<html>
<head>
  <title>Static Files</title>
  <!--
  Flask automatically makes files in the 'static' directory available via
  '/static'.
  -->
  <link rel="stylesheet" type="text/css" href="/static/main.css">
</head>
<body>
  <p>This is a static file serving example.</p>
</body>
</html>

The stylesheet is located at ./static/main.css.

body {
  font-family: Verdana, Helvetica, sans-serif;
  background-color: #CCCCFF;
}

Other Python frameworks, such as Django, Pyramid, and Bottle typically support serving static files directly from the app. Refer to their documentation for details on how to configure and use static content.

Serving files from GCP

You also have the option of using Cloud CDN or another GCP storage service like Cloud Storage.

Serving files from Cloud Storage

Cloud Storage can be used to host static assets for dynamic web apps. The benefits of using Cloud Storage instead of serving directly from your app include:

  • Cloud Storage essentially works as a content delivery network. This does not require any special configuration because by default any publicly readable object is cached in the global Cloud Storage network.
  • Your app's load will be reduced by offloading serving static assets to Cloud Storage. Depending on how many static assets you have and the frequency of access, this can reduce the cost of running your app by a significant amount.
  • Bandwidth charges for accessing content can often be less with Cloud Storage.

You can upload your assets to Cloud Storage by using the Cloud SDK or the Cloud Storage API.

Example of serving from a Cloud Storage bucket

This simple example creates a Cloud Storage bucket and uploads static assets using Cloud SDK:

  1. Create a bucket. It's common, but not required, to name your bucket after your project ID. The bucket name must be globally unique.

    gsutil mb gs://<your-bucket-name>
    
  2. Set the ACL to grant read access to items in the bucket.

    gsutil defacl set public-read gs://<your-bucket-name>
    
  3. Upload items to the bucket. The rsync command is typically the fastest and easiest way to upload and update assets. You could also use cp.

    gsutil -m rsync -r ./static gs://<your-bucket-name>/static
    

You can now access your static assets via https://storage.googleapis.com/<your-bucket-name>/static/....

For more details on how to use Cloud Storage to serve static assets, including how to serve from a custom domain name, refer to How to Host a Static Website.

For more information on how to use the Cloud Storage API to dynamically upload, download, and manipulate files from within your app, see Using Cloud Storage.

Serving from a third-party content delivery network

You can use any external third-party CDN to serve your static files and cache dynamic requests but your app might experience increased latency and cost.

For improved performance, you should use a third-party CDN that supports CDN Interconnect.

Was this page helpful? Let us know how we did:

Send feedback about...

App Engine flexible environment for Python docs