Commit 44cfd9a3 by Rosa Delima Mendrofa

first commit

parents
"""
ASGI config for DjangoAPI 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/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoAPI.settings')
application = get_asgi_application()
"""
Django settings for DjangoAPI project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3xjo2(8qq_2k!zyix2*eccw5$lgs9tmsl(mol&z292p33_6_y0'
# 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',
'MyAPI',
]
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 = 'DjangoAPI.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 = 'DjangoAPI.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
)
}
"""DjangoAPI URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from MyAPI import views
urlpatterns = [
path('', views.home),
]
"""
WSGI config for DjangoAPI 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/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoAPI.settings')
application = get_wsgi_application()
from django.contrib import admin
from . models import approvals
# Register your models here.
admin.site.register(approvals)
from django.apps import AppConfig
class MyapiConfig(AppConfig):
name = 'MyAPI'
from django.forms import ModelForm
from . models import approvals
class MyForm(ModelForm):
class Meta:
model=approvals
fields = '__all__'
#exclude = 'firstname'
\ No newline at end of file
This diff is collapsed. Click to expand it.
from django.db import models
# Create your models here.
class approvals(models.Model):
ApplicationType= (
('Individu', 'Individu'),
('Join', 'Join')
)
EmploymentLength = (
('Old Employee', 'Old Employee'),
('New Employee', 'New Employee')
)
HomeOwnership = (
('MORTGAGE', 'MORTGAGE'),
('OWN', 'OWN'),
('RENT', 'RENT'),
('ANY', 'ANY'),
('OTHER', 'OTHER'),
('NONE', 'NONE')
)
PURPOSE = (
('debt_consolidation', 'debt_consolidation'),
('business', 'business'),
('asset', 'asset'),
('educational', 'educational'),
('medical', 'medical'),
('wedding', 'wedding'),
('vacation', 'vacation'),
('moving', 'moving'),
('other', 'other')
)
TERM = (
('60 months', '60 months'),
('36 months', '36 months')
)
firstname=models.CharField(max_length=15)
lastname=models.CharField(max_length=15)
annual_inc=models.IntegerField(default=0)
application_type=models.CharField(max_length=15, choices=ApplicationType)
dti=models.IntegerField(default=0)
emp_length=models.CharField(max_length=24, choices=EmploymentLength)
home_ownership=models.CharField(max_length=15, choices=HomeOwnership)
installment=models.IntegerField(default=0)
int_rate=models.IntegerField(default=0)
last_pymnt_amnt=models.IntegerField(default=0)
loan_amnt=models.IntegerField(default=0)
purpose=models.CharField(max_length=24, choices=PURPOSE)
term=models.CharField(max_length=24, choices=TERM)
loan_difference=models.IntegerField(default=0)
issue_d=models.DateField()
loan_freq=models.IntegerField(default=0)
def __str__(self):
return '{}'.format(self.lastname, self.firstname)
from rest_framework import serializers
from . models import approvals
class approvalsSerializers(serializers.ModelSerializer):
class Meta:
model=approvals
fields='__all__'
from django.test import TestCase
# Create your tests here.
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('MyAPI', views.ApprovalsView)
urlpatterns = [
path('', views.home),
#path('form/', views.myform, name='myform'),
#path('api/', include(router.urls)),
#path('status/', views.approvereject),
]
from django.shortcuts import render
from . forms import MyForm
from rest_framework import viewsets
from rest_framework.decorators import api_view
from django.core import serializers
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from . models import approvals
from . serializers import approvalsSerializers
import pickle
from sklearn.externals import joblib
import json
import numpy as np
from sklearn import preprocessing
import pandas as pd
def home(request):
return render(request, 'apps/home.html')
class ApprovalsView(viewsets.ModelViewSet):
queryset = approvals.objects.all()
serializer_class = approvalsSerializers
def myform(request):
if request.method=="POST":
form = MyForm(request.POST)
if form.is_valid():
myform = form.save(commit=False)
else:
form = MyForm()
@api_view(["POST"])
def approvereject(request):
try:
mdl=joblib.load("/Users/R. D. Mendrofa/DjangoAPI/MyAPI/loan_model.pkl")
mydata=pd.read_excel('/Users/R. D. Mendrofa/DjangoAPI/bankloan.csv')
mydata=request.data
unit=np.array(list(mydata.values()))
unit=unit.reshape(1,-1)
scalers=joblib.load("/Users/R. D. Mendrofa/DjangoAPI/MyAPIscalers.pkl")
X=scalers.transform(unit)
y_pred=mdl .predict(X)
y_pred=(y_pred>0.58)
newdf=pd.DataFrame(y_pred, columns=['loan_status'])
newdf=newdf.replace({True:'Approved', False:'Rejected'})
return JsonResponse('Your Status is {}'.format(newdf), safe=False)
except ValueError as e:
return Response(e.args[0], status.HTTP_400_BAD_REQUEST)
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoAPI.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()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment