Commit 286c63e2 authored by Yannick De-Oliveira's avatar Yannick De-Oliveira
Browse files

Mise en place schema

parent b4308e7b
/.project
/.pydevproject
*.pyc
*/__pycache__*
# API REST Django
## Mise en place de l'environnement
Ces étapes seront déjà réalisées dans la VM.<br>
Installer virtualenv et éventuellement pip s'ils ne sont pas déjà installés :<br>
`sudo apt-get install python3-venv`<br>
`sudo apt-get install python3-pip`<br>
Créer un environnement virtuel pour python :<br>
`python3 -m venv django-vuejs`<br>
Activer l'environnement virtuel :<br>
`source django-vuejs/bin/activate`<br>
Se déplacer dans le répertoire contenant le code source de l'api :<br>
`cd /mon/repository/git/django-rest-api/`<br>
Installer les dépendances :<br>
`pip install -r requirements.txt`
## Installer la base de données
Pour l'atelier il sera peut être plus simple d'utiiser SQLite. Pour créer la base de données il suffit d'executer la commande suivante<br>
`python manage.py migrate`
import json
from django.db import transaction
from protfamily.models import Family, Alignment, Stat, Tree
DATA_REPO = '../django-vue.js/data/'
ALIGNEMENTS_REPO = DATA_REPO+'/alignments/'
STATS_REPO = DATA_REPO+'/stats/'
TREES_REPO = DATA_REPO+'/trees/'
FAMILIES = ['orthomcl10','orthomcl12','orthomcl17', 'orthomcl909']
with transaction.atomic() :
for fam in FAMILIES :
family_object = Family.objects.create(name=fam)
align_fh = open('{0}{1}.fasta'.format(ALIGNEMENTS_REPO, fam),'r')
align_object = None
sequence = ""
for line in align_fh.readlines() :
if line.startswith('>') :
if align_object != None:
align_object.seq = sequence
align_object.save()
sequence = ""
align_object = Alignment()
align_object.seq_id = line[1:].strip()
align_object.family = family_object
else :
sequence = sequence+line.strip()
align_object.seq = sequence
align_object.save()
align_fh.close()
stat_fh = open('{0}{1}.json'.format(STATS_REPO, fam),'r')
stats_data = json.load(stat_fh)
Stat.objects.create(family = family_object,
proteins = stats_data['proteins'],
species = stats_data['species'])
stat_fh.close()
tree_fh = open('{0}{1}.newick'.format(TREES_REPO, fam),'r')
Tree.objects.create(family = family_object,
tree = tree_fh.read().strip())
tree_fh.close()
\ No newline at end of file
File added
"""
Django settings for django_api project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'lt#3%qeyg%n&h(ozbu9z$!(dqttm+b(%)o2$^li81m-c3#d%-8'
# 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',
'protfamily'
]
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 = 'django_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 = 'django_api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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/2.2/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/2.2/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/2.2/howto/static-files/
STATIC_URL = '/static/'
"""django_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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
urlpatterns = [
path('admin/', admin.site.urls),
]
"""
WSGI config for django_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/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_api.settings')
application = get_wsgi_application()
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_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()
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ProtfamilyConfig(AppConfig):
name = 'protfamily'
# Generated by Django 2.2 on 2021-07-29 09:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Family',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Family name')),
],
),
migrations.CreateModel(
name='Tree',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tree', models.TextField(verbose_name='Tree')),
('family', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='protfamily.Family')),
],
),
migrations.CreateModel(
name='Stat',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('proteins', models.TextField(verbose_name='Proteins')),
('species', models.TextField(verbose_name='Species')),
('family', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='protfamily.Family')),
],
),
migrations.CreateModel(
name='Alignment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('seq_id', models.CharField(max_length=250, verbose_name='Id')),
('seq', models.TextField(verbose_name='Sequence')),
('family', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='protfamily.Family')),
],
),
]
from django.db import models
from django.db.models.deletion import CASCADE
# Create your models here.
class Family(models.Model):
name = models.CharField("Family name", max_length=150)
def __str__(self):
return self.name
class Alignment(models.Model):
seq_id = models.CharField("Id", max_length=250)
seq = models.TextField("Sequence")
family = models.ForeignKey('Family', on_delete=CASCADE)
def __str__(self):
return self.seq_id
class Stat(models.Model):
proteins = models.TextField("Proteins")
species = models.TextField("Species")
family = models.ForeignKey('Family', on_delete=CASCADE)
def __str__(self):
return self.family.name
class Tree(models.Model):
tree = models.TextField("Tree")
family = models.ForeignKey('Family', on_delete=CASCADE)
def __str__(self):
return self.family.name
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.shortcuts import render
# Create your views here.
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