Search code examples
pythondjangodebuggingdjango-rest-frameworkhttp-status-code-404

"detail": "Not Found" Error With Python Django REST API


Im having an issue with a Python Django REST API i've built that manages the file upload and retreival from and to a Google Cloud SQL DB. I am not exactly sure whats causing the error but whene i run it runs fine at successfully connects to the Database and connects at http://127.0.0.1:8000/ but whenever i test a end point for example http://127.0.0.1:8000/upload it returns a 404 { "detail": "Not Found" }

When the app itself runs it logs this to the console:

Could not find platform independent libraries <prefix>
Could not find platform independent libraries <prefix>
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 18, 2024 - 19:03:09
Django version 5.0.6, using settings 'JurisScan_REST_API.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Here are the project files

asgi.py

"""
ASGI config for JurisScan_REST_API project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'JurisScan_REST_API.settings')

application = get_asgi_application()

settings.py

"""
Django settings for JurisScan_REST_API project.

Generated by 'django-admin startproject' using Django 5.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'JurisScan_REST_API'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'JurisScan_REST_API.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'JurisScan_REST_API.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'jurisscan_db',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '35.221.31.137',
        'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


views.py

import base64

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from .models import UserFile
from .serializers import UserFileSerializer

class UploadFileView(APIView):
    def post(self, request):
        user_id = request.data.get('user_id')
        file = request.data.get('file')
        file_path = request.data.get('file_path')
        if not user_id or not file:
            return Response({'error': 'user_id and file are required'}, status=status.HTTP_400_BAD_REQUEST)

        # Save file to user's table
        table_name = f'user_{user_id}'
        with connection.cursor() as cursor:
            cursor.execute(
                f"CREATE TABLE IF NOT EXISTS {table_name} (file_name VARCHAR(255), file_path VARCHAR(255), file LONGBLOB)")
            cursor.execute(f"INSERT INTO {table_name} (file_name, file_path, file) VALUES (%s, %s, %s)",
                           [file.name, file_path, file.read()])

        return Response({'message': 'File uploaded successfully'}, status=status.HTTP_201_CREATED)


class GetUserFilesView(APIView):
    def get(self, request, user_id):
        table_name = f'user_{user_id}'
        with connection.cursor() as cursor:
            cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
            if cursor.fetchone() is None:
                return Response({'error': 'User table does not exist'}, status=status.HTTP_404_NOT_FOUND)

            cursor.execute(f"SELECT file_name, file_path, file FROM {table_name}")
            files = cursor.fetchall()

            response_files = [
                {'file_name': file[0], 'file_path': file[1], 'file_content': base64.b64encode(file[2]).decode('utf-8')}
                for file in files]

            return Response({'files': response_files}, status=status.HTTP_200_OK)

urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

REST_API/urls.py

from django.urls import path
from .views import UploadFileView, GetUserFilesView

urlpatterns = [
    path('upload/', UploadFileView.as_view(), name='file-upload'),
    path('get_user_files/<str:user_id>/', GetUserFilesView.as_view(), name='get-user-files'),
]

wsgi.py

"""
WSGI config for JurisScan_REST_API project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'JurisScan_REST_API.settings')

application = get_wsgi_application()

manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'JurisScan_REST_API.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()


Solution

  • I actually fixed it it turned out to be a error on my part i had another API running on port 8000 and django by default runs on 8000 so i just had to change it to run on a unqiue port.