serializers

This commit is contained in:
Pratyush Desai 2022-01-08 04:42:34 +05:30
parent a88dec9610
commit d414868d93
Signed by: pratyush
GPG Key ID: DBA5BB7505946FAD
17 changed files with 163 additions and 2 deletions

View File

@ -0,0 +1,6 @@
# Django Backend for LibertaCasa
## Setup
* Use a virtual environment and `pip install -r requirements.txt`
* deps: `psychopg2`, `django`, `djangorestframework`.

View File

@ -2,5 +2,6 @@ asgiref==3.4.1
Django==4.0 Django==4.0
djangorestframework==3.13.1 djangorestframework==3.13.1
psycopg2==2.9.2 psycopg2==2.9.2
Pygments==2.11.2
pytz==2021.3 pytz==2021.3
sqlparse==0.4.2 sqlparse==0.4.2

View File

@ -0,0 +1,24 @@
# Generated by Django 4.0 on 2022-01-07 23:05
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200, unique=True)),
('updated_on', models.DateTimeField(auto_now=True)),
('created_on', models.DateTimeField(auto_now_add=True)),
('content', models.TextField()),
],
),
]

View File

@ -11,7 +11,7 @@ STATUS = (
class Post(models.Model): class Post(models.Model):
title = models.CharField(max_length=200, unique=True) title = models.CharField(max_length=200, unique=True)
author = models.ForeignKey('user.auth',on_delete=models.CASCADE) # author = models.ForeignKey('user.auth',on_delete=models.CASCADE)
updated_on =models.DateTimeField(auto_now= True) updated_on =models.DateTimeField(auto_now= True)
created_on = models.DateTimeField(auto_now_add=True) created_on = models.DateTimeField(auto_now_add=True)
content = models.TextField() content = models.TextField()

BIN
website/db.sqlite3 Normal file

Binary file not shown.

View File

View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
website/snippets/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class SnippetsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'snippets'

File diff suppressed because one or more lines are too long

View File

View File

@ -0,0 +1,21 @@
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
# modified?
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Meta:
ordering = ['created']

View File

@ -0,0 +1,7 @@
from rest_framework import serializers
from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']

View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

7
website/snippets/urls.py Normal file
View File

@ -0,0 +1,7 @@
from django.urls import path
from . import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]

49
website/snippets/views.py Normal file
View File

@ -0,0 +1,49 @@
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from .models import Snippet
from .serializers import SnippetSerializer
@csrf_exempt
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
snippet.delete()
return HttpResponse(status=204)

View File

@ -37,6 +37,10 @@ INSTALLED_APPS = [
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'rest_framework',
'snippets.apps.SnippetsConfig',
'blog.apps.BlogConfig',
'api.apps.ApiConfig',
] ]
MIDDLEWARE = [ MIDDLEWARE = [

View File

@ -14,8 +14,9 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
""" """
from django.contrib import admin from django.contrib import admin
from django.urls import path from django.urls import path, include
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('', include('snippets.urls')),
] ]