RED EXPLOIT DEV/SEC BLOG

def contact_me() :

    print("https://github.com/r3dxpl0it")

    print("return_root@protonmail.com")

    print("Discord : )

Django REST framework Tutorial - 1

Mar 8, 2020 • Django,REST,API,Python,Python3,djangorestframework


Install the required packages.
pip install django
pip install djangorestframework
pip install pygments


Create a project.
django-admin startproject tutorial


Create an app.
cd tutorial
python manage.py startapp snippets


Add settings to INSTALLED_APP.

#tutorial/settings.py

INSTALLED_APPS = [
...
'rest_framework',
'snippets.apps.SnippetsConfig', ]

The difference from ordinary Django is that rest_framework is added.


Create a model to store code snippets.

#snippets/models.py

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)
    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']

Migration is done because the model was created.


Make DataBase Migrations and Migrate
python manage.py makemigrations snippets
python manage.py migrate


Creating a serializer

#snippets/serializers.py

The serializer converts a python instance to JSON format and vice versa. Something like the API version of Form.

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES

class SnippetSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    code = serializers.CharField(style={'base_template': 'textarea.html'})
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

    def create(self, validate_data):
        """
        Create and return a new 'Snippet' instance, given validated data.
        """
        return Snippet.objects.create(**validate_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing 'Snippet' instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.language)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance

The serializer defines the fields to be serialized with serialization. It defines what to do at the time of save with create and update. serializer.HogeField has many validation flags as well as forms. You can also change the display to suit your specific situation. {‘base_template’: ‘textarea.html’} does the same thing as widget = wigets.Texarea.


Using a serializer

#snippets/serializers.py

rom snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

snippet = Snippet(code='foo = "bar"\n')
snippet.save()
serializer = SnippetSerializer(snippet)
serializer.data
serializer = SnippetSerializer(snippet)
serializer.data
=> {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
content = JSONRenderer().render(serializer.data)
content
=> b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'

import me
stream = io.BytesIO(content)
data = JSONParser().parse(stream)

serializer = SnippetSerializer(data=data)
serializer.is_valid()
=> True
serializer.validated_data
=> OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()
serializer = SnippetSerializer(Snippet.onjects.all(), many=True)
serializer.data
=> [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]


Create a model serializer.

Using a model serializer makes the code more verbose and functional.

#snippets/views.py


class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ['id, 'title', 'code', 'linenos', 'language', 'style']


Create a normal view using Serializer.
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
form snippets.models import Snippet
from snippets.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=200)
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt is not used originally because it is attached so that it can be posted without a csrf token.

@csrf_token(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(serialzer.data)
        return JsonResponse(serializer.errors, status=400)

   elif request.method == 'DELETE':
       snippet.delete()
       return HttpResponse(status=204)
from django.urls import path
from snippets import views

urlpatterns = [
    path('snippets/', views.snippet_list),
    path('snippets/<int:pk>/', views.snippet_detail),
]

from django.urls import path, include

urlpatterns = [ path(‘’, include(‘snippets.urls’), ]


Linking url

#snippets/urls.py

from django.urls import path
from snippets import views

urlpatterns = [
    path('snippets/', views.snippet_list),
    path('snippets/<int:pk>/', views.snippet_detail),
]

#snippets/urls.py

from django.urls import path, include

urlpatterns = [
    path('', include('snippets.urls'),
]


Test APP
python manage.py runserver

Did you Like the post? Get the feed Or Share on : { Twitter, Linkedin, Facebook, Reddit, Email } !!