#!/usr/bin/env python # -*- coding:utf-8 -*- import inspect import os import sys from types import ModuleType import django from django.conf import settings BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # The current name of the file, which will be the name of our app APP_LABEL, _ = os.path.splitext(os.path.basename(os.path.abspath(__file__))) # Migrations folder need to be created, and django needs to be told where it is APP_MIGRATION_MODULE = '%s_migrations' % APP_LABEL APP_MIGRATION_PATH = os.path.join(BASE_DIR, APP_MIGRATION_MODULE) # Create the folder and a __init__.py if they don't exist if not os.path.exists(APP_MIGRATION_PATH): os.makedirs(APP_MIGRATION_PATH) open(os.path.join(APP_MIGRATION_PATH, '__init__.py'), 'w').close() # Hack to trick Django into thinking this file is actually a package sys.modules[APP_LABEL] = sys.modules[__name__] sys.modules[APP_LABEL].__path__ = [os.path.abspath(__file__)] settings.configure( DEBUG=True, SECRET_KEY=os.environ.get('SECRET_KEY', os.urandom(32)), ALLOWED_HOSTS=os.environ.get('ALLOWED_HOSTS', 'localhost').split(','), ROOT_URLCONF='%s.urls' % APP_LABEL, 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', 'django.middleware.locale.LocaleMiddleware', ], INSTALLED_APPS=[ APP_LABEL, 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ], MIGRATION_MODULES={APP_LABEL: APP_MIGRATION_MODULE}, SITE_ID=1, STATIC_URL='/static/', STATICFILES_DIRS=[ os.path.join(BASE_DIR, "static"), ], STATIC_ROOT=os.path.join(BASE_DIR, "static_root"), MEDIA_ROOT=os.path.join(BASE_DIR, "media"), MEDIA_URL='/media/', TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }, REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 100 } ) django.setup() from django.apps import apps # noqa: E402 isort:skip # Setup the AppConfig so we don't have to add the app_label to all our models def get_containing_app_config(module): if module == '__main__': return apps.get_app_config(APP_LABEL) return apps._get_containing_app_config(module) apps._get_containing_app_config = apps.get_containing_app_config apps.get_containing_app_config = get_containing_app_config # Your code below this line # ############################################################################## from django.db import models from django.contrib import admin from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=200) class Book(models.Model): author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=400) admin.site.register(Book) admin.site.register(Author) admin.autodiscover() from rest_framework import serializers class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' from rest_framework import viewsets class BooksViewSet(viewsets.ReadOnlyModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer from django.conf.urls import url, include from rest_framework import routers from django.http import HttpResponse from django.contrib import admin router = routers.DefaultRouter() router.register(r'books', BooksViewSet) def index(request): return HttpResponse("Hello") urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index, name='homepage'), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls',\ namespace='rest_framework')) ] # Your code above this line # ############################################################################## # Used so you can do 'from .models import *' models_module = ModuleType('%s.models' % (APP_LABEL)) tests_module = ModuleType('%s.tests' % (APP_LABEL)) urls_module = ModuleType('%s.urls' % (APP_LABEL)) urls_module.urlpatterns = urlpatterns for variable_name, value in list(locals().items()): # We are only interested in models if inspect.isclass(value) and issubclass(value, models.Model): setattr(models_module, variable_name, value) # Setup the fake modules sys.modules[models_module.__name__] = models_module sys.modules[urls_module.__name__] = urls_module sys.modules[APP_LABEL].models = models_module sys.modules[APP_LABEL].urls = urls_module if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) else: from django.core.wsgi import get_wsgi_application get_wsgi_application()