We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bug: sentry cannot catch internal server errors
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
sentry cannot catch internal server errors, because api frameworks catches each and every exception

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
Based on config variable, framework should not catch exceptions and instead app should handle them and return proper error response



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `config.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 import os
3 from envparse import env
4 
5 env.read_envfile()
6 
7 basedir = os.path.abspath(os.path.dirname(__file__))
8 
9 VERSION_NAME = '2.0.0-alpha.1'
10 
11 LANGUAGES = {
12     'en': 'English',
13     'bn': 'Bengali/Bangla',
14     'zh_Hans': 'Chinese (Simplified)',
15     'zh_Hant': 'Chinese (Traditional)',
16     'fr': 'French',
17     'de': 'German',
18     'id': 'Indonesian',
19     'ko': 'Korean',
20     'pl': 'Polish',
21     'es': 'Spanish',
22     'th': 'Thai',
23     'vi': 'Vietnamese',
24     'hi': 'Hindi',
25     'ja': 'Japanese',
26     'ru': 'Russian',
27 }
28 
29 
30 class Config(object):
31     """
32     The base configuration option. Contains the defaults.
33     """
34 
35     DEBUG = False
36 
37     DEVELOPMENT = False
38     STAGING = False
39     PRODUCTION = False
40     TESTING = False
41 
42     CACHING = False
43     PROFILE = False
44     SQLALCHEMY_RECORD_QUERIES = False
45 
46     FLASK_ADMIN_SWATCH = 'lumen'
47 
48     VERSION = VERSION_NAME
49     SQLALCHEMY_TRACK_MODIFICATIONS = True
50     ERROR_404_HELP = False
51     CSRF_ENABLED = True
52     SERVER_NAME = env('SERVER_NAME', default=None)
53     CORS_HEADERS = 'Content-Type'
54     SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)
55     SERVE_STATIC = env.bool('SERVE_STATIC', default=False)
56     DATABASE_QUERY_TIMEOUT = 0.1
57     SOFT_DELETE = True
58     PROPOGATE_ERROR = env.bool('PROPOGATE_ERROR', default=False)
59     DASHERIZE_API = True
60     ETAG = True
61     SENTRY_DSN = env('SENTRY_DSN', default=None)
62 
63     if not SQLALCHEMY_DATABASE_URI:
64         print('`DATABASE_URL` either not exported or empty')
65         exit()
66 
67     BASE_DIR = basedir
68     FORCE_SSL = os.getenv('FORCE_SSL', 'no') == 'yes'
69 
70     if SERVE_STATIC:
71         UPLOADS_FOLDER = BASE_DIR + '/static/uploads/'
72         TEMP_UPLOADS_FOLDER = BASE_DIR + '/static/uploads/temp/'
73         UPLOAD_FOLDER = UPLOADS_FOLDER
74         STATIC_URL = '/static/'
75         STATIC_ROOT = 'staticfiles'
76         STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
77 
78     if FORCE_SSL:
79         PREFERRED_URL_SCHEME = 'https'
80 
81 
82 class ProductionConfig(Config):
83     """
84     The configuration for a production environment
85     """
86 
87     MINIFY_PAGE = True
88     PRODUCTION = True
89     CACHING = True
90 
91     # if force on
92 
93 
94 class StagingConfig(ProductionConfig):
95     """
96     The configuration for a staging environment
97     """
98 
99     PRODUCTION = False
100     STAGING = True
101 
102 
103 class DevelopmentConfig(Config):
104     """
105     The configuration for a development environment
106     """
107 
108     DEVELOPMENT = True
109     DEBUG = True
110     CACHING = True
111     PROPOGATE_ERROR = True
112 
113     # Test database performance
114     SQLALCHEMY_RECORD_QUERIES = True
115 
116 
117 class TestingConfig(Config):
118     """
119     The configuration for a test suit
120     """
121     TESTING = True
122     CELERY_ALWAYS_EAGER = True
123     CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
124     SQLALCHEMY_RECORD_QUERIES = True
125     DEBUG_TB_ENABLED = False
126     BROKER_BACKEND = 'memory'
127     SQLALCHEMY_DATABASE_URI = env('TEST_DATABASE_URL', default=None)
128     PROPOGATE_ERROR = True
129
```

Path: `app/__init__.py`
Content:
```
1 # Ignore ExtDeprecationWarnings for Flask 0.11 - see http://stackoverflow.com/a/38080580
2 import warnings
3 from flask.exthook import ExtDeprecationWarning
4 
5 warnings.simplefilter('ignore', ExtDeprecationWarning)
6 # Keep it before flask extensions are imported
7 
8 from pytz import utc
9 
10 from app.helpers.scheduled_jobs import send_mail_to_expired_orders, empty_trash, send_after_event_mail, \
11     send_event_fee_notification, send_event_fee_notification_followup
12 
13 from celery import Celery
14 from celery.signals import after_task_publish
15 import logging
16 import os.path
17 from os import environ
18 from envparse import env
19 import sys
20 from flask import Flask
21 from app.settings import get_settings, get_setts
22 from flask_migrate import Migrate, MigrateCommand
23 from flask_script import Manager
24 from flask_login import current_user
25 from flask_jwt import JWT
26 from datetime import timedelta
27 from flask_cors import CORS
28 from raven.contrib.flask import Sentry
29 
30 import sqlalchemy as sa
31 
32 import stripe
33 from app.settings import get_settings
34 from app.helpers.flask_ext.helpers import SilentUndefined, camel_case, slugify, MiniJSONEncoder
35 from app.helpers.payment import forex
36 from app.models import db
37 from app.models.user import User
38 from app.models.event import Event
39 from app.models.session import Session
40 from app.api.helpers.jwt import jwt_authenticate, jwt_identity
41 from helpers.formatter import operation_name
42 from app.helpers.data_getter import DataGetter
43 from app.helpers.flask_ext.errors import NotFoundError, PermissionDeniedError, ServerError, ValidationError
44 from apscheduler.schedulers.background import BackgroundScheduler
45 from app.helpers.data import DataManager, delete_from_db
46 from app.helpers.helpers import send_after_event
47 from app.helpers.cache import cache
48 from helpers.helpers import send_email_for_expired_orders
49 from werkzeug.contrib.profiler import ProfilerMiddleware
50 from app.views import BlueprintsManager
51 from app.helpers.auth import AuthManager
52 
53 
54 BASE_DIR = os.path.dirname(os.path.abspath(__file__))
55 
56 app = Flask(__name__)
57 
58 env.read_envfile()
59 
60 
61 class ReverseProxied(object):
62     """
63     ReverseProxied flask wsgi app wrapper from http://stackoverflow.com/a/37842465/1562480 by aldel
64     """
65 
66     def __init__(self, app):
67         self.app = app
68 
69     def __call__(self, environ, start_response):
70         scheme = environ.get('HTTP_X_FORWARDED_PROTO')
71         if scheme:
72             environ['wsgi.url_scheme'] = scheme
73         if os.getenv('FORCE_SSL', 'no') == 'yes':
74             environ['wsgi.url_scheme'] = 'https'
75         return self.app(environ, start_response)
76 
77 
78 app.wsgi_app = ReverseProxied(app.wsgi_app)
79 
80 
81 def create_app():
82     BlueprintsManager.register(app)
83     Migrate(app, db)
84 
85     app.config.from_object(env('APP_CONFIG', default='config.ProductionConfig'))
86     db.init_app(app)
87     _manager = Manager(app)
88     _manager.add_command('db', MigrateCommand)
89 
90     if app.config['CACHING']:
91         cache.init_app(app, config={'CACHE_TYPE': 'simple'})
92     else:
93         cache.init_app(app, config={'CACHE_TYPE': 'null'})
94 
95     stripe.api_key = 'SomeStripeKey'
96     app.secret_key = 'super secret key'
97     app.json_encoder = MiniJSONEncoder
98     app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
99     app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
100 
101     app.logger.addHandler(logging.StreamHandler(sys.stdout))
102     app.logger.setLevel(logging.ERROR)
103     app.jinja_env.add_extension('jinja2.ext.do')
104     app.jinja_env.add_extension('jinja2.ext.loopcontrols')
105     app.jinja_env.undefined = SilentUndefined
106     app.jinja_env.filters['operation_name'] = operation_name
107 
108     # set up jwt
109     app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
110     app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)
111     app.config['JWT_AUTH_URL_RULE'] = '/auth/session'
112     _jwt = JWT(app, jwt_authenticate, jwt_identity)
113 
114     # setup celery
115     app.config['CELERY_BROKER_URL'] = environ.get('REDIS_URL', 'redis://localhost:6379/0')
116     app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']
117 
118     CORS(app, resources={r"/*": {"origins": "*"}})
119     AuthManager.init_login(app)
120 
121     if app.config['TESTING'] and app.config['PROFILE']:
122         # Profiling
123         app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
124 
125     # nextgen api
126     with app.app_context():
127         from app.api.bootstrap import api_v1
128         from app.api.uploads import upload_routes
129         app.register_blueprint(api_v1)
130         app.register_blueprint(upload_routes)
131 
132     sa.orm.configure_mappers()
133 
134     if app.config['SERVE_STATIC']:
135         app.add_url_rule('/static/<path:filename>',
136                          endpoint='static',
137                          view_func=app.send_static_file)
138 
139     # sentry
140     if app.config['SENTRY_DSN']:
141         sentry = Sentry(dsn=app.config['SENTRY_DSN'])
142         sentry.init_app(app)
143 
144     return app, _manager, db, _jwt
145 
146 
147 current_app, manager, database, jwt = create_app()
148 
149 
150 # http://stackoverflow.com/questions/26724623/
151 @app.before_request
152 def track_user():
153     if current_user.is_authenticated:
154         current_user.update_lat()
155 
156 
157 def make_celery(app):
158     celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
159     celery.conf.update(app.config)
160     task_base = celery.Task
161 
162     class ContextTask(task_base):
163         abstract = True
164 
165         def __call__(self, *args, **kwargs):
166             if current_app.config['TESTING']:
167                 with app.test_request_context():
168                     return task_base.__call__(self, *args, **kwargs)
169             with app.app_context():
170                 return task_base.__call__(self, *args, **kwargs)
171 
172     celery.Task = ContextTask
173     return celery
174 
175 
176 celery = make_celery(current_app)
177 
178 
179 # http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists
180 @after_task_publish.connect
181 def update_sent_state(sender=None, body=None, **kwargs):
182     # the task may not exist if sent using `send_task` which
183     # sends tasks by name, so fall back to the default result backend
184     # if that is the case.
185     task = celery.tasks.get(sender)
186     backend = task.backend if task else celery.backend
187     backend.store_result(body['id'], None, 'WAITING')
188 
189 
190 # register celery tasks. removing them will cause the tasks to not function. so don't remove them
191 # it is important to register them after celery is defined to resolve circular imports
192 
193 #import api.helpers.tasks
194 import helpers.tasks
195 
196 
197 scheduler = BackgroundScheduler(timezone=utc)
198 scheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)
199 scheduler.add_job(empty_trash, 'cron', hour=5, minute=30)
200 scheduler.add_job(send_after_event_mail, 'cron', hour=5, minute=30)
201 scheduler.add_job(send_event_fee_notification, 'cron', day=1)
202 scheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)
203 scheduler.start()
204 
205 if __name__ == '__main__':
206     current_app.run()
207
```
--- 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
@@ -17,7 +17,7 @@
 from os import environ
 from envparse import env
 import sys
-from flask import Flask
+from flask import Flask, json, make_response
 from app.settings import get_settings, get_setts
 from flask_migrate import Migrate, MigrateCommand
 from flask_script import Manager
@@ -26,6 +26,8 @@
 from datetime import timedelta
 from flask_cors import CORS
 from raven.contrib.flask import Sentry
+from flask_rest_jsonapi.errors import jsonapi_errors
+from flask_rest_jsonapi.exceptions import JsonApiException
 
 import sqlalchemy as sa
 
@@ -202,5 +204,16 @@
 scheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)
 scheduler.start()
 
+
+@app.errorhandler(500)
+def internal_server_error(error):
+    if current_app.config['PROPOGATE_ERROR'] is True:
+        exc = JsonApiException({'pointer': ''}, str(error))
+    else:
+        exc = JsonApiException({'pointer': ''}, 'Unknown error')
+    return make_response(json.dumps(jsonapi_errors([exc.to_dict()])), exc.status,
+                         {'Content-Type': 'application/vnd.api+json'})
+
+
 if __name__ == '__main__':
     current_app.run()
diff --git a/config.py b/config.py
--- a/config.py
+++ b/config.py
@@ -54,11 +54,14 @@
     SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)
     SERVE_STATIC = env.bool('SERVE_STATIC', default=False)
     DATABASE_QUERY_TIMEOUT = 0.1
+    SENTRY_DSN = env('SENTRY_DSN', default=None)
+
+    # API configs
     SOFT_DELETE = True
     PROPOGATE_ERROR = env.bool('PROPOGATE_ERROR', default=False)
     DASHERIZE_API = True
+    API_PROPOGATE_UNCAUGHT_EXCEPTIONS = env.bool('API_PROPOGATE_UNCAUGHT_EXCEPTIONS', default=True)
     ETAG = True
-    SENTRY_DSN = env('SENTRY_DSN', default=None)
 
     if not SQLALCHEMY_DATABASE_URI:
         print('`DATABASE_URL` either not exported or empty')

{"golden_diff": "diff --git a/app/__init__.py b/app/__init__.py\n--- a/app/__init__.py\n+++ b/app/__init__.py\n@@ -17,7 +17,7 @@\n from os import environ\n from envparse import env\n import sys\n-from flask import Flask\n+from flask import Flask, json, make_response\n from app.settings import get_settings, get_setts\n from flask_migrate import Migrate, MigrateCommand\n from flask_script import Manager\n@@ -26,6 +26,8 @@\n from datetime import timedelta\n from flask_cors import CORS\n from raven.contrib.flask import Sentry\n+from flask_rest_jsonapi.errors import jsonapi_errors\n+from flask_rest_jsonapi.exceptions import JsonApiException\n \n import sqlalchemy as sa\n \n@@ -202,5 +204,16 @@\n scheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)\n scheduler.start()\n \n+\n+@app.errorhandler(500)\n+def 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+\n if __name__ == '__main__':\n     current_app.run()\ndiff --git a/config.py b/config.py\n--- a/config.py\n+++ b/config.py\n@@ -54,11 +54,14 @@\n     SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)\n     SERVE_STATIC = env.bool('SERVE_STATIC', default=False)\n     DATABASE_QUERY_TIMEOUT = 0.1\n+    SENTRY_DSN = env('SENTRY_DSN', default=None)\n+\n+    # API configs\n     SOFT_DELETE = True\n     PROPOGATE_ERROR = env.bool('PROPOGATE_ERROR', default=False)\n     DASHERIZE_API = True\n+    API_PROPOGATE_UNCAUGHT_EXCEPTIONS = env.bool('API_PROPOGATE_UNCAUGHT_EXCEPTIONS', default=True)\n     ETAG = True\n-    SENTRY_DSN = env('SENTRY_DSN', default=None)\n \n     if not SQLALCHEMY_DATABASE_URI:\n         print('`DATABASE_URL` either not exported or empty')\n", "issue": "Bug: sentry cannot catch internal server errors\n**I'm submitting a ...**  (check one with \"x\")\r\n- [x] bug report\r\n- [ ] feature request\r\n- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server\r\n\r\n**Current behavior:**\r\n<!-- Describe how the bug manifests. -->\r\nsentry cannot catch internal server errors, because api frameworks catches each and every exception\r\n\r\n**Expected behavior:**\r\n<!-- Describe what the behavior would be without the bug. -->\r\nBased on config variable, framework should not catch exceptions and instead app should handle them and return proper error response\r\n\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nimport os\nfrom envparse import env\n\nenv.read_envfile()\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nVERSION_NAME = '2.0.0-alpha.1'\n\nLANGUAGES = {\n    'en': 'English',\n    'bn': 'Bengali/Bangla',\n    'zh_Hans': 'Chinese (Simplified)',\n    'zh_Hant': 'Chinese (Traditional)',\n    'fr': 'French',\n    'de': 'German',\n    'id': 'Indonesian',\n    'ko': 'Korean',\n    'pl': 'Polish',\n    'es': 'Spanish',\n    'th': 'Thai',\n    'vi': 'Vietnamese',\n    'hi': 'Hindi',\n    'ja': 'Japanese',\n    'ru': 'Russian',\n}\n\n\nclass Config(object):\n    \"\"\"\n    The base configuration option. Contains the defaults.\n    \"\"\"\n\n    DEBUG = False\n\n    DEVELOPMENT = False\n    STAGING = False\n    PRODUCTION = False\n    TESTING = False\n\n    CACHING = False\n    PROFILE = False\n    SQLALCHEMY_RECORD_QUERIES = False\n\n    FLASK_ADMIN_SWATCH = 'lumen'\n\n    VERSION = VERSION_NAME\n    SQLALCHEMY_TRACK_MODIFICATIONS = True\n    ERROR_404_HELP = False\n    CSRF_ENABLED = True\n    SERVER_NAME = env('SERVER_NAME', default=None)\n    CORS_HEADERS = 'Content-Type'\n    SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)\n    SERVE_STATIC = env.bool('SERVE_STATIC', default=False)\n    DATABASE_QUERY_TIMEOUT = 0.1\n    SOFT_DELETE = True\n    PROPOGATE_ERROR = env.bool('PROPOGATE_ERROR', default=False)\n    DASHERIZE_API = True\n    ETAG = True\n    SENTRY_DSN = env('SENTRY_DSN', default=None)\n\n    if not SQLALCHEMY_DATABASE_URI:\n        print('`DATABASE_URL` either not exported or empty')\n        exit()\n\n    BASE_DIR = basedir\n    FORCE_SSL = os.getenv('FORCE_SSL', 'no') == 'yes'\n\n    if SERVE_STATIC:\n        UPLOADS_FOLDER = BASE_DIR + '/static/uploads/'\n        TEMP_UPLOADS_FOLDER = BASE_DIR + '/static/uploads/temp/'\n        UPLOAD_FOLDER = UPLOADS_FOLDER\n        STATIC_URL = '/static/'\n        STATIC_ROOT = 'staticfiles'\n        STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)\n\n    if FORCE_SSL:\n        PREFERRED_URL_SCHEME = 'https'\n\n\nclass ProductionConfig(Config):\n    \"\"\"\n    The configuration for a production environment\n    \"\"\"\n\n    MINIFY_PAGE = True\n    PRODUCTION = True\n    CACHING = True\n\n    # if force on\n\n\nclass StagingConfig(ProductionConfig):\n    \"\"\"\n    The configuration for a staging environment\n    \"\"\"\n\n    PRODUCTION = False\n    STAGING = True\n\n\nclass DevelopmentConfig(Config):\n    \"\"\"\n    The configuration for a development environment\n    \"\"\"\n\n    DEVELOPMENT = True\n    DEBUG = True\n    CACHING = True\n    PROPOGATE_ERROR = True\n\n    # Test database performance\n    SQLALCHEMY_RECORD_QUERIES = True\n\n\nclass TestingConfig(Config):\n    \"\"\"\n    The configuration for a test suit\n    \"\"\"\n    TESTING = True\n    CELERY_ALWAYS_EAGER = True\n    CELERY_EAGER_PROPAGATES_EXCEPTIONS = True\n    SQLALCHEMY_RECORD_QUERIES = True\n    DEBUG_TB_ENABLED = False\n    BROKER_BACKEND = 'memory'\n    SQLALCHEMY_DATABASE_URI = env('TEST_DATABASE_URL', default=None)\n    PROPOGATE_ERROR = True\n", "path": "config.py"}, {"content": "# Ignore ExtDeprecationWarnings for Flask 0.11 - see http://stackoverflow.com/a/38080580\nimport warnings\nfrom flask.exthook import ExtDeprecationWarning\n\nwarnings.simplefilter('ignore', ExtDeprecationWarning)\n# Keep it before flask extensions are imported\n\nfrom pytz import utc\n\nfrom app.helpers.scheduled_jobs import send_mail_to_expired_orders, empty_trash, send_after_event_mail, \\\n    send_event_fee_notification, send_event_fee_notification_followup\n\nfrom celery import Celery\nfrom celery.signals import after_task_publish\nimport logging\nimport os.path\nfrom os import environ\nfrom envparse import env\nimport sys\nfrom flask import Flask\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 raven.contrib.flask import Sentry\n\nimport sqlalchemy as sa\n\nimport stripe\nfrom app.settings import get_settings\nfrom app.helpers.flask_ext.helpers import SilentUndefined, camel_case, slugify, MiniJSONEncoder\nfrom app.helpers.payment import forex\nfrom app.models import db\nfrom app.models.user import User\nfrom app.models.event import Event\nfrom app.models.session import Session\nfrom app.api.helpers.jwt import jwt_authenticate, jwt_identity\nfrom helpers.formatter import operation_name\nfrom app.helpers.data_getter import DataGetter\nfrom app.helpers.flask_ext.errors import NotFoundError, PermissionDeniedError, ServerError, ValidationError\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom app.helpers.data import DataManager, delete_from_db\nfrom app.helpers.helpers import send_after_event\nfrom app.helpers.cache import cache\nfrom helpers.helpers import send_email_for_expired_orders\nfrom werkzeug.contrib.profiler import ProfilerMiddleware\nfrom app.views import BlueprintsManager\nfrom app.helpers.auth import AuthManager\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\napp = Flask(__name__)\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\n\ndef create_app():\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.json_encoder = MiniJSONEncoder\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.jinja_env.add_extension('jinja2.ext.do')\n    app.jinja_env.add_extension('jinja2.ext.loopcontrols')\n    app.jinja_env.undefined = SilentUndefined\n    app.jinja_env.filters['operation_name'] = operation_name\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'] = environ.get('REDIS_URL', 'redis://localhost:6379/0')\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    # nextgen api\n    with app.app_context():\n        from app.api.bootstrap import api_v1\n        from app.api.uploads import upload_routes\n        app.register_blueprint(api_v1)\n        app.register_blueprint(upload_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 app.config['SENTRY_DSN']:\n        sentry = Sentry(dsn=app.config['SENTRY_DSN'])\n        sentry.init_app(app)\n\n    return app, _manager, db, _jwt\n\n\ncurrent_app, manager, database, jwt = create_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):\n    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])\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\ncelery = make_celery(current_app)\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\n#import api.helpers.tasks\nimport helpers.tasks\n\n\nscheduler = BackgroundScheduler(timezone=utc)\nscheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)\nscheduler.add_job(empty_trash, 'cron', hour=5, minute=30)\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\nif __name__ == '__main__':\n    current_app.run()\n", "path": "app/__init__.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nimport os\nfrom envparse import env\n\nenv.read_envfile()\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nVERSION_NAME = '2.0.0-alpha.1'\n\nLANGUAGES = {\n    'en': 'English',\n    'bn': 'Bengali/Bangla',\n    'zh_Hans': 'Chinese (Simplified)',\n    'zh_Hant': 'Chinese (Traditional)',\n    'fr': 'French',\n    'de': 'German',\n    'id': 'Indonesian',\n    'ko': 'Korean',\n    'pl': 'Polish',\n    'es': 'Spanish',\n    'th': 'Thai',\n    'vi': 'Vietnamese',\n    'hi': 'Hindi',\n    'ja': 'Japanese',\n    'ru': 'Russian',\n}\n\n\nclass Config(object):\n    \"\"\"\n    The base configuration option. Contains the defaults.\n    \"\"\"\n\n    DEBUG = False\n\n    DEVELOPMENT = False\n    STAGING = False\n    PRODUCTION = False\n    TESTING = False\n\n    CACHING = False\n    PROFILE = False\n    SQLALCHEMY_RECORD_QUERIES = False\n\n    FLASK_ADMIN_SWATCH = 'lumen'\n\n    VERSION = VERSION_NAME\n    SQLALCHEMY_TRACK_MODIFICATIONS = True\n    ERROR_404_HELP = False\n    CSRF_ENABLED = True\n    SERVER_NAME = env('SERVER_NAME', default=None)\n    CORS_HEADERS = 'Content-Type'\n    SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)\n    SERVE_STATIC = env.bool('SERVE_STATIC', default=False)\n    DATABASE_QUERY_TIMEOUT = 0.1\n    SENTRY_DSN = env('SENTRY_DSN', default=None)\n\n    # API configs\n    SOFT_DELETE = True\n    PROPOGATE_ERROR = env.bool('PROPOGATE_ERROR', default=False)\n    DASHERIZE_API = True\n    API_PROPOGATE_UNCAUGHT_EXCEPTIONS = env.bool('API_PROPOGATE_UNCAUGHT_EXCEPTIONS', default=True)\n    ETAG = True\n\n    if not SQLALCHEMY_DATABASE_URI:\n        print('`DATABASE_URL` either not exported or empty')\n        exit()\n\n    BASE_DIR = basedir\n    FORCE_SSL = os.getenv('FORCE_SSL', 'no') == 'yes'\n\n    if SERVE_STATIC:\n        UPLOADS_FOLDER = BASE_DIR + '/static/uploads/'\n        TEMP_UPLOADS_FOLDER = BASE_DIR + '/static/uploads/temp/'\n        UPLOAD_FOLDER = UPLOADS_FOLDER\n        STATIC_URL = '/static/'\n        STATIC_ROOT = 'staticfiles'\n        STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)\n\n    if FORCE_SSL:\n        PREFERRED_URL_SCHEME = 'https'\n\n\nclass ProductionConfig(Config):\n    \"\"\"\n    The configuration for a production environment\n    \"\"\"\n\n    MINIFY_PAGE = True\n    PRODUCTION = True\n    CACHING = True\n\n    # if force on\n\n\nclass StagingConfig(ProductionConfig):\n    \"\"\"\n    The configuration for a staging environment\n    \"\"\"\n\n    PRODUCTION = False\n    STAGING = True\n\n\nclass DevelopmentConfig(Config):\n    \"\"\"\n    The configuration for a development environment\n    \"\"\"\n\n    DEVELOPMENT = True\n    DEBUG = True\n    CACHING = True\n    PROPOGATE_ERROR = True\n\n    # Test database performance\n    SQLALCHEMY_RECORD_QUERIES = True\n\n\nclass TestingConfig(Config):\n    \"\"\"\n    The configuration for a test suit\n    \"\"\"\n    TESTING = True\n    CELERY_ALWAYS_EAGER = True\n    CELERY_EAGER_PROPAGATES_EXCEPTIONS = True\n    SQLALCHEMY_RECORD_QUERIES = True\n    DEBUG_TB_ENABLED = False\n    BROKER_BACKEND = 'memory'\n    SQLALCHEMY_DATABASE_URI = env('TEST_DATABASE_URL', default=None)\n    PROPOGATE_ERROR = True\n", "path": "config.py"}, {"content": "# Ignore ExtDeprecationWarnings for Flask 0.11 - see http://stackoverflow.com/a/38080580\nimport warnings\nfrom flask.exthook import ExtDeprecationWarning\n\nwarnings.simplefilter('ignore', ExtDeprecationWarning)\n# Keep it before flask extensions are imported\n\nfrom pytz import utc\n\nfrom app.helpers.scheduled_jobs import send_mail_to_expired_orders, empty_trash, send_after_event_mail, \\\n    send_event_fee_notification, send_event_fee_notification_followup\n\nfrom celery import Celery\nfrom celery.signals import after_task_publish\nimport logging\nimport os.path\nfrom os import environ\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 raven.contrib.flask import Sentry\nfrom flask_rest_jsonapi.errors import jsonapi_errors\nfrom flask_rest_jsonapi.exceptions import JsonApiException\n\nimport sqlalchemy as sa\n\nimport stripe\nfrom app.settings import get_settings\nfrom app.helpers.flask_ext.helpers import SilentUndefined, camel_case, slugify, MiniJSONEncoder\nfrom app.helpers.payment import forex\nfrom app.models import db\nfrom app.models.user import User\nfrom app.models.event import Event\nfrom app.models.session import Session\nfrom app.api.helpers.jwt import jwt_authenticate, jwt_identity\nfrom helpers.formatter import operation_name\nfrom app.helpers.data_getter import DataGetter\nfrom app.helpers.flask_ext.errors import NotFoundError, PermissionDeniedError, ServerError, ValidationError\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom app.helpers.data import DataManager, delete_from_db\nfrom app.helpers.helpers import send_after_event\nfrom app.helpers.cache import cache\nfrom helpers.helpers import send_email_for_expired_orders\nfrom werkzeug.contrib.profiler import ProfilerMiddleware\nfrom app.views import BlueprintsManager\nfrom app.helpers.auth import AuthManager\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\napp = Flask(__name__)\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\n\ndef create_app():\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.json_encoder = MiniJSONEncoder\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.jinja_env.add_extension('jinja2.ext.do')\n    app.jinja_env.add_extension('jinja2.ext.loopcontrols')\n    app.jinja_env.undefined = SilentUndefined\n    app.jinja_env.filters['operation_name'] = operation_name\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'] = environ.get('REDIS_URL', 'redis://localhost:6379/0')\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    # nextgen api\n    with app.app_context():\n        from app.api.bootstrap import api_v1\n        from app.api.uploads import upload_routes\n        app.register_blueprint(api_v1)\n        app.register_blueprint(upload_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 app.config['SENTRY_DSN']:\n        sentry = Sentry(dsn=app.config['SENTRY_DSN'])\n        sentry.init_app(app)\n\n    return app, _manager, db, _jwt\n\n\ncurrent_app, manager, database, jwt = create_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):\n    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])\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\ncelery = make_celery(current_app)\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\n#import api.helpers.tasks\nimport helpers.tasks\n\n\nscheduler = BackgroundScheduler(timezone=utc)\nscheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)\nscheduler.add_job(empty_trash, 'cron', hour=5, minute=30)\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"}]}