notify-api-412 use black to enforce python coding style

This commit is contained in:
Kenneth Kehl
2023-08-25 09:12:23 -07:00
parent c6eb007386
commit 8c9721d8e2
201 changed files with 31660 additions and 28105 deletions

View File

@@ -125,27 +125,24 @@ basic_auth = CustomBasicAuth()
# The current service attached to the request stack.
current_service = LocalProxy(partial(getattr, request_ctx, 'service'))
current_service = LocalProxy(partial(getattr, request_ctx, "service"))
# The current organization attached to the request stack.
current_organization = LocalProxy(partial(getattr, request_ctx, 'organization'))
current_organization = LocalProxy(partial(getattr, request_ctx, "organization"))
navigation = {
'casework_navigation': CaseworkNavigation(),
'main_navigation': MainNavigation(),
'header_navigation': HeaderNavigation(),
'org_navigation': OrgNavigation(),
"casework_navigation": CaseworkNavigation(),
"main_navigation": MainNavigation(),
"header_navigation": HeaderNavigation(),
"org_navigation": OrgNavigation(),
}
def _csp(config):
asset_domain = config['ASSET_DOMAIN']
logo_domain = config['LOGO_CDN_DOMAIN']
asset_domain = config["ASSET_DOMAIN"]
logo_domain = config["LOGO_CDN_DOMAIN"]
return {
"default-src": [
"'self'",
asset_domain
],
"default-src": ["'self'", asset_domain],
"frame-ancestors": "'none'",
"form-action": "'self'",
"script-src": [
@@ -155,32 +152,22 @@ def _csp(config):
"https://js-agent.newrelic.com",
"https://gov-bam.nr-data.net",
],
"connect-src": [
"'self'",
"https://gov-bam.nr-data.net"
],
"style-src": [
"'self'",
asset_domain
],
"img-src": [
"'self'",
asset_domain,
logo_domain
]
"connect-src": ["'self'", "https://gov-bam.nr-data.net"],
"style-src": ["'self'", asset_domain],
"img-src": ["'self'", asset_domain, logo_domain],
}
def create_app(application):
notify_environment = os.environ['NOTIFY_ENVIRONMENT']
notify_environment = os.environ["NOTIFY_ENVIRONMENT"]
application.config.from_object(configs[notify_environment])
asset_fingerprinter._asset_root = application.config['ASSET_PATH']
asset_fingerprinter._asset_root = application.config["ASSET_PATH"]
init_app(application)
if 'extensions' not in application.jinja_options:
application.jinja_options['extensions'] = []
if "extensions" not in application.jinja_options:
application.jinja_options["extensions"] = []
init_govuk_frontend(application)
init_jinja(application)
@@ -190,7 +177,6 @@ def create_app(application):
login_manager,
proxy_fix,
request_helper,
# API clients
api_key_api_client,
billing_api_client,
@@ -212,41 +198,39 @@ def create_app(application):
template_statistics_client,
upload_api_client,
user_api_client,
# External API clients
redis_client,
zendesk_client,
):
client.init_app(application)
talisman.init_app(
application,
content_security_policy=_csp(application.config),
content_security_policy_nonce_in=['style-src', 'script-src'],
content_security_policy_nonce_in=["style-src", "script-src"],
permissions_policy={
'accelerometer': '()',
'ambient-light-sensor': '()',
'autoplay': '()',
'battery': '()',
'camera': '()',
'document-domain': '()',
'geolocation': '()',
'gyroscope': '()',
'local-fonts': '()',
'magnetometer': '()',
'microphone': '()',
'midi': '()',
'payment': '()',
'screen-wake-lock': '()'
"accelerometer": "()",
"ambient-light-sensor": "()",
"autoplay": "()",
"battery": "()",
"camera": "()",
"document-domain": "()",
"geolocation": "()",
"gyroscope": "()",
"local-fonts": "()",
"magnetometer": "()",
"microphone": "()",
"midi": "()",
"payment": "()",
"screen-wake-lock": "()",
},
frame_options='deny',
force_https=(application.config['HTTP_PROTOCOL'] == 'https')
frame_options="deny",
force_https=(application.config["HTTP_PROTOCOL"] == "https"),
)
logging.init_app(application)
login_manager.login_view = 'main.sign_in'
login_manager.login_message_category = 'default'
login_manager.login_view = "main.sign_in"
login_manager.login_message_category = "default"
login_manager.session_protection = None
login_manager.anonymous_user = AnonymousUser
@@ -276,22 +260,25 @@ def init_app(application):
application.before_request(make_session_permanent)
application.after_request(save_service_or_org_after_request)
start = len(asset_fingerprinter._filesystem_path)
font_paths = [
str(item)[len(asset_fingerprinter._filesystem_path):]
for item in pathlib.Path(asset_fingerprinter._filesystem_path).glob('fonts/*.woff2')
str(item)[start:]
for item in pathlib.Path(asset_fingerprinter._filesystem_path).glob(
"fonts/*.woff2"
)
]
@application.context_processor
def _attach_current_service():
return {'current_service': current_service}
return {"current_service": current_service}
@application.context_processor
def _attach_current_organization():
return {'current_org': current_organization}
return {"current_org": current_organization}
@application.context_processor
def _attach_current_user():
return {'current_user': current_user}
return {"current_user": current_user}
@application.context_processor
def _nav_selected():
@@ -302,10 +289,10 @@ def init_app(application):
remaining_global_messages = 0
if current_app:
global_limit = current_app.config['GLOBAL_SERVICE_MESSAGE_LIMIT']
global_limit = current_app.config["GLOBAL_SERVICE_MESSAGE_LIMIT"]
global_messages_count = service_api_client.get_global_notification_count()
remaining_global_messages = global_limit - global_messages_count
return {'daily_global_messages_remaining': remaining_global_messages}
return {"daily_global_messages_remaining": remaining_global_messages}
@application.before_request
def record_start_time():
@@ -315,16 +302,16 @@ def init_app(application):
@application.context_processor
def inject_global_template_variables():
return {
'asset_path': application.config['ASSET_PATH'],
'header_colour': application.config['HEADER_COLOUR'],
'asset_url': asset_fingerprinter.get_url,
'font_paths': font_paths,
"asset_path": application.config["ASSET_PATH"],
"header_colour": application.config["HEADER_COLOUR"],
"asset_url": asset_fingerprinter.get_url,
"font_paths": font_paths,
}
application.url_map.converters['uuid'].to_python = lambda self, value: value
application.url_map.converters['template_type'] = TemplateTypeConverter
application.url_map.converters['ticket_type'] = TicketTypeConverter
application.url_map.converters['simple_date'] = SimpleDateTypeConverter
application.url_map.converters["uuid"].to_python = lambda self, value: value
application.url_map.converters["template_type"] = TemplateTypeConverter
application.url_map.converters["ticket_type"] = TicketTypeConverter
application.url_map.converters["simple_date"] = SimpleDateTypeConverter
@login_manager.user_loader
@@ -346,21 +333,21 @@ def make_session_permanent():
def load_service_before_request():
if '/static/' in request.url:
if "/static/" in request.url:
request_ctx.service = None
return
if request_ctx is not None:
request_ctx.service = None
if request.view_args:
service_id = request.view_args.get('service_id', session.get('service_id'))
service_id = request.view_args.get("service_id", session.get("service_id"))
else:
service_id = session.get('service_id')
service_id = session.get("service_id")
if service_id:
try:
request_ctx.service = Service(
service_api_client.get_service(service_id)['data']
service_api_client.get_service(service_id)["data"]
)
except HTTPError as exc:
# if service id isn't real, then 404 rather than 500ing later because we expect service to be set
@@ -371,14 +358,14 @@ def load_service_before_request():
def load_organization_before_request():
if '/static/' in request.url:
if "/static/" in request.url:
request_ctx.organization = None
return
if request_ctx is not None:
request_ctx.organization = None
if request.view_args:
org_id = request.view_args.get('org_id')
org_id = request.view_args.get("org_id")
if org_id:
try:
@@ -393,15 +380,19 @@ def load_organization_before_request():
def save_service_or_org_after_request(response):
# Only save the current session if the request is 200
service_id = request.view_args.get('service_id', None) if request.view_args else None
organization_id = request.view_args.get('org_id', None) if request.view_args else None
service_id = (
request.view_args.get("service_id", None) if request.view_args else None
)
organization_id = (
request.view_args.get("org_id", None) if request.view_args else None
)
if response.status_code == 200:
if service_id:
session['service_id'] = service_id
session['organization_id'] = None
session["service_id"] = service_id
session["organization_id"] = None
elif organization_id:
session['service_id'] = None
session['organization_id'] = organization_id
session["service_id"] = None
session["organization_id"] = organization_id
return response
@@ -409,32 +400,38 @@ def register_errorhandlers(application): # noqa (C901 too complex)
def _error_response(error_code, error_page_template=None):
if error_page_template is None:
error_page_template = error_code
return make_response(render_template("error/{0}.html".format(error_page_template)), error_code)
return make_response(
render_template("error/{0}.html".format(error_page_template)), error_code
)
@application.errorhandler(HTTPError)
def render_http_error(error):
application.logger.warning("API {} failed with status {} message {}".format(
error.response.url if error.response else 'unknown',
error.status_code,
error.message
))
application.logger.warning(
"API {} failed with status {} message {}".format(
error.response.url if error.response else "unknown",
error.status_code,
error.message,
)
)
error_code = error.status_code
if error_code not in [401, 404, 403, 410]:
# probably a 500 or 503.
# it might be a 400, which we should handle as if it's an internal server error. If the API might
# legitimately return a 400, we should handle that within the view or the client that calls it.
application.logger.exception("API {} failed with status {} message {}".format(
error.response.url if error.response else 'unknown',
error.status_code,
error.message
))
application.logger.exception(
"API {} failed with status {} message {}".format(
error.response.url if error.response else "unknown",
error.status_code,
error.message,
)
)
error_code = 500
return _error_response(error_code)
@application.errorhandler(400)
def handle_client_error(error):
# This is tripped if we call `abort(400)`.
application.logger.exception('Unhandled 400 client error')
application.logger.exception("Unhandled 400 client error")
return _error_response(400, error_page_template=500)
@application.errorhandler(410)
@@ -456,23 +453,24 @@ def register_errorhandlers(application): # noqa (C901 too complex)
@application.errorhandler(BadSignature)
def handle_bad_token(error):
# if someone has a malformed token
flash('Theres something wrong with the link youve used.')
flash("Theres something wrong with the link youve used.")
return _error_response(404)
@application.errorhandler(CSRFError)
def handle_csrf(reason):
application.logger.warning('csrf.error_message: {}'.format(reason))
application.logger.warning("csrf.error_message: {}".format(reason))
if 'user_id' not in session:
if "user_id" not in session:
application.logger.warning(
u'csrf.session_expired: Redirecting user to log in page'
"csrf.session_expired: Redirecting user to log in page"
)
return application.login_manager.unauthorized()
application.logger.warning(
u'csrf.invalid_token: Aborting request, user_id: {user_id}',
extra={'user_id': session['user_id']})
"csrf.invalid_token: Aborting request, user_id: {user_id}",
extra={"user_id": session["user_id"]},
)
return _error_response(400, error_page_template=500)
@@ -491,14 +489,14 @@ def register_errorhandlers(application): # noqa (C901 too complex)
@application.errorhandler(InviteTokenError)
def handle_bad_invite_token(error):
flash(str(error))
return redirect(url_for('main.sign_in'))
return redirect(url_for("main.sign_in"))
@application.errorhandler(500)
@application.errorhandler(Exception)
def handle_bad_request(error):
current_app.logger.exception(error)
# We want the Flask in browser stacktrace
if current_app.config.get('DEBUG', None):
if current_app.config.get("DEBUG", None):
raise error
return _error_response(500)
@@ -561,9 +559,9 @@ def add_template_filters(application):
def init_jinja(application):
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
template_folders = [
os.path.join(repo_root, 'app/templates'),
os.path.join(repo_root, "app/templates"),
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
application.jinja_loader = jinja_loader