Flask extension that integrates APScheduler for job scheduling with REST API management and authentication support
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Primary scheduler functionality that integrates APScheduler with Flask applications. Provides initialization, lifecycle management, configuration loading, and event handling capabilities.
Main scheduler class that wraps APScheduler functionality and provides Flask integration.
class APScheduler:
"""
Provides a scheduler integrated to Flask.
Attributes:
allowed_hosts (list): List of hostnames allowed to start scheduler
auth (HTTPAuth): Authentication handler for API endpoints
api_enabled (bool): Whether REST API is enabled
api_prefix (str): URL prefix for API endpoints
endpoint_prefix (str): Prefix for Flask endpoint names
app (Flask): Flask application instance
"""
def __init__(self, scheduler=None, app=None):
"""
Initialize APScheduler.
Args:
scheduler: APScheduler instance (BackgroundScheduler if None)
app: Flask application instance
"""Setup and configuration methods for integrating with Flask applications.
def init_app(self, app):
"""
Initialize the APScheduler with a Flask application instance.
Args:
app (Flask): Flask application instance
Note:
- Loads configuration from Flask config
- Loads job definitions from config
- Sets up REST API if enabled
- Sets app.apscheduler = self
"""Read-only properties providing scheduler state and information.
@property
def host_name(self) -> str:
"""Get the host name."""
@property
def running(self) -> bool:
"""Get true whether the scheduler is running."""
@property
def state(self) -> int:
"""Get the state of the scheduler (STATE_RUNNING, STATE_PAUSED, STATE_STOPPED)."""
@property
def scheduler(self):
"""Get the base APScheduler instance."""
@property
def task(self):
"""Get the scheduler decorator for job definitions."""Methods for controlling scheduler execution state.
def start(self, paused=False):
"""
Start the scheduler.
Args:
paused (bool): If True, don't start job processing until resume is called
Note:
- Prevents double-start in Flask debug mode
- Checks hostname against allowed_hosts
- Only starts if hostname is in allowed_hosts or "*" is allowed
"""
def shutdown(self, wait=True):
"""
Shut down the scheduler.
Args:
wait (bool): True to wait until all currently executing jobs have finished
Raises:
SchedulerNotRunningError: If scheduler has not been started yet
"""
def pause(self):
"""
Pause job processing in the scheduler.
Note:
Prevents scheduler from waking up for job processing until resume() is called.
Does not stop already running jobs.
"""
def resume(self):
"""Resume job processing in the scheduler."""Methods for managing scheduler event listeners.
def add_listener(self, callback, mask=EVENT_ALL):
"""
Add a listener for scheduler events.
Args:
callback: Callable that takes one argument (event object)
mask (int): Bitmask indicating which events to listen for
Note:
When a matching event occurs, callback is executed with the event object.
If mask is not provided, callback receives events of all types.
"""
def remove_listener(self, callback):
"""Remove a previously added event listener."""Decorator for registering authentication functions.
def authenticate(self, func):
"""
A decorator that is used to register a function to authenticate a user.
Args:
func: The callback function to authenticate users
Returns:
The decorated function
Example:
@scheduler.authenticate
def authenticate(auth):
return auth["username"] == "admin" and auth["password"] == "secret"
"""from flask import Flask
from flask_apscheduler import APScheduler
app = Flask(__name__)
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()from flask import Flask
from flask_apscheduler import APScheduler
class Config:
SCHEDULER_API_ENABLED = True
SCHEDULER_API_PREFIX = "/api/scheduler"
SCHEDULER_ALLOWED_HOSTS = ["localhost", "production.example.com"]
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
def job_executed(event):
print(f"Job {event.job_id} executed")
def job_failed(event):
print(f"Job {event.job_id} failed: {event.exception}")
scheduler.add_listener(job_executed, EVENT_JOB_EXECUTED)
scheduler.add_listener(job_failed, EVENT_JOB_ERROR)# Allow scheduler to run only on specific hosts
app.config["SCHEDULER_ALLOWED_HOSTS"] = ["worker1.example.com", "worker2.example.com"]
# Allow on any host (default)
app.config["SCHEDULER_ALLOWED_HOSTS"] = ["*"]Install with Tessl CLI
npx tessl i tessl/pypi-flask-apscheduler