#๐Ÿ”’ problem with deleteing dynamic databases

10 messages ยท Page 1 of 1 (latest)

steel ore
#

the function works but when i try to use a nother function or delete soemthing ill get an error wqhere it still tries to check for that datasbase that has been deleted even though i checked the jsopn file that contains the dtabase that its not there anymore so im confused where its going wrong

sudden oceanBOT
#

@steel ore

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

steel ore
#

heres the middleware

#
class DynamicDatabaseMiddleware(MiddlewareMixin):
    def process_request(self, request):
        branch_name = None

        # Handle both POST body and GET query parameter
        if request.method == 'POST' and request.body:
            try:
                data = json.loads(request.body)
                if isinstance(data, dict):
                    branch_name = data.get('branch_name')
            except json.JSONDecodeError:
                print("Invalid JSON payload in request body.")

        if not branch_name:
            branch_name = request.GET.get('branch_name')

        if branch_name:
            db_name = f'branch_{branch_name.lower()}'
            # Reload dynamic database settings
            dynamic_db_settings_path = settings.DYNAMIC_DATABASE_SETTINGS_PATH
            if os.path.exists(dynamic_db_settings_path):
                with open(dynamic_db_settings_path) as f:
                    dynamic_databases = json.load(f)
                if db_name in dynamic_databases:
                    request.db_name = db_name
                else:
                    request.db_name = None
            else:
                print("Database settings file not found.")
                request.db_name = 'default'  # Fallback to default database
        else:
            request.db_name = 'default'  # Fallback to default database

    def process_response(self, request, response):
        db_name = getattr(request, 'db_name', None)
        if db_name and db_name in connections:
            connections[db_name].close()
        return response
#

heres trhe views.py that contains the delete



def delete_branch(request):
    data = request.data
    branch_name = data.get('branch_name')

    if not branch_name:
        return JsonResponse({'error': 'Branch name is required'}, status=400)

    db_name = f'branch_{branch_name.lower()}'

    # Check if the branch exists in the default database
    try:
        branch = Branch.objects.get(name=branch_name)
    except Branch.DoesNotExist:
        return JsonResponse({'error': 'Branch not found'}, status=404)

    # Load dynamic databases from JSON file
    dynamic_db_settings_path = settings.DYNAMIC_DATABASE_SETTINGS_PATH
    if os.path.exists(dynamic_db_settings_path):
        with open(dynamic_db_settings_path) as f:
            dynamic_databases = json.load(f)
    else:
        return JsonResponse({'error': 'Database settings file not found'}, status=500)

    # Ensure the database exists in the settings
    if db_name not in dynamic_databases:
        return JsonResponse({'error': 'Database not found in settings'}, status=404)

    # Step 1: Drop the database
    with connection.cursor() as cursor:
        try:
            cursor.execute(f"DROP DATABASE IF EXISTS {db_name}")
        except OperationalError as e:
            return JsonResponse({'error': f'Database drop failed: {str(e)}'}, status=500)

    # Step 2: Remove the database entry from the JSON settings
    del dynamic_databases[db_name]
    with open(dynamic_db_settings_path, 'w') as f:
        json.dump(dynamic_databases, f, indent=4)

    # Step 3: Delete the branch entry from the default database
    branch.delete()

    # Step 4: Remove associated admin users (optional)
    CustomUser.objects.filter(username=f'user_{branch_name.lower()}').delete()

    # Step 5: Close all database connections to avoid cached connections
    connections.close_all()

    return JsonResponse({'message': 'Branch and database deleted successfully. System reloaded.'}, status=200)
#

then when i just reload my terminal like saving normally it wont check for that database anymore

steel ore
#

.

cedar finch
#

and what is the reason why you want to dinamically delete the database?

sudden oceanBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.