diff --git a/netbox/netbox/cursor.py b/netbox/netbox/cursor.py index 257f6e61c..0e8272f3e 100644 --- a/netbox/netbox/cursor.py +++ b/netbox/netbox/cursor.py @@ -1,7 +1,6 @@ import logging import time -from django.conf import settings from django.db.backends.utils import CursorWrapper as _CursorWrapper from netbox.exceptions import DatabaseWriteDenied @@ -10,11 +9,8 @@ logger = logging.getLogger('netbox.db') class ReadOnlyCursorWrapper: """ - A read-only wrapper around a database cursor. - This wrapper prevents write operations from being performed on the database. It is used to prevent changes to the - database during a read-only request. It is not intended to be used directly; rather, it is applied automatically by - the ReadOnlyMiddleware. See the documentation for that class for more information. + database during a read-only request. """ SQL_BLACKLIST = ( @@ -35,20 +31,19 @@ class ReadOnlyCursorWrapper: def __init__(self, cursor, db, *args, **kwargs): self.cursor = cursor self.db = db - self.read_only = settings.MAINTENANCE_MODE + + def __check_sql(self, sql): + if self._write_sql(sql): + raise DatabaseWriteDenied def execute(self, sql, params=()): # Check the SQL - if self.read_only and self._write_sql(sql): - raise DatabaseWriteDenied - + self.__check_sql(sql) return self.cursor.execute(sql, params) def executemany(self, sql, param_list): # Check the SQL - if self.read_only and self._write_sql(sql): - raise DatabaseWriteDenied - + self.__check_sql(sql) return self.cursor.executemany(sql, param_list) def __getattr__(self, item): diff --git a/netbox/netbox/middleware.py b/netbox/netbox/middleware.py index fa5a920f0..d1ff85649 100644 --- a/netbox/netbox/middleware.py +++ b/netbox/netbox/middleware.py @@ -229,20 +229,13 @@ class DatabaseReadOnlyMiddleware(MiddlewareMixin): if not isinstance(exception, DatabaseWriteDenied): return None - not_allowed_methods = ['POST', 'PUT', 'PATCH', 'DELETE'] error_message = 'The database is currently in read-only mode. Please try again later.' status_code = 503 - # If the request is an API request, return a 503 Service Unavailable response - if is_api_request(request) and request.method in not_allowed_methods: - return JsonResponse({'detail': error_message, }, status=status_code) + if is_api_request(request): + return JsonResponse({'detail': error_message}, status=status_code) else: - # Handle exceptions - if request.method in not_allowed_methods: - # Display a message to the user - messages.error(request, error_message) - - # Redirect back to the referring page - return HttpResponseReload(request) - else: - return HttpResponse(error_message, status=status_code) + # Display a message to the user + messages.error(request, error_message) + # Redirect back to the referring page + return HttpResponseReload(request)