MoinMoin Logo
  • Comments
  • Immutable Page
  • Menu
    • Navigation
    • RecentChanges
    • FindPage
    • Local Site Map
    • Help
    • HelpContents
    • HelpOnMoinWikiSyntax
    • Display
    • Attachments
    • Info
    • Raw Text
    • Print View
    • Edit
    • Load
    • Save
  • Login

Navigation

  • Start
  • Sitemap

Upload page content

You can upload content for the page named below. If you change the page name, you can also upload content for another page. If the page name is empty, we derive the page name from the file name.

File to load page content from
Page name
Comment

Revision 8 as of 2021-07-20 11:07:46
  • Python
  • DjangoREST

Django REST framework

  • https://www.django-rest-framework.org/tutorial/quickstart/#quickstart

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Quickstart

  • Based on https://www.django-rest-framework.org/tutorial/quickstart/#quickstart

   1 cd ~/tmp
   2 mkdir django-rest-test
   3 cd django-rest-test
   4 sudo apt install python3-venv
   5 python3 -m venv virtenv
   6 . virtenv/bin/activate
   7 pip install djangorestframework
   8 find . virtenv/
   9 django-admin startproject tutorial . 
  10 cd tutorial
  11 django-admin startapp quickstart
  12 cd ..
  13 python manage.py migrate # sync DB 
  14 python manage.py createsuperuser --email admin@example.com --username admin # create super user, pwd: 12345678 
  15 nano tutorial/quickstart/serializers.py
  16 nano tutorial/quickstart/views.py
  17 nano tutorial/urls.py
  18 nano tutorial/settings.py
  19 python manage.py runserver
  20 # Starting development server at http://127.0.0.1:8000/
  21 curl -H 'Accept: application/json; indent=4' -u admin:12345678 http://127.0.0.1:8000/users/

tutorial/quickstart/serializers.py

   1 from django.contrib.auth.models import User, Group
   2 from rest_framework import serializers
   3 
   4 class UserSerializer(serializers.HyperlinkedModelSerializer):
   5     class Meta:
   6         model = User
   7         # select fields to return
   8         fields = ['url', 'username', 'email', 'groups']
   9 
  10 class GroupSerializer(serializers.HyperlinkedModelSerializer):
  11     class Meta:
  12         model = Group
  13         # select fields to return
  14         fields = ['url', 'name']

tutorial/quickstart/views.py

   1 from django.contrib.auth.models import User, Group
   2 from rest_framework import viewsets
   3 from rest_framework import permissions
   4 from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
   5 
   6 class UserViewSet(viewsets.ModelViewSet):
   7     """
   8     API endpoint that allows users to be viewed or edited.
   9     """
  10     queryset = User.objects.all().order_by('-date_joined')
  11     serializer_class = UserSerializer
  12     permission_classes = [permissions.IsAuthenticated]
  13 
  14 class GroupViewSet(viewsets.ModelViewSet):
  15     """
  16     API endpoint that allows groups to be viewed or edited.
  17     """
  18     queryset = Group.objects.all()
  19     serializer_class = GroupSerializer
  20     permission_classes = [permissions.IsAuthenticated]

tutorial/urls.py

   1 from django.urls import include, path
   2 from rest_framework import routers
   3 from tutorial.quickstart import views
   4 
   5 router = routers.DefaultRouter()
   6 router.register(r'users', views.UserViewSet)
   7 router.register(r'groups', views.GroupViewSet)
   8 
   9 # Wire up our API using automatic URL routing.
  10 # Additionally, we include login URLs for the browsable API.
  11 urlpatterns = [
  12     path('', include(router.urls)),
  13     path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
  14     path('helloworld/',views.hello_world)
  15 ]

tutorial/settings.py

   1 from pathlib import Path
   2 # Build paths inside the project like this: BASE_DIR / 'subdir'.
   3 BASE_DIR = Path(__file__).resolve().parent.parent
   4 # Quick-start development settings - unsuitable for production
   5 # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
   6 # SECURITY WARNING: keep the secret key used in production secret!
   7 SECRET_KEY = 'django-insecure-j8vs^2rq97)%g%v4fk-nl(3pho4ve)=6%&$**0++$p%v514r8r'
   8 # SECURITY WARNING: don't run with debug turned on in production!
   9 DEBUG = True
  10 ALLOWED_HOSTS = []
  11 # Application definition
  12 INSTALLED_APPS = [
  13     'django.contrib.admin',
  14     'django.contrib.auth',
  15     'django.contrib.contenttypes',
  16     'django.contrib.sessions',
  17     'django.contrib.messages',
  18     'django.contrib.staticfiles',
  19     'rest_framework',
  20 ]
  21 MIDDLEWARE = [
  22     'django.middleware.security.SecurityMiddleware',
  23     'django.contrib.sessions.middleware.SessionMiddleware',
  24     'django.middleware.common.CommonMiddleware',
  25     'django.middleware.csrf.CsrfViewMiddleware',
  26     'django.contrib.auth.middleware.AuthenticationMiddleware',
  27     'django.contrib.messages.middleware.MessageMiddleware',
  28     'django.middleware.clickjacking.XFrameOptionsMiddleware',
  29 ]
  30 ROOT_URLCONF = 'tutorial.urls'
  31 TEMPLATES = [
  32     {
  33         'BACKEND': 'django.template.backends.django.DjangoTemplates',
  34         'DIRS': [],
  35         'APP_DIRS': True,
  36         'OPTIONS': {
  37             'context_processors': [
  38                 'django.template.context_processors.debug',
  39                 'django.template.context_processors.request',
  40                 'django.contrib.auth.context_processors.auth',
  41                 'django.contrib.messages.context_processors.messages',
  42             ],
  43         },
  44     },
  45 ]
  46 WSGI_APPLICATION = 'tutorial.wsgi.application'
  47 # Database
  48 # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
  49 DATABASES = {
  50     'default': {
  51         'ENGINE': 'django.db.backends.sqlite3',
  52         'NAME': BASE_DIR / 'db.sqlite3',
  53     }
  54 }
  55 # Password validation
  56 # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
  57 AUTH_PASSWORD_VALIDATORS = [
  58     {
  59         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  60     },
  61     {
  62         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  63     },
  64     {
  65         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  66     },
  67     {
  68         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  69     },
  70 ]
  71 # Internationalization
  72 # https://docs.djangoproject.com/en/3.2/topics/i18n/
  73 LANGUAGE_CODE = 'en-us'
  74 TIME_ZONE = 'UTC'
  75 USE_I18N = True
  76 USE_L10N = True
  77 USE_TZ = True
  78 # Static files (CSS, JavaScript, Images)
  79 # https://docs.djangoproject.com/en/3.2/howto/static-files/
  80 STATIC_URL = '/static/'
  81 # Default primary key field type
  82 # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
  83 DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  84 REST_FRAMEWORK = {
  85     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
  86     'PAGE_SIZE': 10
  87 }
  • MoinMoin Powered
  • Python Powered
  • GPL licensed
  • Valid HTML 4.01