Compare commits

...

9 Commits

Author SHA1 Message Date
eb24f56b7c
object level permissions, basic auth flow achvd 2022-01-08 05:29:03 +05:30
17f5199fa1
routing for auth 2022-01-08 05:25:14 +05:30
18b063713e
permissions 2022-01-08 05:18:12 +05:30
3632f27583
user association 2 2022-01-08 05:13:06 +05:30
e8cd3c33d2
user association 1 2022-01-08 05:10:31 +05:30
a004b3eb0e
generic cbviews 2022-01-08 04:59:57 +05:30
37bf9a0c82
class based views 2022-01-08 04:58:32 +05:30
01035a2b45
Reqest Response 2022-01-08 04:54:32 +05:30
d414868d93
serializers 2022-01-08 04:42:34 +05:30
19 changed files with 200 additions and 3 deletions

3
.gitignore vendored
View File

@ -1,3 +1,4 @@
venv
.vscode
__pycache__
__pycache__
db.sqlite3

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
djangorestframework==3.13.1
psycopg2==2.9.2
Pygments==2.11.2
pytz==2021.3
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):
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)
created_on = models.DateTimeField(auto_now_add=True)
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,39 @@
from django.db import models
# pygments
from pygments import highlight
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
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)
owner = models.ForeignKey('auth.user', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField
class Meta:
ordering = ['created']
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = 'table' if self.linenos else False
options = {'title': self.title} if self.title else {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs)

View File

@ -0,0 +1,15 @@
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user

View File

@ -0,0 +1,17 @@
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Snippet
fields = ['id', 'title', 'owner', 'code', 'linenos', 'language', 'style']
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
class Meta:
model = User
fields = ['id', 'username', 'snippets']

View File

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

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

@ -0,0 +1,12 @@
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
path('users/', views.UserList.as_view()),
path('users/<int:pk>/', views.UserDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

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

@ -0,0 +1,29 @@
from django.contrib.auth.models import User
from .models import Snippet
from .serializers import SnippetSerializer, UserSerializer
from .permissions import IsOwnerOrReadOnly
from rest_framework import generics, permissions
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer

View File

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

View File

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