We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error logs generated in Celery while sending Mails
```
Traceback (most recent call last):
  File "/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 551, in on_task_received
    payload = message.decode()
  File "/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/kombu/message.py", line 193, in decode
    self._decoded_cache = self._decode()
  File "/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/kombu/message.py", line 198, in _decode
    self.content_encoding, accept=self.accept)
  File "/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/kombu/serialization.py", line 253, in loads
    raise self._for_untrusted_content(content_type, 'untrusted')
kombu.exceptions.ContentDisallowed: Refusing to deserialize untrusted content of type pickle (application/x-python-serialize)
```

Similar logs are there for JSON format of mail objects.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `app/__init__.py`
Content:
```
1 from celery.signals import after_task_publish
2 import logging
3 import os.path
4 from envparse import env
5 
6 import sys
7 from flask import Flask, json, make_response
8 from flask_celeryext import FlaskCeleryExt
9 from app.settings import get_settings, get_setts
10 from flask_migrate import Migrate, MigrateCommand
11 from flask_script import Manager
12 from flask_login import current_user
13 from flask_jwt import JWT
14 from datetime import timedelta
15 from flask_cors import CORS
16 from flask_rest_jsonapi.errors import jsonapi_errors
17 from flask_rest_jsonapi.exceptions import JsonApiException
18 from healthcheck import HealthCheck
19 from apscheduler.schedulers.background import BackgroundScheduler
20 from elasticsearch_dsl.connections import connections
21 from pytz import utc
22 
23 import sqlalchemy as sa
24 
25 import stripe
26 from app.settings import get_settings
27 from app.models import db
28 from app.api.helpers.jwt import jwt_authenticate, jwt_identity
29 from app.api.helpers.cache import cache
30 from werkzeug.middleware.profiler import ProfilerMiddleware
31 from app.views import BlueprintsManager
32 from app.api.helpers.auth import AuthManager
33 from app.api.helpers.scheduled_jobs import send_after_event_mail, send_event_fee_notification, \
34     send_event_fee_notification_followup, change_session_state_on_event_completion, \
35     expire_pending_tickets_after_three_days
36 from app.models.event import Event
37 from app.models.role_invite import RoleInvite
38 from app.views.healthcheck import health_check_celery, health_check_db, health_check_migrations, check_migrations
39 from app.views.elastic_search import client
40 from app.views.elastic_cron_helpers import sync_events_elasticsearch, cron_rebuild_events_elasticsearch
41 from app.views.redis_store import redis_store
42 from app.views.celery_ import celery
43 from app.templates.flask_ext.jinja.filters import init_filters
44 import sentry_sdk
45 from sentry_sdk.integrations.flask import FlaskIntegration
46 
47 
48 BASE_DIR = os.path.dirname(os.path.abspath(__file__))
49 
50 static_dir = os.path.dirname(os.path.dirname(__file__)) + "/static"
51 template_dir = os.path.dirname(__file__) + "/templates"
52 app = Flask(__name__, static_folder=static_dir, template_folder=template_dir)
53 env.read_envfile()
54 
55 
56 class ReverseProxied(object):
57     """
58     ReverseProxied flask wsgi app wrapper from http://stackoverflow.com/a/37842465/1562480 by aldel
59     """
60 
61     def __init__(self, app):
62         self.app = app
63 
64     def __call__(self, environ, start_response):
65         scheme = environ.get('HTTP_X_FORWARDED_PROTO')
66         if scheme:
67             environ['wsgi.url_scheme'] = scheme
68         if os.getenv('FORCE_SSL', 'no') == 'yes':
69             environ['wsgi.url_scheme'] = 'https'
70         return self.app(environ, start_response)
71 
72 
73 app.wsgi_app = ReverseProxied(app.wsgi_app)
74 
75 app_created = False
76 
77 
78 def create_app():
79     global app_created
80     if not app_created:
81         BlueprintsManager.register(app)
82     Migrate(app, db)
83 
84     app.config.from_object(env('APP_CONFIG', default='config.ProductionConfig'))
85     db.init_app(app)
86     _manager = Manager(app)
87     _manager.add_command('db', MigrateCommand)
88 
89     if app.config['CACHING']:
90         cache.init_app(app, config={'CACHE_TYPE': 'simple'})
91     else:
92         cache.init_app(app, config={'CACHE_TYPE': 'null'})
93 
94     stripe.api_key = 'SomeStripeKey'
95     app.secret_key = 'super secret key'
96     app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
97     app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
98 
99     app.logger.addHandler(logging.StreamHandler(sys.stdout))
100     app.logger.setLevel(logging.ERROR)
101 
102     # set up jwt
103     app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
104     app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)
105     app.config['JWT_AUTH_URL_RULE'] = '/auth/session'
106     _jwt = JWT(app, jwt_authenticate, jwt_identity)
107 
108     # setup celery
109     app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL']
110     app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']
111 
112     CORS(app, resources={r"/*": {"origins": "*"}})
113     AuthManager.init_login(app)
114 
115     if app.config['TESTING'] and app.config['PROFILE']:
116         # Profiling
117         app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
118 
119     # development api
120     with app.app_context():
121         from app.api.admin_statistics_api.events import event_statistics
122         from app.api.auth import auth_routes
123         from app.api.attendees import attendee_misc_routes
124         from app.api.bootstrap import api_v1
125         from app.api.celery_tasks import celery_routes
126         from app.api.event_copy import event_copy
127         from app.api.exports import export_routes
128         from app.api.imports import import_routes
129         from app.api.uploads import upload_routes
130         from app.api.users import user_misc_routes
131         from app.api.orders import order_misc_routes
132         from app.api.role_invites import role_invites_misc_routes
133         from app.api.auth import ticket_blueprint, authorised_blueprint
134         from app.api.admin_translations import admin_blueprint
135         from app.api.orders import alipay_blueprint
136 
137         app.register_blueprint(api_v1)
138         app.register_blueprint(event_copy)
139         app.register_blueprint(upload_routes)
140         app.register_blueprint(export_routes)
141         app.register_blueprint(import_routes)
142         app.register_blueprint(celery_routes)
143         app.register_blueprint(auth_routes)
144         app.register_blueprint(event_statistics)
145         app.register_blueprint(user_misc_routes)
146         app.register_blueprint(attendee_misc_routes)
147         app.register_blueprint(order_misc_routes)
148         app.register_blueprint(role_invites_misc_routes)
149         app.register_blueprint(ticket_blueprint)
150         app.register_blueprint(authorised_blueprint)
151         app.register_blueprint(admin_blueprint)
152         app.register_blueprint(alipay_blueprint)
153 
154     sa.orm.configure_mappers()
155 
156     if app.config['SERVE_STATIC']:
157         app.add_url_rule('/static/<path:filename>',
158                          endpoint='static',
159                          view_func=app.send_static_file)
160 
161     # sentry
162     if not app_created and 'SENTRY_DSN' in app.config:
163         sentry_sdk.init(app.config['SENTRY_DSN'], integrations=[FlaskIntegration()])
164 
165     # redis
166     redis_store.init_app(app)
167 
168     # elasticsearch
169     if app.config['ENABLE_ELASTICSEARCH']:
170         client.init_app(app)
171         connections.add_connection('default', client.elasticsearch)
172         with app.app_context():
173             try:
174                 cron_rebuild_events_elasticsearch.delay()
175             except Exception:
176                 pass
177 
178     app_created = True
179     return app, _manager, db, _jwt
180 
181 
182 current_app, manager, database, jwt = create_app()
183 init_filters(app)
184 
185 
186 # http://stackoverflow.com/questions/26724623/
187 @app.before_request
188 def track_user():
189     if current_user.is_authenticated:
190         current_user.update_lat()
191 
192 
193 def make_celery(app=None):
194     app = app or create_app()[0]
195     celery.conf.update(app.config)
196     ext = FlaskCeleryExt(app)
197     return ext.celery
198 
199 
200 # Health-check
201 health = HealthCheck(current_app, "/health-check")
202 health.add_check(health_check_celery)
203 health.add_check(health_check_db)
204 with current_app.app_context():
205     current_app.config['MIGRATION_STATUS'] = check_migrations()
206 health.add_check(health_check_migrations)
207 
208 
209 # http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists
210 @after_task_publish.connect
211 def update_sent_state(sender=None, headers=None, **kwargs):
212     # the task may not exist if sent using `send_task` which
213     # sends tasks by name, so fall back to the default result backend
214     # if that is the case.
215     task = celery.tasks.get(sender)
216     backend = task.backend if task else celery.backend
217     backend.store_result(headers['id'], None, 'WAITING')
218 
219 
220 # register celery tasks. removing them will cause the tasks to not function. so don't remove them
221 # it is important to register them after celery is defined to resolve circular imports
222 
223 from .api.helpers import tasks
224 
225 # import helpers.tasks
226 
227 
228 scheduler = BackgroundScheduler(timezone=utc)
229 # scheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)
230 # scheduler.add_job(empty_trash, 'cron', hour=5, minute=30)
231 if app.config['ENABLE_ELASTICSEARCH']:
232     scheduler.add_job(sync_events_elasticsearch, 'interval', minutes=60)
233     scheduler.add_job(cron_rebuild_events_elasticsearch, 'cron', day=7)
234 
235 scheduler.add_job(send_after_event_mail, 'cron', hour=5, minute=30)
236 scheduler.add_job(send_event_fee_notification, 'cron', day=1)
237 scheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)
238 scheduler.add_job(change_session_state_on_event_completion, 'cron', hour=5, minute=30)
239 scheduler.add_job(expire_pending_tickets_after_three_days, 'cron', hour=5)
240 scheduler.start()
241 
242 
243 @app.errorhandler(500)
244 def internal_server_error(error):
245     if current_app.config['PROPOGATE_ERROR'] is True:
246         exc = JsonApiException({'pointer': ''}, str(error))
247     else:
248         exc = JsonApiException({'pointer': ''}, 'Unknown error')
249     return make_response(json.dumps(jsonapi_errors([exc.to_dict()])), exc.status,
250                          {'Content-Type': 'application/vnd.api+json'})
251 
252 
253 if __name__ == '__main__':
254     current_app.run()
255
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -108,6 +108,7 @@
     # setup celery
     app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL']
     app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']
+    app.config['CELERY_ACCEPT_CONTENT'] = ['json', 'application/text']
 
     CORS(app, resources={r"/*": {"origins": "*"}})
     AuthManager.init_login(app)

{"golden_diff": "diff --git a/app/__init__.py b/app/__init__.py\n--- a/app/__init__.py\n+++ b/app/__init__.py\n@@ -108,6 +108,7 @@\n     # setup celery\n     app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL']\n     app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']\n+    app.config['CELERY_ACCEPT_CONTENT'] = ['json', 'application/text']\n \n     CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n     AuthManager.init_login(app)\n", "issue": "Error logs generated in Celery while sending Mails\n```\r\nTraceback (most recent call last):\r\n  File \"/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py\", line 551, in on_task_received\r\n    payload = message.decode()\r\n  File \"/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/kombu/message.py\", line 193, in decode\r\n    self._decoded_cache = self._decode()\r\n  File \"/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/kombu/message.py\", line 198, in _decode\r\n    self.content_encoding, accept=self.accept)\r\n  File \"/Users/abhinav/Documents/OpenSource/fossassia/open-event-server/venv/lib/python3.6/site-packages/kombu/serialization.py\", line 253, in loads\r\n    raise self._for_untrusted_content(content_type, 'untrusted')\r\nkombu.exceptions.ContentDisallowed: Refusing to deserialize untrusted content of type pickle (application/x-python-serialize)\r\n```\r\n\r\nSimilar logs are there for JSON format of mail objects.\n", "before_files": [{"content": "from celery.signals import after_task_publish\nimport logging\nimport os.path\nfrom envparse import env\n\nimport sys\nfrom flask import Flask, json, make_response\nfrom flask_celeryext import FlaskCeleryExt\nfrom app.settings import get_settings, get_setts\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager\nfrom flask_login import current_user\nfrom flask_jwt import JWT\nfrom datetime import timedelta\nfrom flask_cors import CORS\nfrom flask_rest_jsonapi.errors import jsonapi_errors\nfrom flask_rest_jsonapi.exceptions import JsonApiException\nfrom healthcheck import HealthCheck\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom elasticsearch_dsl.connections import connections\nfrom pytz import utc\n\nimport sqlalchemy as sa\n\nimport stripe\nfrom app.settings import get_settings\nfrom app.models import db\nfrom app.api.helpers.jwt import jwt_authenticate, jwt_identity\nfrom app.api.helpers.cache import cache\nfrom werkzeug.middleware.profiler import ProfilerMiddleware\nfrom app.views import BlueprintsManager\nfrom app.api.helpers.auth import AuthManager\nfrom app.api.helpers.scheduled_jobs import send_after_event_mail, send_event_fee_notification, \\\n    send_event_fee_notification_followup, change_session_state_on_event_completion, \\\n    expire_pending_tickets_after_three_days\nfrom app.models.event import Event\nfrom app.models.role_invite import RoleInvite\nfrom app.views.healthcheck import health_check_celery, health_check_db, health_check_migrations, check_migrations\nfrom app.views.elastic_search import client\nfrom app.views.elastic_cron_helpers import sync_events_elasticsearch, cron_rebuild_events_elasticsearch\nfrom app.views.redis_store import redis_store\nfrom app.views.celery_ import celery\nfrom app.templates.flask_ext.jinja.filters import init_filters\nimport sentry_sdk\nfrom sentry_sdk.integrations.flask import FlaskIntegration\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nstatic_dir = os.path.dirname(os.path.dirname(__file__)) + \"/static\"\ntemplate_dir = os.path.dirname(__file__) + \"/templates\"\napp = Flask(__name__, static_folder=static_dir, template_folder=template_dir)\nenv.read_envfile()\n\n\nclass ReverseProxied(object):\n    \"\"\"\n    ReverseProxied flask wsgi app wrapper from http://stackoverflow.com/a/37842465/1562480 by aldel\n    \"\"\"\n\n    def __init__(self, app):\n        self.app = app\n\n    def __call__(self, environ, start_response):\n        scheme = environ.get('HTTP_X_FORWARDED_PROTO')\n        if scheme:\n            environ['wsgi.url_scheme'] = scheme\n        if os.getenv('FORCE_SSL', 'no') == 'yes':\n            environ['wsgi.url_scheme'] = 'https'\n        return self.app(environ, start_response)\n\n\napp.wsgi_app = ReverseProxied(app.wsgi_app)\n\napp_created = False\n\n\ndef create_app():\n    global app_created\n    if not app_created:\n        BlueprintsManager.register(app)\n    Migrate(app, db)\n\n    app.config.from_object(env('APP_CONFIG', default='config.ProductionConfig'))\n    db.init_app(app)\n    _manager = Manager(app)\n    _manager.add_command('db', MigrateCommand)\n\n    if app.config['CACHING']:\n        cache.init_app(app, config={'CACHE_TYPE': 'simple'})\n    else:\n        cache.init_app(app, config={'CACHE_TYPE': 'null'})\n\n    stripe.api_key = 'SomeStripeKey'\n    app.secret_key = 'super secret key'\n    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\n    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'\n\n    app.logger.addHandler(logging.StreamHandler(sys.stdout))\n    app.logger.setLevel(logging.ERROR)\n\n    # set up jwt\n    app.config['JWT_AUTH_USERNAME_KEY'] = 'email'\n    app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)\n    app.config['JWT_AUTH_URL_RULE'] = '/auth/session'\n    _jwt = JWT(app, jwt_authenticate, jwt_identity)\n\n    # setup celery\n    app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL']\n    app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']\n\n    CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n    AuthManager.init_login(app)\n\n    if app.config['TESTING'] and app.config['PROFILE']:\n        # Profiling\n        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])\n\n    # development api\n    with app.app_context():\n        from app.api.admin_statistics_api.events import event_statistics\n        from app.api.auth import auth_routes\n        from app.api.attendees import attendee_misc_routes\n        from app.api.bootstrap import api_v1\n        from app.api.celery_tasks import celery_routes\n        from app.api.event_copy import event_copy\n        from app.api.exports import export_routes\n        from app.api.imports import import_routes\n        from app.api.uploads import upload_routes\n        from app.api.users import user_misc_routes\n        from app.api.orders import order_misc_routes\n        from app.api.role_invites import role_invites_misc_routes\n        from app.api.auth import ticket_blueprint, authorised_blueprint\n        from app.api.admin_translations import admin_blueprint\n        from app.api.orders import alipay_blueprint\n\n        app.register_blueprint(api_v1)\n        app.register_blueprint(event_copy)\n        app.register_blueprint(upload_routes)\n        app.register_blueprint(export_routes)\n        app.register_blueprint(import_routes)\n        app.register_blueprint(celery_routes)\n        app.register_blueprint(auth_routes)\n        app.register_blueprint(event_statistics)\n        app.register_blueprint(user_misc_routes)\n        app.register_blueprint(attendee_misc_routes)\n        app.register_blueprint(order_misc_routes)\n        app.register_blueprint(role_invites_misc_routes)\n        app.register_blueprint(ticket_blueprint)\n        app.register_blueprint(authorised_blueprint)\n        app.register_blueprint(admin_blueprint)\n        app.register_blueprint(alipay_blueprint)\n\n    sa.orm.configure_mappers()\n\n    if app.config['SERVE_STATIC']:\n        app.add_url_rule('/static/<path:filename>',\n                         endpoint='static',\n                         view_func=app.send_static_file)\n\n    # sentry\n    if not app_created and 'SENTRY_DSN' in app.config:\n        sentry_sdk.init(app.config['SENTRY_DSN'], integrations=[FlaskIntegration()])\n\n    # redis\n    redis_store.init_app(app)\n\n    # elasticsearch\n    if app.config['ENABLE_ELASTICSEARCH']:\n        client.init_app(app)\n        connections.add_connection('default', client.elasticsearch)\n        with app.app_context():\n            try:\n                cron_rebuild_events_elasticsearch.delay()\n            except Exception:\n                pass\n\n    app_created = True\n    return app, _manager, db, _jwt\n\n\ncurrent_app, manager, database, jwt = create_app()\ninit_filters(app)\n\n\n# http://stackoverflow.com/questions/26724623/\n@app.before_request\ndef track_user():\n    if current_user.is_authenticated:\n        current_user.update_lat()\n\n\ndef make_celery(app=None):\n    app = app or create_app()[0]\n    celery.conf.update(app.config)\n    ext = FlaskCeleryExt(app)\n    return ext.celery\n\n\n# Health-check\nhealth = HealthCheck(current_app, \"/health-check\")\nhealth.add_check(health_check_celery)\nhealth.add_check(health_check_db)\nwith current_app.app_context():\n    current_app.config['MIGRATION_STATUS'] = check_migrations()\nhealth.add_check(health_check_migrations)\n\n\n# http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists\n@after_task_publish.connect\ndef update_sent_state(sender=None, headers=None, **kwargs):\n    # the task may not exist if sent using `send_task` which\n    # sends tasks by name, so fall back to the default result backend\n    # if that is the case.\n    task = celery.tasks.get(sender)\n    backend = task.backend if task else celery.backend\n    backend.store_result(headers['id'], None, 'WAITING')\n\n\n# register celery tasks. removing them will cause the tasks to not function. so don't remove them\n# it is important to register them after celery is defined to resolve circular imports\n\nfrom .api.helpers import tasks\n\n# import helpers.tasks\n\n\nscheduler = BackgroundScheduler(timezone=utc)\n# scheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)\n# scheduler.add_job(empty_trash, 'cron', hour=5, minute=30)\nif app.config['ENABLE_ELASTICSEARCH']:\n    scheduler.add_job(sync_events_elasticsearch, 'interval', minutes=60)\n    scheduler.add_job(cron_rebuild_events_elasticsearch, 'cron', day=7)\n\nscheduler.add_job(send_after_event_mail, 'cron', hour=5, minute=30)\nscheduler.add_job(send_event_fee_notification, 'cron', day=1)\nscheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)\nscheduler.add_job(change_session_state_on_event_completion, 'cron', hour=5, minute=30)\nscheduler.add_job(expire_pending_tickets_after_three_days, 'cron', hour=5)\nscheduler.start()\n\n\n@app.errorhandler(500)\ndef internal_server_error(error):\n    if current_app.config['PROPOGATE_ERROR'] is True:\n        exc = JsonApiException({'pointer': ''}, str(error))\n    else:\n        exc = JsonApiException({'pointer': ''}, 'Unknown error')\n    return make_response(json.dumps(jsonapi_errors([exc.to_dict()])), exc.status,\n                         {'Content-Type': 'application/vnd.api+json'})\n\n\nif __name__ == '__main__':\n    current_app.run()\n", "path": "app/__init__.py"}], "after_files": [{"content": "from celery.signals import after_task_publish\nimport logging\nimport os.path\nfrom envparse import env\n\nimport sys\nfrom flask import Flask, json, make_response\nfrom flask_celeryext import FlaskCeleryExt\nfrom app.settings import get_settings, get_setts\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager\nfrom flask_login import current_user\nfrom flask_jwt import JWT\nfrom datetime import timedelta\nfrom flask_cors import CORS\nfrom flask_rest_jsonapi.errors import jsonapi_errors\nfrom flask_rest_jsonapi.exceptions import JsonApiException\nfrom healthcheck import HealthCheck\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom elasticsearch_dsl.connections import connections\nfrom pytz import utc\n\nimport sqlalchemy as sa\n\nimport stripe\nfrom app.settings import get_settings\nfrom app.models import db\nfrom app.api.helpers.jwt import jwt_authenticate, jwt_identity\nfrom app.api.helpers.cache import cache\nfrom werkzeug.middleware.profiler import ProfilerMiddleware\nfrom app.views import BlueprintsManager\nfrom app.api.helpers.auth import AuthManager\nfrom app.api.helpers.scheduled_jobs import send_after_event_mail, send_event_fee_notification, \\\n    send_event_fee_notification_followup, change_session_state_on_event_completion, \\\n    expire_pending_tickets_after_three_days\nfrom app.models.event import Event\nfrom app.models.role_invite import RoleInvite\nfrom app.views.healthcheck import health_check_celery, health_check_db, health_check_migrations, check_migrations\nfrom app.views.elastic_search import client\nfrom app.views.elastic_cron_helpers import sync_events_elasticsearch, cron_rebuild_events_elasticsearch\nfrom app.views.redis_store import redis_store\nfrom app.views.celery_ import celery\nfrom app.templates.flask_ext.jinja.filters import init_filters\nimport sentry_sdk\nfrom sentry_sdk.integrations.flask import FlaskIntegration\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nstatic_dir = os.path.dirname(os.path.dirname(__file__)) + \"/static\"\ntemplate_dir = os.path.dirname(__file__) + \"/templates\"\napp = Flask(__name__, static_folder=static_dir, template_folder=template_dir)\nenv.read_envfile()\n\n\nclass ReverseProxied(object):\n    \"\"\"\n    ReverseProxied flask wsgi app wrapper from http://stackoverflow.com/a/37842465/1562480 by aldel\n    \"\"\"\n\n    def __init__(self, app):\n        self.app = app\n\n    def __call__(self, environ, start_response):\n        scheme = environ.get('HTTP_X_FORWARDED_PROTO')\n        if scheme:\n            environ['wsgi.url_scheme'] = scheme\n        if os.getenv('FORCE_SSL', 'no') == 'yes':\n            environ['wsgi.url_scheme'] = 'https'\n        return self.app(environ, start_response)\n\n\napp.wsgi_app = ReverseProxied(app.wsgi_app)\n\napp_created = False\n\n\ndef create_app():\n    global app_created\n    if not app_created:\n        BlueprintsManager.register(app)\n    Migrate(app, db)\n\n    app.config.from_object(env('APP_CONFIG', default='config.ProductionConfig'))\n    db.init_app(app)\n    _manager = Manager(app)\n    _manager.add_command('db', MigrateCommand)\n\n    if app.config['CACHING']:\n        cache.init_app(app, config={'CACHE_TYPE': 'simple'})\n    else:\n        cache.init_app(app, config={'CACHE_TYPE': 'null'})\n\n    stripe.api_key = 'SomeStripeKey'\n    app.secret_key = 'super secret key'\n    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\n    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'\n\n    app.logger.addHandler(logging.StreamHandler(sys.stdout))\n    app.logger.setLevel(logging.ERROR)\n\n    # set up jwt\n    app.config['JWT_AUTH_USERNAME_KEY'] = 'email'\n    app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)\n    app.config['JWT_AUTH_URL_RULE'] = '/auth/session'\n    _jwt = JWT(app, jwt_authenticate, jwt_identity)\n\n    # setup celery\n    app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL']\n    app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']\n    app.config['CELERY_ACCEPT_CONTENT'] = ['json', 'application/text']\n\n    CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n    AuthManager.init_login(app)\n\n    if app.config['TESTING'] and app.config['PROFILE']:\n        # Profiling\n        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])\n\n    # development api\n    with app.app_context():\n        from app.api.admin_statistics_api.events import event_statistics\n        from app.api.auth import auth_routes\n        from app.api.attendees import attendee_misc_routes\n        from app.api.bootstrap import api_v1\n        from app.api.celery_tasks import celery_routes\n        from app.api.event_copy import event_copy\n        from app.api.exports import export_routes\n        from app.api.imports import import_routes\n        from app.api.uploads import upload_routes\n        from app.api.users import user_misc_routes\n        from app.api.orders import order_misc_routes\n        from app.api.role_invites import role_invites_misc_routes\n        from app.api.auth import ticket_blueprint, authorised_blueprint\n        from app.api.admin_translations import admin_blueprint\n        from app.api.orders import alipay_blueprint\n\n        app.register_blueprint(api_v1)\n        app.register_blueprint(event_copy)\n        app.register_blueprint(upload_routes)\n        app.register_blueprint(export_routes)\n        app.register_blueprint(import_routes)\n        app.register_blueprint(celery_routes)\n        app.register_blueprint(auth_routes)\n        app.register_blueprint(event_statistics)\n        app.register_blueprint(user_misc_routes)\n        app.register_blueprint(attendee_misc_routes)\n        app.register_blueprint(order_misc_routes)\n        app.register_blueprint(role_invites_misc_routes)\n        app.register_blueprint(ticket_blueprint)\n        app.register_blueprint(authorised_blueprint)\n        app.register_blueprint(admin_blueprint)\n        app.register_blueprint(alipay_blueprint)\n\n    sa.orm.configure_mappers()\n\n    if app.config['SERVE_STATIC']:\n        app.add_url_rule('/static/<path:filename>',\n                         endpoint='static',\n                         view_func=app.send_static_file)\n\n    # sentry\n    if not app_created and 'SENTRY_DSN' in app.config:\n        sentry_sdk.init(app.config['SENTRY_DSN'], integrations=[FlaskIntegration()])\n\n    # redis\n    redis_store.init_app(app)\n\n    # elasticsearch\n    if app.config['ENABLE_ELASTICSEARCH']:\n        client.init_app(app)\n        connections.add_connection('default', client.elasticsearch)\n        with app.app_context():\n            try:\n                cron_rebuild_events_elasticsearch.delay()\n            except Exception:\n                pass\n\n    app_created = True\n    return app, _manager, db, _jwt\n\n\ncurrent_app, manager, database, jwt = create_app()\ninit_filters(app)\n\n\n# http://stackoverflow.com/questions/26724623/\n@app.before_request\ndef track_user():\n    if current_user.is_authenticated:\n        current_user.update_lat()\n\n\ndef make_celery(app=None):\n    app = app or create_app()[0]\n    celery.conf.update(app.config)\n    ext = FlaskCeleryExt(app)\n    return ext.celery\n\n\n# Health-check\nhealth = HealthCheck(current_app, \"/health-check\")\nhealth.add_check(health_check_celery)\nhealth.add_check(health_check_db)\nwith current_app.app_context():\n    current_app.config['MIGRATION_STATUS'] = check_migrations()\nhealth.add_check(health_check_migrations)\n\n\n# http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists\n@after_task_publish.connect\ndef update_sent_state(sender=None, headers=None, **kwargs):\n    # the task may not exist if sent using `send_task` which\n    # sends tasks by name, so fall back to the default result backend\n    # if that is the case.\n    task = celery.tasks.get(sender)\n    backend = task.backend if task else celery.backend\n    backend.store_result(headers['id'], None, 'WAITING')\n\n\n# register celery tasks. removing them will cause the tasks to not function. so don't remove them\n# it is important to register them after celery is defined to resolve circular imports\n\nfrom .api.helpers import tasks\n\n# import helpers.tasks\n\n\nscheduler = BackgroundScheduler(timezone=utc)\n# scheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)\n# scheduler.add_job(empty_trash, 'cron', hour=5, minute=30)\nif app.config['ENABLE_ELASTICSEARCH']:\n    scheduler.add_job(sync_events_elasticsearch, 'interval', minutes=60)\n    scheduler.add_job(cron_rebuild_events_elasticsearch, 'cron', day=7)\n\nscheduler.add_job(send_after_event_mail, 'cron', hour=5, minute=30)\nscheduler.add_job(send_event_fee_notification, 'cron', day=1)\nscheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)\nscheduler.add_job(change_session_state_on_event_completion, 'cron', hour=5, minute=30)\nscheduler.add_job(expire_pending_tickets_after_three_days, 'cron', hour=5)\nscheduler.start()\n\n\n@app.errorhandler(500)\ndef internal_server_error(error):\n    if current_app.config['PROPOGATE_ERROR'] is True:\n        exc = JsonApiException({'pointer': ''}, str(error))\n    else:\n        exc = JsonApiException({'pointer': ''}, 'Unknown error')\n    return make_response(json.dumps(jsonapi_errors([exc.to_dict()])), exc.status,\n                         {'Content-Type': 'application/vnd.api+json'})\n\n\nif __name__ == '__main__':\n    current_app.run()\n", "path": "app/__init__.py"}]}