diff --git a/LICENSE b/LICENSE index 09f4784..29cbf33 100644 --- a/LICENSE +++ b/LICENSE @@ -1,14 +1,201 @@ -Copyright 2021 Department of Biodiversity, Conservation and Attractions + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..04f196a --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include README.md +include LICENSE diff --git a/README.md b/README.md index 460bd4d..ce1c88a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,23 @@ -DBCA utility functions mainly related to Django SSO authentication middleware. +# Overview -## SSO Login Middleware +DBCA Django utility classes and functions. + +# SSO Login Middleware This will automatically login and create users using headers from an upstream proxy (REMOTE_USER and some others). The logout view will redirect to a separate logout page which clears the SSO session. -Install with pip, then add the following to ``settings.py`` (note middleware must come after session and contrib.auth). -Also note that the auth backend *django.contrib.auth.backends.ModelBackend* is in AUTHENTICATION_BACKENDS as this middleware -depends on it for retrieving the logged in user for a session (will still work without it, but will reauthenticate the session -on every request, and request.user.is_authenticated won't work properly/will be false). +## Usage + +Add `dbca_utils.middleware.SSOLoginMiddleware` to `settings.MIDDLEWARE` (after both of +`django.contrib.sessions.middleware.SessionMiddleware` and +`django.contrib.auth.middleware.AuthenticationMiddleware`. +Ensure that `AUTHENTICATION_BACKENDS` contains `django.contrib.auth.backends.ModelBackend`, +as this middleware depends on it for retrieving the logged in user for a session. +Note that the middleware will still work without it, but will reauthenticate the session +on every request, and `request.user.is_authenticated` won't work properly/will be false. + +Example: ``` MIDDLEWARE = [ @@ -16,19 +25,15 @@ MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'dbca_utils.middleware.SSOLoginMiddleware' + ..., ] ``` -## Audit model mixin and middleware +# Audit model mixin -``AuditMixin`` is an extension of ``Django.db.model.Model`` that adds a -number of additional fields: +``AuditMixin`` is an extension of ``Django.db.model.Model`` that adds a number of additional fields: * creator - FK to ``AUTH_USER_MODEL``, used to record the object creator * modifier - FK to ``AUTH_USER_MODEL``, used to record who the object was last modified by * created - a timestamp that is set on initial object save * modified - an auto-updating timestamp (on each object save) - -``AuditMiddleware`` is a middleware that will process any request for an -object having a ``creator`` or ``modifier`` field, and automatically set those -to the request user via a ``pre_save`` signal. diff --git a/dbca_utils/middleware.py b/dbca_utils/middleware.py index bcde2af..b8bc09b 100644 --- a/dbca_utils/middleware.py +++ b/dbca_utils/middleware.py @@ -1,94 +1,34 @@ -from django import http, VERSION +from django import http from django.conf import settings from django.contrib.auth import login, logout, get_user_model -from django.db.models import signals from django.utils.deprecation import MiddlewareMixin -from django.utils.functional import SimpleLazyObject -from django.contrib.auth.middleware import AuthenticationMiddleware, get_user -from dbca_utils.utils import env - -ENABLE_AUTH2_GROUPS = env("ENABLE_AUTH2_GROUPS", default=False) -LOCAL_USERGROUPS = env("LOCAL_USERGROUPS", default=[]) - - -def sync_usergroups(user, groups): - from django.contrib.auth.models import Group - - usergroups = ( - [Group.objects.get_or_create(name=name)[0] for name in groups.split(",")] - if groups - else [] - ) - usergroups.sort(key=lambda o: o.id) - existing_usergroups = list(user.groups.exclude(name__in=LOCAL_USERGROUPS).order_by("id")) - index1 = 0 - index2 = 0 - len1 = len(usergroups) - len2 = len(existing_usergroups) - while True: - group1 = usergroups[index1] if index1 < len1 else None - group2 = existing_usergroups[index2] if index2 < len2 else None - if not group1 and not group2: - break - if not group1: - user.groups.remove(group2) - index2 += 1 - elif not group2: - user.groups.add(group1) - index1 += 1 - elif group1.id == group2.id: - index1 += 1 - index2 += 1 - elif group1.id < group2.id: - user.groups.add(group1) - index1 += 1 - else: - user.groups.remove(group2) - index2 += 1 - - -class SimpleLazyUser(SimpleLazyObject): - def __init__(self, func, request, groups): - super().__init__(func) - self.request = request - self.usergroups = groups - - def __getattr__(self, name): - if name == "groups": - sync_usergroups(self._wrapped, self.usergroups) - self.request.session["usergroups"] = self.usergroups - - return super().__getattr__(name) - - -# overwrite the authentication middleware to add logic to processing user groups -if ENABLE_AUTH2_GROUPS: - original_process_request = AuthenticationMiddleware.process_request - - def _process_request(self, request): - if "HTTP_X_GROUPS" in request.META: - groups = request.META["HTTP_X_GROUPS"] or None - existing_groups = request.session.get("usergroups") - if groups != existing_groups: - # user group is changed. - request.user = SimpleLazyUser( - lambda: get_user(request), request, groups - ) - return - original_process_request(self, request) - - AuthenticationMiddleware.process_request = _process_request +User = get_user_model() class SSOLoginMiddleware(MiddlewareMixin): + """Django middleware to process HTTP requests containing headers set by the Auth2 + SSO service, specificially: + - `HTTP_REMOTE_USER` + - `HTTP_X_LAST_NAME` + - `HTTP_X_FIRST_NAME` + - `HTTP_X_EMAIL` + + The middleware assesses requests containing these headers, and (having deferred user + authentication to the upstream service), retrieves the local Django User and logs + the user in automatically. + + If the request path starts with one of the defined logout paths and a `HTTP_X_LOGOUT_URL` + value is set in the response, log out the user and redirect to that URL instead. + """ + def process_request(self, request): - User = get_user_model() + # Logout headers included with request. if ( ( request.path.startswith("/logout") - or request.path.startswith("/ledger/logout") + or request.path.startswith("/admin/logout") ) and "HTTP_X_LOGOUT_URL" in request.META and request.META["HTTP_X_LOGOUT_URL"] @@ -96,20 +36,16 @@ def process_request(self, request): logout(request) return http.HttpResponseRedirect(request.META["HTTP_X_LOGOUT_URL"]) + # Auth2 is not enabled, skip further processing. if ( "HTTP_REMOTE_USER" not in request.META or not request.META["HTTP_REMOTE_USER"] ): - # auth2 not enabled return - if VERSION < (2, 0): - user_auth = request.user.is_authenticated() - else: - user_auth = request.user.is_authenticated - - if not user_auth: - # Not authenticate before + # Auth2 is enabled. + # Request user is not authenticated. + if not request.user.is_authenticated: attributemap = { "username": "HTTP_REMOTE_USER", "last_name": "HTTP_X_LAST_NAME", @@ -121,6 +57,8 @@ def process_request(self, request): if value in request.META: attributemap[key] = request.META[value] + # Optional setting: projects may define accepted user email domains either as + # a list of strings, or a single string. if ( hasattr(settings, "ALLOWED_EMAIL_SUFFIXES") and settings.ALLOWED_EMAIL_SUFFIXES @@ -133,79 +71,19 @@ def process_request(self, request): ): return http.HttpResponseForbidden() + # Check if the supplied request user email already exists as a local User. if ( attributemap["email"] and User.objects.filter(email__iexact=attributemap["email"]).exists() ): - user = User.objects.filter(email__iexact=attributemap["email"])[0] - elif (User.__name__ != "EmailUser") and User.objects.filter( - username__iexact=attributemap["username"] - ).exists(): - user = User.objects.filter(username__iexact=attributemap["username"])[0] + user = User.objects.get(email__iexact=attributemap["email"]) else: user = User() + + # Set the user's details from the supplied information. user.__dict__.update(attributemap) user.save() user.backend = "django.contrib.auth.backends.ModelBackend" - login(request, user) - # synchronize the user groups - if ENABLE_AUTH2_GROUPS and "HTTP_X_GROUPS" in request.META: - groups = request.META["HTTP_X_GROUPS"] or None - sync_usergroups(user, groups) - request.session["usergroups"] = groups - - -def curry(_curried_func, *args, **kwargs): - """Reference: https://docs.djangoproject.com/en/2.2/_modules/django/utils/functional/ - Deprecated in Django 3.0. - """ - - def _curried(*moreargs, **morekwargs): - return _curried_func(*args, *moreargs, **{**kwargs, **morekwargs}) - - return _curried - - -class AuditMiddleware(MiddlewareMixin): - """Adds creator and modifier foreign key refs to any model automatically. - Ref: https://gist.github.com/mindlace/3918300 - """ - - def process_request(self, request): - if request.method not in ("GET", "HEAD", "OPTIONS", "TRACE"): - if hasattr(request, "user"): - if VERSION < (2, 0): - if request.user.is_authenticated(): - user = request.user - else: - user = None - else: - if request.user.is_authenticated: - user = request.user - else: - user = None - - set_auditfields = curry(self.set_auditfields, user) - signals.pre_save.connect( - set_auditfields, - dispatch_uid=( - self.__class__, - request, - ), - weak=False, - ) - - def process_response(self, request, response): - signals.pre_save.disconnect( - dispatch_uid=( - self.__class__, - request, - ) - ) - return response - def set_auditfields(self, user, sender, instance, **kwargs): - if not getattr(instance, "creator_id", None): - instance.creator = user - if hasattr(instance, "modifier_id"): - instance.modifier = user + # Log the user in. + login(request, user) diff --git a/dbca_utils/requests/__init__.py b/dbca_utils/requests/__init__.py deleted file mode 100644 index d73192b..0000000 --- a/dbca_utils/requests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .api import get,options,head,post,put,patch,delete diff --git a/dbca_utils/requests/api.py b/dbca_utils/requests/api.py deleted file mode 100644 index 106cd18..0000000 --- a/dbca_utils/requests/api.py +++ /dev/null @@ -1,228 +0,0 @@ -import requests -import os -try: - from StringIO import StringIO # Python 2 -except ImportError: - from io import StringIO # Python 3 - - -session_key_header = "X_SESSION_KEY" -http_session_key_header = "HTTP_{}".format(session_key_header) -sso_cookie_name = os.environ.get( - "SSO_COOKIE_NAME") or "_dpaw_wa_gov_au_sessionid" -debug = (os.environ.get("DEBUG_SSO") or "false").lower() in [ - "true", "yes", "t", "y", "on"] - -if debug: - import json as json_lib - request_seq = 0 - - -def _set_session_key(user_request, kwargs): - """ - Get the session key from user request for sso - if not found, return None - """ - if not user_request: - return - - session_key = None - request_name = user_request.__module__ + "." + user_request.__class__.__name__ - try: - if request_name[0:7] == "bottle.": - session_key = user_request.get_header( - session_key_header, user_request.get_header( - http_session_key_header, None)) - elif request_name[0:7] == "django.": - session_key = user_request.META.get( - http_session_key_header, user_request.META.get( - session_key_header, None)) - else: - session_key = user_request.META.get( - http_session_key_header, user_request.META.get( - session_key_header, None)) - except: - pass - - if not session_key: - # Try to use the current session id - try: - session_key = user_request.session.session_key - except: - pass - if session_key: - cookies = kwargs.get("cookies", {}) - cookies[sso_cookie_name] = session_key - kwargs["cookies"] = cookies - - return - - -log_head_format = """{}-{}: {} - server-side request: {} {} - header: - {} -""" - - -def log(user_request, url, method, data=None, json=None, kwargs=None): - global request_seq - request_seq += 1 - try: - request_path = user_request.path - except: - request_path = "" - log_msg = log_head_format.format(os.getpid(), request_seq, request_path, - url, method, - ("\n" + ' ' * 12).join(["{}={}".format(k, v) for k, v in (kwargs or {}).iteritems()])) - if data: - log_msg += "{}body(data): {}\n".format(' ' * 8, str(data)) - - if json: - json_out = StringIO() - try: - json_lib.dump(json, json_out, indent=4) - json_str = "\n".join( - [" " * 12 + line for line in json_out.getvalue().split("\n")]) - finally: - json_out.close() - - log_msg += "{}body(json):\n{}\n".format(' ' * 8, json_str) - - print(log_msg) - - -def options(user_request, url, **kwargs): - """ A wrapper of requests.options. - This method will automatically add user's session key as the cookie to enable sso - - Sends a OPTIONS request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "OPTIONS", kwargs=kwargs) - - return requests.options(url, **kwargs) - - -def head(user_request, url, **kwargs): - """ A wrapper of requests.head. - This method will automatically add user's session key as the cookie to enable sso - - Sends a HEAD request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "HEAD", kwargs=kwargs) - - return requests.head(url, **kwargs) - - -def get(user_request, url, **kwargs): - """ A wrapper of requests.get. - This method will automatically add user's session key as the cookie to enable sso - - Sends a GET request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "GET", kwargs=kwargs) - - return requests.get(url, **kwargs) - - -def post(user_request, url, data=None, json=None, **kwargs): - """ A wrapper of requests.post. - This method will automatically add user's session key as the cookie to enable sso - - Sends a POST request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. - :param json: (optional) json data to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "POST", data=data, json=json, kwargs=kwargs) - - return requests.post(url, data, json, **kwargs) - - -def put(user_request, url, data=None, **kwargs): - """ A wrapper of requests.put. - This method will automatically add user's session key as the cookie to enable sso - - Sends a PUT request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "PUT", data=data, kwargs=kwargs) - - return requests.put(url, data, **kwargs) - - -def patch(user_request, url, data=None, **kwargs): - """ A wrapper of requests.patch. - This method will automatically add user's session key as the cookie to enable sso - - Sends a PATCH request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "PATCH", data=data, kwargs=kwargs) - - return requests.patch(url, data, **kwargs) - - -def delete(user_request, url, **kwargs): - """ A wrapper of requests.delete. - This method will automatically add user's session key as the cookie to enable sso - - Sends a DELETE request. Returns :class:`Response` object. - - :param user_request: The http request contains the authentication key and is triggered by user. - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - """ - - _set_session_key(user_request, kwargs) - - if debug: - log(user_request, url, "DELETE", kwargs=kwargs) - - return requests.delete(url, **kwargs) diff --git a/dbca_utils/utils.py b/dbca_utils/utils.py index 2ed3a65..7ce283c 100644 --- a/dbca_utils/utils.py +++ b/dbca_utils/utils.py @@ -15,7 +15,7 @@ def env(key, default=None, required=False, value_type=None): except KeyError: if default is not None or not required: return default - raise Exception("Missing required environment variable '%s'" % key) + raise Exception(f"Missing required environment variable {key}") if value_type is None: if default is not None: @@ -53,9 +53,7 @@ def env(key, default=None, required=False, value_type=None): return False else: raise Exception( - "'{}' is a boolean environment variable, only accept value 'true' ,'false' and '' with case insensitive, but the configured value is '{}'".format( - key, value - ) + f"{key} is a boolean environment variable and only accepts 'true' ,'false' and '' (case-insensitive), but the configured value is '{value}'" ) elif issubclass(value_type, int): return int(value) @@ -63,7 +61,5 @@ def env(key, default=None, required=False, value_type=None): return float(value) else: raise Exception( - "'{0}' is a {1} environment variable, but {1} is not supported now".format( - key, value_type - ) + f"{key} is a {value_type} environment variable, but {value_type} is not supported now" ) diff --git a/setup.py b/setup.py index 80e4b1e..807ef5f 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ setup( name='dbca-utils', - version='1.1.6', + version='2.0.0', packages=['dbca_utils'], description='Utilities for Django/Python apps', long_description=long_description, @@ -23,23 +23,24 @@ zip_safe=False, keywords=['django', 'middleware', 'utility'], install_requires=[ - 'Django>=2.1', - 'requests', + 'Django>=3.2', ], classifiers=[ 'Framework :: Django', - 'Framework :: Django :: 2.2', - 'Framework :: Django :: 3.0', 'Framework :: Django :: 3.2', + 'Framework :: Django :: 4.0', + 'Framework :: Django :: 4.2', + 'Framework :: Django :: 5.0', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ],