Maxi Sbrocca
Maxi Sbrocca

Reputation: 66

Can django webapp and django-rest-framework live together?

I have a Django WebApp to administrate certain things of my business. It's currently using Django 1.5.5, but I just migrated the code to Django 1.11.

The thing is that we are developing another apps using other technologies, and due to all my information is in the Django app, I decided to add Django Rest Framework to my existing Django Webapp. All ok so far, beautiful, API with Token access... happy...

But, then I realized that on PROD env, I've ALLOWED_HOST setting. :(. I added that line in my devbox, and the happiness end.

I tried adding CORS support using django-cors-headers, but, so far, I've not successful.

So, to avoid wasting time, I want to ask to people that knows more than me about it, if the Django App and the DRF API can live together, without removing the ALLOWED_HOST setting or setting it as ALLOWED_HOSTS = ['*'].

Thanks in advance!

UPDATE

My settings.py file looks like this:

# Django settings for dojosite project.
# -*- coding:  utf-8 -*-
import os
import datetime

DEBUG = True

ALLOWED_HOSTS = ['www.myapp.com']

...

MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware'
)



TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [(os.path.join(ROOT_PATH, 'templates'),)],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.i18n',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'django.contrib.humanize',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'myapp',
)

...

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissions',
    ]
}


# JWT settings
JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_response_payload_handler',

    'JWT_SECRET_KEY': SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'Bearer',
    'JWT_AUTH_COOKIE': None,
}

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False

That configuration is causing that ALLOWED_HOSTS is applied to the WebApp urls and also to the API URLs.

UPDATE 2

Something I didn't say, is that I want that API public. I mean, let's suppose that I didn't know which hosts will invoke my API. So, what I want to do is:

WebApp: should be just called from known hosts (ALLOWED_HOSTS should be applied)

API: can be called from unknown hosts (ALLOWED_HOSTS control should not be applied here).

Is this possible? How can I achieve this?

Thanks!

Upvotes: 0

Views: 278

Answers (1)

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3974

Yes you can use Django Rest Framework with your Django webapp with no problem at all. Moving to cors part you should first install pip install django-cors-headers then add corsheaders to installed apps

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

Add middleware properly in settings.py

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ... ]

lastly you should do in settings.py as you are allowing every host

CORS_ORIGIN_ALLOW_ALL = True

else make the whitelist

CORS_ORIGIN_WHITELIST = (
    'hostname.example.com',
    'localhost:8000',
    '127.0.0.1:9000'
)

Upvotes: 1

Related Questions