Last Updated: January 27, 2021
·
988
· kalinin84

Django

#!/bin/bash


cat > requirements.txt <<EOL
django==3.0.7
psycopg2==2.8.5
djangorestframework==3.11.0
markdown==3.2.2
django-filter==2.3.0
EOL


cat > Dockerfile <<EOL
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
EOL


cat > docker-compose.yml <<EOL
version: '3'

services:
  db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"
  redis:
    image: "redis:alpine"
    ports:
      - "6379:6379"
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
      - redis
EOL


docker-compose build
docker-compose run web django-admin startproject application .
docker-compose up -d
docker-compose run web python manage.py startapp corpus
docker-compose run web python manage.py makemigrations
docker-compose run web python manage.py migrate
docker-compose logs web
chown -R $USER:$USER .
docker-compose run web python manage.py createsuperuser
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from corpus import views


router = routers.DefaultRouter()
router.register(r'documents', views.DocumentViewSet)


urlpatterns = [
    path('', include(router.urls)),
    path('admin/', admin.site.urls)
]
from django.contrib import admin
from .models import Document


admin.site.register(Document)
from .models import Document
from rest_framework import viewsets
from .serializers import DocumentSerializer


class DocumentViewSet(viewsets.ModelViewSet):
    queryset = Document.objects.all().order_by('-id')
    serializer_class = DocumentSerializer
from .models import Document
from rest_framework import serializers


class DocumentSerializer(serializers.ModelSerializer):
    content_size = serializers.SerializerMethodField()

    def get_content_size(self, obj):
        return len(obj.content)

    class Meta:
        model = Document
        fields = ['id', 'target', 'content', 'content_size']
from django.db import models


class Document(models.Model):
    TARGETS = (
        (0, 'Bad'),
        (1, 'Good'),
    )
    target = models.IntegerField(default=TARGETS[0][0], choices=TARGETS)
    content = models.TextField()

    def __str__(self):
        return 'ID: {} (target: {})'.format(self.id, self.target)