Skip to main content

Flask-CronDecorator

Securely decorates Google Cloud Cron Endpoints via convention and X-Appengine-Cron header.

Per the docs:

The X-Appengine-Cron header is set internally by Google App Engine. If your request handler finds this header it can trust that the request is a cron request. The X- headers are stripped by App Engine when they originate from external sources so that you can trust this header.

Installation

Add this line to your application's requirements.txt

Flask-CronDecorator

And then execute:

$ pip install -r requirements.txt

Or install it yourself as:

$ pip install Flask-CronDecorator

Usage

The following snippet should get you coding

from flask import Flask, Blueprint
from CronDecorator import CronDecorator
import logging
from datetime import datetime, timedelta
from models import Task, TaskRequest


app = Flask(__name__)
app.cron = CronDecorator(app)

# blueprint can optionally be passed in for registering cron task endpoints in a blueprint
admin = Blueprint('admin', __name__, template_folder='templates', url_prefix='/admin')
blueprint.cron = CronDecorator(app, blueprint)

app.register_blueprint(admin)
_logger = logging.getLogger(__name__)


@admin.cron.task('/purge_tasks', methods=['GET'])  # creates /cron/admin/purge_tasks endpoint
def purge_tasks():
    _logger.info('Purging first 100 Tasks older than 1 year')
    year_ago = datetime.utcnow() - timedelta(days=365)
    tasks = Task.query.filter(Task.created <= year_ago).order_by(Task.id.asc()).limit(100).all()
    for task in tasks:
        db.session.delete(task)

    _logger.info('Purging first 1000 TaskRequests older than 2 weeks')
    two_weeks_ago = datetime.utcnow() - timedelta(days=14)
    task_requests = TaskRequest.query.join(Task).filter(
        models.Task.created <= two_weeks_ago
    ).order_by(Task.id.desc()).limit(1000).all()

    for task_request in task_requests:
        db.session.delete(task_request)

    db.session.commit()

    return '', 200

Google Cloud Settings

Given the above snippet, you'll need to update your Google Cloud cron.yaml

cron:
- description: "Purges Tasks older than 1 year and TaskRequests older than 2 weeks"
  url: /cron/admin/purge_tasks
  schedule: every 30 minutes

Be sure your /cron/* endpoints are covered in Google Cloud app.yaml. Note: the handlers:script must be a wsgi path to your flask app instantiation relative to where the process is started, not necessarily where app.yaml lives.

runtime: python
runtime_config:
  python_version: 2
threadsafe: true
env: flex
handlers:
- script: flask.app
  secure: always
  url: /cron/.*

Deploy

Deploy app and cron.yaml to Google Cloud

$ gcloud app deploy
$ gcloud app deploy cron.yaml

Testing

$ pytest -s tests.py

Metadata

Release files for Flask-CronDecorator 0.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for Flask-CronDecorator 0.0.3
File Size Uploaded
Flask-CronDecorator-0.0.3.tar.gz 3.2 kB Details

Release files / Flask-CronDecorator-0.0.3.tar.gz

Download URL Flask-CronDecorator-0.0.3.tar.gz
Size 3.2 kB
Tags Source
SHA-256 checksum
How to use checksums
177694682cccf747ccc121775540679f92c954cd600ea662c74c5b5cd6583334
BLAKE2b-256 checksum
How to use checksums
fb9bed019aa71c40e276085cd7d735fa52f47de26255a774607f6fc4d0ebe96e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.20.0 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.6.5

Release history Release notifications | RSS feed

This release

0.0.3 This release

1 release file

0.0.2

1 release file

0.0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page