We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Set up logging correctly
Currently, logging is hardcoded in the app and never really used. Logging should be used almost on every action with proper label as:

- trace
- debug
- info
- warn
- error

Right now, logger is hardcoded to show ERROR only. This needs to be configurable through the command line. 

Also, I think default should be `INFO` or even `DEBUG` for the app itself and warn for other 3rd party libraries. 

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

{"golden_diff": "diff --git a/app/__init__.py b/app/__init__.py\n--- a/app/__init__.py\n+++ b/app/__init__.py\n@@ -1,4 +1,5 @@\n from celery.signals import after_task_publish\n+from logging.config import dictConfig\n import logging\n import os.path\n from envparse import env\n@@ -93,8 +94,28 @@\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+    app.logger = logging.getLogger(__name__)\n+\n+    dictConfig({\n+        'version': 1,\n+        'handlers': {\n+            'console': {\n+                'level': logging.WARN,\n+                'class': 'logging.StreamHandler',\n+                'stream': 'ext://sys.stdout'\n+            }\n+        },\n+        'loggers': {\n+            '': {\n+                'handlers': ['console'],\n+                'level': logging.WARN\n+            },\n+            'default': {\n+                'handlers': ['console'],\n+                'level': logging.INFO\n+            }\n+        }\n+    })\n \n     # set up jwt\n     app.config['JWT_AUTH_USERNAME_KEY'] = 'email'\n", "issue": "Set up logging correctly\nCurrently, logging is hardcoded in the app and never really used. Logging should be used almost on every action with proper label as:\r\n\r\n- trace\r\n- debug\r\n- info\r\n- warn\r\n- error\r\n\r\nRight now, logger is hardcoded to show ERROR only. This needs to be configurable through the command line. \r\n\r\nAlso, I think default should be `INFO` or even `DEBUG` for the app itself and warn for other 3rd party libraries. \n", "before_files": [{"content": "from celery.signals import after_task_publish\nimport logging\nimport os.path\nfrom envparse import env\nimport sys\nfrom flask import Flask, json, make_response\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, EnvironmentDump\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.contrib.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\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.sentry import sentry\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\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)\n\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\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\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.init_app(app, dsn=app.config['SENTRY_DSN'])\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    task_base = celery.Task\n\n    class ContextTask(task_base):\n        abstract = True\n\n        def __call__(self, *args, **kwargs):\n            if current_app.config['TESTING']:\n                with app.test_request_context():\n                    return task_base.__call__(self, *args, **kwargs)\n            with app.app_context():\n                return task_base.__call__(self, *args, **kwargs)\n\n    celery.Task = ContextTask\n    return celery\n\n\n# Health-check\nhealth = HealthCheck(current_app, \"/health-check\")\nenvdump = EnvironmentDump(current_app, \"/environment\", include_config=False)\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, body=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(body['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.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\nfrom logging.config import dictConfig\nimport logging\nimport os.path\nfrom envparse import env\nimport sys\nfrom flask import Flask, json, make_response\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, EnvironmentDump\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.contrib.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\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.sentry import sentry\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\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)\n\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 = logging.getLogger(__name__)\n\n    dictConfig({\n        'version': 1,\n        'handlers': {\n            'console': {\n                'level': logging.WARN,\n                'class': 'logging.StreamHandler',\n                'stream': 'ext://sys.stdout'\n            }\n        },\n        'loggers': {\n            '': {\n                'handlers': ['console'],\n                'level': logging.WARN\n            },\n            'default': {\n                'handlers': ['console'],\n                'level': logging.INFO\n            }\n        }\n    })\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\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\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.init_app(app, dsn=app.config['SENTRY_DSN'])\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    task_base = celery.Task\n\n    class ContextTask(task_base):\n        abstract = True\n\n        def __call__(self, *args, **kwargs):\n            if current_app.config['TESTING']:\n                with app.test_request_context():\n                    return task_base.__call__(self, *args, **kwargs)\n            with app.app_context():\n                return task_base.__call__(self, *args, **kwargs)\n\n    celery.Task = ContextTask\n    return celery\n\n\n# Health-check\nhealth = HealthCheck(current_app, \"/health-check\")\nenvdump = EnvironmentDump(current_app, \"/environment\", include_config=False)\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, body=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(body['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.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"}]}