Commit c7ac0681 authored by Wickramasinghe R.J.P's avatar Wickramasinghe R.J.P

canis care backend added

parent 69a0ea3b
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
CanisCare_Backend
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="djangoProject/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/../djangoProject\templates" />
</list>
</option>
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N806" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (djangoProject)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/CanisCare_Backend.iml" filepath="$PROJECT_DIR$/.idea/CanisCare_Backend.iml" />
</modules>
</component>
</project>
\ No newline at end of file
from django.contrib import admin
from .models import Note
admin.site.register(Note)
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
# Generated by Django 4.1 on 2022-08-25 06:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Note',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('body', models.TextField()),
('updated', models.DateTimeField(auto_now=True)),
('created', models.DateTimeField(auto_now_add=True)),
],
options={
'ordering': ['-updated'],
},
),
]
from django.db import models
class Note(models.Model):
body = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
class Meta:
ordering = ['-updated']
from rest_framework.serializers import ModelSerializer
from .models import Note
class NoteSerializer(ModelSerializer):
class Meta:
model = Note
fields = '__all__'
from django.test import TestCase
# Create your tests here.
from django.urls import path
from . import views
urlpatterns = [
path('', views.getRoutes),
path('notes/', views.getNotes),
path('diseases/', views.get_diseases),
path('disease/<str:pk>/', views.get_disease_description),
path('disease/<str:pk>/<str:pk2>/', views.get_disease_sub),
path('disease/<str:pk>/<str:pk2>/<str:pk3>/', views.get_disease_sub_info),
path('notes/create/', views.createNote),
path('disease/treatment/', views.get_treatment),
path('notes/<str:pk>/update/', views.updateNote),
path('notes/<str:pk>/delete/', views.deleteNote),
path('notes/<str:pk>/', views.getNote),
]
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import NoteSerializer
from .models import Note
from owlready2 import *
from rdflib import *
# onto = get_ontology("C:\\Users\\LENOVO\\Desktop\\dogSkinDisease.owl").load(reload_if_newer = True)
# onto = get_ontology(
# "C:\\Users\\LENOVO\\Music\\Ontology Generation\\Ontology generation\\Fourth\\Ontology with uppercase disease "
# "name\\dogDisease.owl"
# ).load(
# reload_if_newer=True)
onto = get_ontology("C:\\Users\\LENOVO\\PycharmProjects\\buildOntology\\dogDisease.owl").load(reload_if_newer=True)
graph = default_world.as_rdflib_graph()
@api_view(['GET'])
def getRoutes(request):
routes = [
{
'EndPoint': '/notes/',
'method': 'GET',
'body': None,
'description': 'Returns an array of notes'
},
{
'EndPoint': '/notes/id',
'method': 'GET',
'body': None,
'description': 'Returns an array of notes'
},
{
'EndPoint': '/decease/treatment/',
'method': 'POST',
'body': {'decease': ""},
'description': 'Get treatments for the decease'
},
{
'EndPoint': '/notes/id/update/',
'method': 'PUT',
'body': {'body': ""},
'description': 'Updates an existing record with data sent in put request'
},
{
'EndPoint': '/notes/id/delete',
'method': 'DELETE',
'body': None,
'description': 'Deletes any existing note'
}
]
return Response(routes)
@api_view(['GET'])
def getNotes(request):
notes = Note.objects.all()
serializer = NoteSerializer(notes, many=True)
return Response(serializer.data)
@api_view(['GET'])
def getNote(request, pk):
notes = Note.objects.get(id=pk)
serializer = NoteSerializer(notes, many=False)
return Response(serializer.data)
@api_view(['GET'])
def get_disease_description(request, pk):
disease_description = list(graph.query(
"""
SELECT ?description
WHERE { ?disease <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#NamedDisease>;
FILTER(?disease = <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogDisease.owl#"""+pk+""">).
?disease <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#hasDescription> ?description.
}"""
))
new_disease_description = [str(x[0]) for x in disease_description]
new_disease_description = ' '.join(new_disease_description)
new_disease_description = new_disease_description.split('.')
new_disease_description = new_disease_description[1:-1]
print(new_disease_description)
return Response(new_disease_description)
@api_view(['GET'])
def get_disease_sub_info(request, pk, pk2, pk3):
global sci_name
new_pk2 = pk2[:-1]
if pk == "Dandruff":
sci_name = "seborrheic dermatitis"
elif pk == "Ringworm":
sci_name = "dermatophytes"
elif pk == "YeastInfection":
sci_name = "Malassezia pachydermatitis"
sub_list_info = list(graph.query(
"""
SELECT ?treatdescribe
WHERE { ?disease <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#NamedDisease>;
FILTER((?disease = <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogDisease.owl#""" + pk + """>) && (?treat = <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogDisease.owl#""" + pk3 + """>)).
?disease <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#has""" + new_pk2 + """> ?treat.
?treat <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#has""" + new_pk2 + """Description> ?treatdescribe.
}"""))
new_sub_list_info = [str(x[0]) for x in sub_list_info]
new_sub_list_info = ' '.join(new_sub_list_info)
new_sub_list_info = new_sub_list_info.split('.')
new_sub_list_info = new_sub_list_info[1:-1]
print(new_sub_list_info)
return Response(new_sub_list_info)
@api_view(['GET'])
def get_disease_sub(request, pk, pk2):
new_pk2 = pk2[:-1]
sub_list = list(graph.query(
"""
SELECT ?treat
WHERE { ?disease <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#NamedDisease>;
FILTER(?disease = <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogDisease.owl#""" + pk + """>).
?disease <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#has""" + new_pk2 + """> ?treat.
}"""))
new_sub_list = [str(x[0]) for x in sub_list]
fin_sub_list = []
for y in new_sub_list:
itm = y[y.find('#'):][1:]
fin_sub_list.append(itm)
return Response(new_sub_list)
@api_view(['GET'])
def get_diseases(request):
des_list = list(graph.query("""
SELECT ?disease
WHERE {
?disease <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#NamedDisease> .
}"""))
new_des_list = [str(x[0]) for x in des_list]
# index = []
# for y in range(len(new_list)):
# index.append(y + 1)
#
# print(index)
# disease_dict = dict.fromkeys(new_list, "disease")
# index_dict = dict.fromkeys(index, "id")
# d1 = dict(enumerate(new_list))
# print(disease_dict)
# print(index_dict)
fin_des_list = []
for y in new_des_list:
des = y[y.find('#'):][1:]
fin_des_list.append(des)
print(fin_des_list)
return Response(fin_des_list)
@api_view(['POST'])
def get_treatment(request):
data = request.data
disease = data['disease']
res = list(graph.query("""
SELECT ?disease ?treat ?treatdescribe
WHERE { ?disease <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#hasScientificName> ?o;
FILTER(REGEX(?o, \"""" + disease + """\", "i")).
?disease <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#hasTreatment> ?treat.
?treat <http://www.semanticweb.org/dogdisease/ontologies/2022/4/dogSkinDisease#hasTreatmentDescription> ?treatdescribe.
}"""))
return Response(res)
@api_view(['PUT'])
def updateNote(request, pk):
data = request.data
note = Note.objects.get(id=pk)
serializer = NoteSerializer(note, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def createNote(request):
data = request.data
note = Note.objects.create(
body=data['body']
)
serializer = NoteSerializer(note, many=False)
return Response(serializer.data)
@api_view(['DELETE'])
def deleteNote(request, pk):
data = request.data
note = Note.objects.get(id=pk)
note.delete()
return Response("Note has been deleted!")
"""
ASGI config for djangoProject 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/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings')
application = get_asgi_application()
"""
Django settings for djangoProject project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-3ts!3sf#jntwaa-9r(^t%7ty=nc03p_eil3yha%#hinc30b&ww'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['192.168.1.102', '192.168.1.101', '192.168.1.5', '192.168.1.100']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'rest_framework',
'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
"corsheaders.middleware.CorsMiddleware",
'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 = 'djangoProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'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 = 'djangoProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/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/4.1/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/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ALLOW_ALL_ORIGINS = True
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('api.urls'))
]
"""
WSGI config for djangoProject 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/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings')
application = get_wsgi_application()
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from owlready2 import *
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings')
# onto = get_ontology("C:\\Users\\LENOVO\\Documents\\Research\\dogSkinDisease.owl").load()
#
# default_world.set_backend(filename="disease.sqlite3")
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