-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.py
More file actions
87 lines (60 loc) · 2.28 KB
/
Copy pathconfig.py
File metadata and controls
87 lines (60 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""Configuration module for the Flask application."""
# Author: Alexander Hambley
# License: MIT
# Copyright (c) 2025 eScience Lab, The University of Manchester
import os
from celery import Celery
from flask import Flask
def get_env(name: str, default=None, required=False):
value = os.environ.get(name, default)
if required and value is None:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
class Config:
"""Base configuration class for the Flask application."""
# Celery configuration:
CELERY_BROKER_URL = get_env("CELERY_BROKER_URL", required=False)
CELERY_RESULT_BACKEND = get_env("CELERY_RESULT_BACKEND", required=False)
# rocrate validator configuration:
PROFILES_PATH = get_env("PROFILES_PATH", required=False)
class DevelopmentConfig(Config):
"""Development configuration class."""
DEBUG = True
class ProductionConfig(Config):
"""Production configuration class."""
DEBUG = False
class InvalidAPIUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
super().__init__()
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
def make_celery(app: Flask = None) -> Celery:
"""
Initialises and configures a Celery instance with the Flask application.
:param app: The Flask application to use.
:return: The Celery instance.
"""
env = os.environ.get("FLASK_ENV", "development")
config_cls = ProductionConfig if env == "production" else DevelopmentConfig
celery = Celery(
app.import_name if app else __name__,
broker=config_cls.CELERY_BROKER_URL,
backend=config_cls.CELERY_RESULT_BACKEND,
)
if app:
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
"""Task class to run tasks within the Flask app context."""
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery