Skip to content

Commit

Permalink
Merge pull request #1886 from DrFaustie/master
Browse files Browse the repository at this point in the history
Move up to fstrings
  • Loading branch information
leplatrem committed Nov 29, 2018
2 parents 58b2410 + 76d0c01 commit ea5f66d
Show file tree
Hide file tree
Showing 48 changed files with 268 additions and 302 deletions.
18 changes: 8 additions & 10 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
dist: trusty
language: python
python: 3.5
python: 3.6
cache: pip
services:
- memcached
addons:
postgresql: "9.5"
env:
- TOX_ENV=py35
- TOX_ENV=py35-raw
- TOX_ENV=py36
- TOX_ENV=py36-raw
- TOX_ENV=lint
- TOX_ENV=docs
install:
- pip install tox
Expand All @@ -27,18 +28,15 @@ after_success:

matrix:
include:
- python: 3.6
env:
- TOX_ENV=py36
- python: 3.6
env:
- TOX_ENV=lint
- python: 3.7
dist: xenial
sudo: true
env:
- TOX_ENV=py37
- env: ENV=functional
- python: 3.7
dist: xenial
sudo: true
env: ENV=functional
before_install:
- make install-dev
- make install-postgres
Expand Down
10 changes: 8 additions & 2 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ Changelog

This document describes changes between each past release.

11.3.0 (unreleased)
12.0.0 (unreleased)
-------------------

- Nothing changed yet.
**Breaking changes**

- Remove Python 3.5 support and upgrade to Python 3.6. (#1886)

**Internal changes**

- Use f-string instead of % or format operators. (#1886)


11.2.0 (2018-11-29)
Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ OBJECTS = .venv .coverage

help:
@echo "Please use 'make <target>' where <target> is one of"
@echo " black reformat code"
@echo " install install dependencies and prepare environment"
@echo " install-monitoring enable monitoring features like StatsD and Newrelic"
@echo " install-postgres install postgresql support"
Expand Down Expand Up @@ -86,6 +87,9 @@ tests-once: install-dev version-file install-postgres install-monitoring
flake8: install-dev
$(VENV)/bin/flake8 kinto tests

black: install-dev
$(VENV)/bin/black kinto tests

tests: version-file
$(VENV)/bin/tox

Expand Down
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ Kinto is a minimalist JSON storage service with synchronisation and sharing abil
Requirements
------------

* **Python**: 3.5+
* **Python**: 3.6+
* **Backends**: In-memory (development), Postgresql 9.5+ (production)
1 change: 1 addition & 0 deletions dev-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
black==18.9b0
bravado_core==5.10.0
flake8==3.6.0
pytest==4.0.1
Expand Down
4 changes: 2 additions & 2 deletions kinto/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def main(args=None):

if which_command == "init":
if os.path.exists(config_file):
print("{} already exists.".format(config_file), file=sys.stderr)
print(f"{config_file} already exists.", file=sys.stderr)
return 1

backend = parsed_args["backend"]
Expand Down Expand Up @@ -246,7 +246,7 @@ def main(args=None):
pserve_argv.append("-q")

pserve_argv.append(config_file)
pserve_argv.append("http_port={}".format(parsed_args["port"]))
pserve_argv.append(f"http_port={parsed_args['port']}")
pserve.main(argv=pserve_argv)

else:
Expand Down
6 changes: 3 additions & 3 deletions kinto/authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ def _relative_object_uri(resource_name, object_uri):
if resource_name == parent_resource_name:
return parent_uri

error_msg = "Cannot get URL of resource '{}' from parent '{}'."
raise ValueError(error_msg.format(resource_name, object_uri))
error_msg = f"Cannot get URL of resource '{resource_name}' from parent '{object_uri}'."
raise ValueError(error_msg)


def _inherited_permissions(object_uri, permission):
Expand All @@ -111,7 +111,7 @@ def _inherited_permissions(object_uri, permission):

# When requesting permissions for a single object, we check if they are any
# specific inherited permissions for the attributes.
attributes_permission = "{}:attributes".format(permission) if not plural else permission
attributes_permission = f"{permission}:attributes" if not plural else permission
inherited_perms = object_perms_tree.get(attributes_permission, object_perms_tree[permission])

granters = set()
Expand Down
8 changes: 4 additions & 4 deletions kinto/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def render_template(template, destination, **kwargs):
if folder and not os.path.exists(folder):
os.makedirs(folder)

logger.info("Created config {}".format(os.path.abspath(destination)))
logger.info(f"Created config {os.path.abspath(destination)}")

with codecs.open(template, "r", encoding="utf-8") as f:
raw_template = f.read()
Expand Down Expand Up @@ -50,9 +50,9 @@ def init(config_file, backend, cache_backend, host="127.0.0.1"):
values["kinto_version"] = __version__
values["config_file_timestamp"] = str(strftime("%a, %d %b %Y %H:%M:%S %z"))

values["storage_backend"] = "kinto.core.storage.{}".format(backend)
values["cache_backend"] = "kinto.core.cache.{}".format(cache_backend)
values["permission_backend"] = "kinto.core.permission.{}".format(backend)
values["storage_backend"] = f"kinto.core.storage.{backend}"
values["cache_backend"] = f"kinto.core.cache.{cache_backend}"
values["permission_backend"] = f"kinto.core.permission.{backend}"
cache_backend_url = get_cache_backend_url(values["cache_backend"])

if backend == "postgresql":
Expand Down
2 changes: 1 addition & 1 deletion kinto/core/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def unauthenticated_userid(self, request):
return

hmac_secret = settings["userid_hmac_secret"]
credentials = "{}:{}".format(*credentials)
credentials = f"{credentials[0]}:{credentials[1]}"
userid = utils.hmac_digest(hmac_secret, credentials)
return userid

Expand Down
8 changes: 4 additions & 4 deletions kinto/core/authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def permits(self, context, principals, permission):
if permission == DYNAMIC:
permission = context.required_permission

create_permission = "{}:create".format(context.resource_name)
create_permission = f"{context.resource_name}:create"
if permission == "create":
permission = create_permission

Expand Down Expand Up @@ -178,9 +178,9 @@ def check_permission(self, principals, bound_perms):
for (_, permission) in bound_perms:
# With Kinto inheritance tree, we can have: `permission = "record:create"`
if self.resource_name and permission.startswith(self.resource_name):
setting = "{}_principals".format(permission.replace(":", "_"))
setting = f"{permission.replace(':', '_')}_principals"
else:
setting = "{}_{}_principals".format(self.resource_name, permission)
setting = f"{self.resource_name}_{permission}_principals"
allowed_principals = aslist(self._settings.get(setting, ""))
if allowed_principals:
if bool(set(allowed_principals) & set(principals)):
Expand Down Expand Up @@ -233,7 +233,7 @@ def get_permission_object_id(self, request, object_id=None):
# Maybe the resource has no single record endpoint.
# We consider that object URIs in permissions backend will
# be stored naively:
object_uri = "{}/{}".format(object_uri, object_id)
object_uri = f"{object_uri}/{object_id}"

return object_uri

Expand Down
2 changes: 1 addition & 1 deletion kinto/core/cache/postgresql/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def initialize_schema(self, dry_run=False):
sql_file = os.path.join(here, "schema.sql")

if dry_run:
logger.info("Create cache schema from '{}'".format(sql_file))
logger.info(f"Create cache schema from '{sql_file}'")
return

# Since called outside request, force commit.
Expand Down
4 changes: 1 addition & 3 deletions kinto/core/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ def __init__(self, payload, request):
self.request = request

def __repr__(self):
return "<{klass} action={action} uri={uri}>".format(
klass=self.__class__.__name__, **self.payload
)
return f"<{self.__class__.__name__} action={self.payload['action']} uri={self.payload['uri']}>"


class ResourceRead(_ResourceEvent):
Expand Down
38 changes: 19 additions & 19 deletions kinto/core/initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _redirect_to_version_view(request):
return utils.reapply_cors(request, Response())

querystring = request.url[(request.url.rindex(request.path) + len(request.path)) :]
redirect = "/{}{}{}".format(route_prefix, request.path, querystring)
redirect = f"/{route_prefix}{request.path}{querystring}"
raise HTTPTemporaryRedirect(redirect)

# Disable the route prefix passed by the app.
Expand Down Expand Up @@ -213,7 +213,7 @@ def setup_storage(config):
storage_mod = config.maybe_dotted(storage_mod)
backend = storage_mod.load_from_config(config)
if not isinstance(backend, storage.StorageBase):
raise ConfigurationError("Invalid storage backend: {}".format(backend))
raise ConfigurationError(f"Invalid storage backend: {backend}")
config.registry.storage = backend

heartbeat = storage.heartbeat(backend)
Expand All @@ -229,7 +229,7 @@ def setup_permission(config):
permission_mod = config.maybe_dotted(permission_mod)
backend = permission_mod.load_from_config(config)
if not isinstance(backend, permission.PermissionBase):
raise ConfigurationError("Invalid permission backend: {}".format(backend))
raise ConfigurationError(f"Invalid permission backend: {backend}")
config.registry.permission = backend

heartbeat = permission.heartbeat(backend)
Expand All @@ -245,7 +245,7 @@ def setup_cache(config):
cache_mod = config.maybe_dotted(cache_mod)
backend = cache_mod.load_from_config(config)
if not isinstance(backend, cache.CacheBase):
raise ConfigurationError("Invalid cache backend: {}".format(backend))
raise ConfigurationError(f"Invalid cache backend: {backend}")
config.registry.cache = backend

heartbeat = cache.heartbeat(backend)
Expand Down Expand Up @@ -288,12 +288,12 @@ def on_new_response(event):

# Count authentication verifications.
if hasattr(request, "authn_type"):
client.count("authn_type.{}".format(request.authn_type))
client.count(f"authn_type.{request.authn_type}")

# Count view calls.
service = request.current_service
if service:
client.count("view.{}.{}".format(service.name, request.method))
client.count(f"view.{service.name}.{request.method}")

config.add_subscriber(on_new_response, NewResponse)

Expand Down Expand Up @@ -390,7 +390,7 @@ def __init__(self, actions, config):
self.actions = [action.value for action in actions]

def phash(self):
return "for_actions = {}".format(",".join(self.actions))
return f"for_actions = {','.join(self.actions)}"

def __call__(self, event):
action = event.payload.get("action")
Expand All @@ -402,7 +402,7 @@ def __init__(self, resources, config):
self.resources = resources

def phash(self):
return "for_resources = {}".format(",".join(self.resources))
return f"for_resources = {','.join(self.resources)}"

def __call__(self, event):
resource = event.payload.get("resource_name")
Expand All @@ -420,33 +420,33 @@ def setup_listeners(config):
listeners = aslist(settings["event_listeners"])

for name in listeners:
logger.info("Setting up '{}' listener".format(name))
prefix = "event_listeners.{}.".format(name)
logger.info(f"Setting up '{name}' listener")
prefix = f"event_listeners.{name}."

try:
listener_mod = config.maybe_dotted(name)
prefix = "event_listeners.{}.".format(name.split(".")[-1])
prefix = f"event_listeners.{name.split('.')[-1]}."
listener = listener_mod.load_from_config(config, prefix)
except (ImportError, AttributeError):
module_setting = prefix + "use"
# Read from ENV or settings.
module_value = utils.read_env(
"{}.{}".format(settings_prefix, module_setting), settings.get(module_setting)
f"{settings_prefix}.{module_setting}", settings.get(module_setting)
)
listener_mod = config.maybe_dotted(module_value)
listener = listener_mod.load_from_config(config, prefix)

# If StatsD is enabled, monitor execution time of listeners.
if getattr(config.registry, "statsd", None):
statsd_client = config.registry.statsd
key = "listeners.{}".format(name)
key = f"listeners.{name}"
listener = statsd_client.timer(key)(listener.__call__)

# Optional filter by event action.
actions_setting = prefix + "actions"
# Read from ENV or settings.
actions_value = utils.read_env(
"{}.{}".format(settings_prefix, actions_setting), settings.get(actions_setting, "")
f"{settings_prefix}.{actions_setting}", settings.get(actions_setting, "")
)
actions = aslist(actions_value)
if len(actions) > 0:
Expand All @@ -458,7 +458,7 @@ def setup_listeners(config):
resource_setting = prefix + "resources"
# Read from ENV or settings.
resource_value = utils.read_env(
"{}.{}".format(settings_prefix, resource_setting), settings.get(resource_setting, "")
f"{settings_prefix}.{resource_setting}", settings.get(resource_setting, "")
)
resource_names = aslist(resource_value)

Expand All @@ -485,7 +485,7 @@ def _prefixed_keys(key):
unprefixed = key
if key.startswith(settings_prefix + "."):
unprefixed = key.split(".", 1)[1]
project_prefix = "{}.{}".format(settings_prefix, unprefixed)
project_prefix = f"{settings_prefix}.{unprefixed}"
return unprefixed, project_prefix

# Fill settings with default values if not defined.
Expand All @@ -505,7 +505,7 @@ def _prefixed_keys(key):

if len(defined) > 1 and len(distinct_values) > 1:
names = "', '".join(defined)
raise ValueError("Settings '{}' are in conflict.".format(names))
raise ValueError(f"Settings '{names}' are in conflict.")

# Override settings from OS env values.
# e.g. HTTP_PORT, READINGLIST_HTTP_PORT, KINTO_HTTP_PORT
Expand Down Expand Up @@ -557,7 +557,7 @@ def initialize(config, version=None, settings_prefix="", default_settings=None):
# Override project version from settings.
project_version = settings.get("project_version") or version
if not project_version:
error_msg = "Invalid project version: {}".format(project_version)
error_msg = f"Invalid project version: {project_version}"
raise ConfigurationError(error_msg)
settings["project_version"] = project_version = str(project_version)

Expand All @@ -567,7 +567,7 @@ def initialize(config, version=None, settings_prefix="", default_settings=None):
# The API version is derivated from the module version if not provided.
http_api_version = ".".join(project_version.split(".")[0:2])
settings["http_api_version"] = http_api_version = str(http_api_version)
api_version = "v{}".format(http_api_version.split(".")[0])
api_version = f"v{http_api_version.split('.')[0]}"

# Include kinto.core views with the correct api version prefix.
config.include("kinto.core", route_prefix=api_version)
Expand Down
4 changes: 2 additions & 2 deletions kinto/core/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def __init__(self, services, request):
self.ignore_ctypes = ["application/json-patch+json"]

# Matches the base routing address - See kinto.core.initialization
self.base_path = "/v{}".format(self.api_version.split(".")[0])
self.base_path = f"/v{self.api_version.split('.')[0]}"

def generate(self):
base_spec = {
Expand Down Expand Up @@ -95,7 +95,7 @@ def default_op_ids(self, service, method):

resource = resource.replace("-collection", "s")
resource = resource.replace("-record", "")
op_id = "{}_{}".format(method, resource)
op_id = f"{method}_{resource}"

return op_id

Expand Down

0 comments on commit ea5f66d

Please sign in to comment.