Skip to content

Commit

Permalink
isort and black changes
Browse files Browse the repository at this point in the history
  • Loading branch information
turb0c0w committed Apr 30, 2024
1 parent 7ac7e18 commit 0310ec5
Show file tree
Hide file tree
Showing 28 changed files with 279 additions and 270 deletions.
8 changes: 4 additions & 4 deletions strr-api/gunicorn_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

import os

workers = int(os.environ.get('GUNICORN_PROCESSES', '1')) # pylint: disable=invalid-name
threads = int(os.environ.get('GUNICORN_THREADS', '1')) # pylint: disable=invalid-name
workers = int(os.environ.get("GUNICORN_PROCESSES", "1")) # pylint: disable=invalid-name
threads = int(os.environ.get("GUNICORN_THREADS", "1")) # pylint: disable=invalid-name

forwarded_allow_ips = '*' # pylint: disable=invalid-name
secure_scheme_headers = {'X-Forwarded-Proto': 'https'} # pylint: disable=invalid-name
forwarded_allow_ips = "*" # pylint: disable=invalid-name
secure_scheme_headers = {"X-Forwarded-Proto": "https"} # pylint: disable=invalid-name
36 changes: 20 additions & 16 deletions strr-api/src/strr_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@
This module is the API for the Legal Entity system.
"""
import os
import logging
import logging.config
import os

import coloredlogs
import sentry_sdk
from flask_cors import CORS
from sentry_sdk.integrations.flask import FlaskIntegration
from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate, upgrade
from sentry_sdk.integrations.flask import FlaskIntegration

from .common.auth import jwt
from .common.flags import Flags
from .common.run_version import get_run_version
Expand All @@ -56,7 +58,7 @@
# logging.config.fileConfig(fname=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logging.conf'))
logging.basicConfig(level=logging.DEBUG)
coloredlogs.install()
logger = logging.getLogger('api')
logger = logging.getLogger("api")


def create_app(environment: Config = Production, **kwargs) -> Flask:
Expand All @@ -67,53 +69,55 @@ def create_app(environment: Config = Production, **kwargs) -> Flask:
app.logger.setLevel(logging.DEBUG)

# Configure Sentry
if dsn := app.config.get('SENTRY_DSN', None):
if dsn := app.config.get("SENTRY_DSN", None):
sentry_sdk.init(
dsn=dsn,
integrations=[FlaskIntegration()],
release=f'strr-api@{get_run_version()}',
release=f"strr-api@{get_run_version()}",
send_default_pii=False,
environment=app.config.get('POD_NAMESPACE', 'unknown')
environment=app.config.get("POD_NAMESPACE", "unknown"),
)

db.init_app(app)

if not app.config.get('TESTING', False):
if not app.config.get("TESTING", False):
Migrate(app, db)
logger.info('Running migration upgrade.')
logger.info("Running migration upgrade.")
with app.app_context():
upgrade(directory='migrations', revision='head', sql=False, tag=None)
upgrade(directory="migrations", revision="head", sql=False, tag=None)

strr_pay.init_app(app)
# td is testData instance passed in to support testing
td = kwargs.get('ld_test_data', None)
td = kwargs.get("ld_test_data", None)
Flags().init_app(app, td)
babel.init_app(app)
register_endpoints(app)
setup_jwt_manager(app, jwt)

@app.before_request
def before_request(): # pylint: disable=unused-variable
flag_name = os.getenv('OPS_LOGGER_LEVEL_FLAG', None)
flag_name = os.getenv("OPS_LOGGER_LEVEL_FLAG", None)
if flag_name:
flag_value = Flags.value(flag_name)
if (level_name := logging.getLevelName(logging.getLogger().level)) and flag_value != level_name:
logger.error('Logger level is %s, setting to %s', level_name, flag_value)
logger.error("Logger level is %s, setting to %s", level_name, flag_value)
logging.getLogger().setLevel(level=flag_value)

@app.after_request
def add_version(response): # pylint: disable=unused-variable
version = get_run_version()
response.headers['API'] = f'strr-api/{version}'
response.headers["API"] = f"strr-api/{version}"
return response

return app


def setup_jwt_manager(app, jwt_manager):
"""Use flask app to configure the JWTManager to work for a particular Realm."""

def get_roles(a_dict):
return a_dict['realm_access']['roles'] # pragma: no cover
app.config['JWT_ROLE_CALLBACK'] = get_roles
return a_dict["realm_access"]["roles"] # pragma: no cover

app.config["JWT_ROLE_CALLBACK"] = get_roles

jwt_manager.init_app(app)
1 change: 0 additions & 1 deletion strr-api/src/strr_api/common/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,4 @@
"""Bring in the common JWT Manager."""
from flask_jwt_oidc import JwtManager


jwt = JwtManager() # pylint: disable=invalid-name; lower case name as used by convention in most Flask apps
3 changes: 1 addition & 2 deletions strr-api/src/strr_api/common/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@
# POSSIBILITY OF SUCH DAMAGE.
"""Enum Utilities."""
from enum import auto # noqa: F401 pylint: disable=W0611
from enum import Enum
from enum import EnumMeta
from enum import Enum, EnumMeta
from typing import Optional


Expand Down
3 changes: 1 addition & 2 deletions strr-api/src/strr_api/common/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@
from werkzeug.exceptions import HTTPException
from werkzeug.routing import RoutingException


logger = logging.getLogger('api')
logger = logging.getLogger("api")


def init_app(app):
Expand Down
39 changes: 19 additions & 20 deletions strr-api/src/strr_api/common/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,22 +38,20 @@
from typing import Union

import ldclient
from flask import Flask, current_app, has_app_context
from ldclient import Config, Context, LDClient
from ldclient.integrations.test_data import TestData
from flask import current_app
from flask import has_app_context
from flask import Flask

import strr_api


class Flags():
class Flags:
"""Wrapper around the feature flag system.
1 client per application.
"""

COMPONENT_NAME = 'featureflags'
COMPONENT_NAME = "featureflags"

def __init__(self, app: Flask = None):
"""Initialize this object."""
Expand All @@ -69,10 +67,10 @@ def init_app(self, app: Flask, td: TestData = None):
Provide TD for TestData.
"""
self.app = app
self.sdk_key = app.config.get('LD_SDK_KEY')
self.sdk_key = app.config.get("LD_SDK_KEY")

if td:
client = LDClient(config=Config('testing', update_processor_class=td))
client = LDClient(config=Config("testing", update_processor_class=td))
elif self.sdk_key:
ldclient.set_config(Config(self.sdk_key))
client = ldclient.get()
Expand All @@ -84,7 +82,7 @@ def init_app(self, app: Flask, td: TestData = None):
app.teardown_appcontext(self.teardown)
except Exception as err: # noqa: B903
if app and has_app_context():
app.logger.warn('issue registering flag service', err)
app.logger.warn("issue registering flag service", err)

def teardown(self, exception): # pylint: disable=unused-argument,useless-option-value; flask method signature
"""Destroy all objects created by this extension.
Expand Down Expand Up @@ -112,22 +110,23 @@ def get_flag_context(user: strr_api.models.User, account_id: int = None) -> Cont
"""Convert User into a Flag user dict."""
if isinstance(user, strr_api.models.User):
user_ctx = Context(
kind='user',
kind="user",
key=user.sub,
attributes={
'firstName': user.firstname,
'lastName': user.lastname,
'email': user.email,
'loginSource': user.login_source
})
"firstName": user.firstname,
"lastName": user.lastname,
"email": user.email,
"loginSource": user.login_source,
},
)
return Context(
kind='multi',
key='',
kind="multi",
key="",
allow_empty_key=True,
multi_contexts=[
user_ctx or Context(kind='user', key='anonymous'),
Context(kind='org', key=str(account_id) if account_id else 'anonymous'),
]
user_ctx or Context(kind="user", key="anonymous"),
Context(kind="org", key=str(account_id) if account_id else "anonymous"),
],
)

@staticmethod
Expand All @@ -140,7 +139,7 @@ def value(flag: str, user=None, account_id=None):
try:
return client.variation(flag, flag_context, None)
except Exception as err: # noqa: B902
current_app.logger.error(f'Unable to read flags: {repr(err)}', exc_info=True)
current_app.logger.error(f"Unable to read flags: {repr(err)}", exc_info=True)
return None

@staticmethod
Expand Down
3 changes: 1 addition & 2 deletions strr-api/src/strr_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@

import os

from dotenv import find_dotenv
from dotenv import load_dotenv
from dotenv import find_dotenv, load_dotenv

basedir = os.path.abspath(os.path.dirname(__file__))

Expand Down
2 changes: 1 addition & 1 deletion strr-api/src/strr_api/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Application Specific Exceptions/Responses, to manage handled errors."""
from .exceptions import (ExternalServiceException) # noqa: F401
from .exceptions import ExternalServiceException # noqa: F401
4 changes: 2 additions & 2 deletions strr-api/src/strr_api/exceptions/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ class ExternalServiceException(BaseExceptionE):

def __post_init__(self):
"""Return a valid ExternalServiceException."""
self.message = '3rd party service error while processing request.'
self.error = f'{repr(self.error)}, {self.status_code}'
self.message = "3rd party service error while processing request."
self.error = f"{repr(self.error)}, {self.status_code}"
self.status_code = HTTPStatus.SERVICE_UNAVAILABLE
1 change: 0 additions & 1 deletion strr-api/src/strr_api/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
from .db import db # noqa: I001
from .user import User


__all__ = (
"db",
"User",
Expand Down
1 change: 0 additions & 1 deletion strr-api/src/strr_api/models/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
from flask_sqlalchemy import SQLAlchemy
from sql_versioning import versioned_session


# by convention in the Flask community these are lower case,
# whereas pylint wants them upper case
db = SQLAlchemy()
Expand Down
2 changes: 2 additions & 0 deletions strr-api/src/strr_api/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
here as a convenience for audit and db reporting.
"""
from __future__ import annotations

from flask import current_app

from .db import db


Expand Down
24 changes: 12 additions & 12 deletions strr-api/src/strr_api/resources/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,29 @@
"""

import logging

from flask import Blueprint
from flask import jsonify
from flask import request
from flask import current_app as app
from flask_restx import Api, Namespace, Resource
from flask_restx import abort
from flask import jsonify, request
from flask_restx import Api, Namespace, Resource, abort

from strr_api.schemas import utils as schema_utils

logger = logging.getLogger('api')
logger = logging.getLogger("api")
bp = Blueprint("base", __name__)
api = Api(bp, description="Short Term Rental API", default="?")
ns = Namespace('', description='Base Endpoints')
ns = Namespace("", description="Base Endpoints")
api.add_namespace(ns, path="")


@ns.route('/hello')
@ns.route("/hello")
class HelloWorld(Resource):
"""HellowWorld endpoint"""

def get(self):
'''HTTP GET'''
"""HTTP GET"""

print('TESTING-PRINT')
print("TESTING-PRINT")
logger.info("TESTING-LOGGER")
app.logger.info("TESTING-APP-LOGGER")
return jsonify(name="world")
Expand All @@ -70,15 +70,15 @@ class GoodbyeWorld(Resource):
"""GoodbyeWorld endpoint"""

def post(self):
'''HTTP POST'''
"""HTTP POST"""

logger.info("Request data: %s", request.get_json())
json_input = request.get_json()
logger.info("Request data: %s", json_input)

valid, errors = schema_utils.validate(json_input, 'goodbye')
valid, errors = schema_utils.validate(json_input, "goodbye")
if not valid:
logger.warning("Validation errors: %s", errors)
abort(400, 'Bad request')
abort(400, "Bad request")

return jsonify(name="goodbye")
25 changes: 14 additions & 11 deletions strr-api/src/strr_api/resources/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,23 @@
Health is determined by the ability to execute a simple SELECT 1 query on the connected database.
"""
from http import HTTPStatus

from flask import Blueprint, current_app
from sqlalchemy import exc, text
from flask_restx import Namespace, Resource
from sqlalchemy import exc, text

from strr_api.models import db

from .base import api

bp = Blueprint("ops", __name__)
ns = Namespace('ops', description='Ops Endpoints')
ns = Namespace("ops", description="Ops Endpoints")
api.add_namespace(ns, path="")


@ns.route("/healthz", methods=("GET",))
class Health(Resource):
'''Health check endpoint.'''
"""Health check endpoint."""

def get(self):
"""
Expand All @@ -66,21 +69,21 @@ def get(self):
A dictionary with the message 'api is down' and the HTTP status code 500 if the database connection fails.
"""
try:
db.session.execute(text('select 1'))
db.session.execute(text("select 1"))
except exc.SQLAlchemyError as db_exception:
current_app.logger.error('DB connection pool unhealthy:' + repr(db_exception))
return {'message': 'api is down'}, HTTPStatus.INTERNAL_SERVER_ERROR
current_app.logger.error("DB connection pool unhealthy:" + repr(db_exception))
return {"message": "api is down"}, HTTPStatus.INTERNAL_SERVER_ERROR
except Exception as default_exception: # noqa: B902; log error
current_app.logger.error('DB connection failed:' + repr(default_exception))
return {'message': 'api is down'}, 500
current_app.logger.error("DB connection failed:" + repr(default_exception))
return {"message": "api is down"}, 500

return {'message': 'api is healthy'}, HTTPStatus.OK
return {"message": "api is healthy"}, HTTPStatus.OK


@ns.route("/readyz", methods=("GET",))
class Ready(Resource):
'''Readiness check endpoint.'''
"""Readiness check endpoint."""

def get(self):
"""Return a JSON object that identifies if the service is setup and ready to work."""
return {'message': 'api is ready'}, HTTPStatus.OK
return {"message": "api is ready"}, HTTPStatus.OK
Loading

0 comments on commit 0310ec5

Please sign in to comment.