-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
123 lines (95 loc) Β· 3.67 KB
/
main.py
File metadata and controls
123 lines (95 loc) Β· 3.67 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""
main.py
This is the application factory for the Nyota β¨ project.
"""
import os
import json
from datetime import timedelta
from flask import Flask, g, session, request
from flask_babel import Babel
import mistune
from flask_compress import Compress
from config import Config
from models.nyota import db, migrate
from routes import main_bp, admin_bp
babel = Babel()
# --- Jinja2 Custom Filters ---
def format_currency(value, symbol='$'):
if value is None:
return f"{symbol} 0.00"
return f"{symbol} {float(value):,.2f}"
from utils.translator import translate
# --- Language Selection for Babel ---
def get_locale():
if 'language' in session:
return session['language']
# Check headers for country code (Cloudflare, App Engine, or Generic)
country = request.headers.get('CF-IPCountry') or \
request.headers.get('X-AppEngine-Country') or \
request.headers.get('X-Country-Code')
# If a country is detected and it is NOT Tanzania, default to English
if country and country.upper() != 'TZ':
return 'en'
# Default to Swahili for Tanzania and all unknown locations
return 'sw'
# --- Application Factory Function ---
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
# Trust the reverse proxy's X-Forwarded-Proto header so request.url_root
# uses https:// instead of http:// when behind nginx/Cloudflare.
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
# --- Initialize Flask Extensions ---
db.init_app(app)
migrate.init_app(app, db)
babel.init_app(app, locale_selector=get_locale)
Compress(app)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 31536000 # 1 year cache for static files
# --- Register Jinja2 Filters ---
app.jinja_env.filters['format_currency'] = format_currency
def nl2br(value):
from markupsafe import Markup, escape
if not value:
return ""
return Markup(str(escape(value)).replace('\n', '<br>\n'))
app.jinja_env.filters['nl2br'] = nl2br
# This lambda function takes text, processes it with mistune, and returns HTML.
app.jinja_env.filters['markdown'] = lambda text: mistune.html(text)
# --- Register Blueprints ---
app.register_blueprint(main_bp)
app.register_blueprint(admin_bp)
# --- Request Hooks ---
@app.before_request
def before_request_tasks():
session.permanent = True
app.permanent_session_lifetime = timedelta(days=30)
g.language = get_locale()
# --- Context Processors ---
@app.context_processor
def inject_global_vars():
return dict(
store_name="Nyota β¨",
currency_symbol=get_currency_symbol(),
translate=translate
)
def get_currency_symbol():
from models.nyota import Creator
creator = Creator.query.first()
if creator:
return creator.get_setting('payment_uza_currency', 'TZS')
return 'TZS'
# --- Cache Headers for Static Assets ---
@app.after_request
def add_cache_headers(response):
if request.path.startswith('/static/'):
response.cache_control.max_age = 31536000
response.cache_control.public = True
return response
# Start background worker (scheduled campaigns + subscription reminders).
# Suppressed during flask db migrate / flask db upgrade via env var.
import os
if not os.environ.get('FLASK_SKIP_BACKGROUND_WORKER'):
from services.background_tasks import start_background_worker
start_background_worker(app)
return app