Size: 8390
Comment:
|
Size: 8502
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 49: | Line 49: |
from tutorial.quickstart.models import Task | |
Line 53: | Line 54: |
# select fields to return | |
Line 55: | Line 55: |
Line 59: | Line 60: |
# select fields to return | |
Line 61: | Line 61: |
class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id','task','created'] |
Django REST framework
Django REST framework is a powerful and flexible toolkit for building Web APIs.
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/
22
23 sqlite3 db.sqlite3
24 .tables
25 select * from auth_user;
26 .exit
27
28 python3 manage.py collectstatic
29 mkdir -p static/others
30 echo "aaaa" > static/others/test.txt
31
32 curl -H 'Accept: application/json' -u admin:1234567 http://127.0.0.1:8000/helloworld/
33 curl -H 'Accept: application/json' -u admin:12345678 http://127.0.0.1:8000/helloworldanon/
34 curl http://127.0.0.1:8000/helloworldviewset/
35 curl http://127.0.0.1:8000/static/others/test.txt
tutorial/quickstart/serializers.py
1 from django.contrib.auth.models import User, Group
2 from rest_framework import serializers
3 from tutorial.quickstart.models import Task
4
5 class UserSerializer(serializers.HyperlinkedModelSerializer):
6 class Meta:
7 model = User
8 fields = ['url', 'username', 'email', 'groups']
9
10
11 class GroupSerializer(serializers.HyperlinkedModelSerializer):
12 class Meta:
13 model = Group
14 fields = ['url', 'name']
15
16 class TaskSerializer(serializers.ModelSerializer):
17 class Meta:
18 model = Task
19 fields = ['id','task','created']
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 from django.views.decorators.csrf import csrf_exempt
6 from rest_framework.authentication import SessionAuthentication, BasicAuthentication
7 from rest_framework.permissions import IsAuthenticated
8 from rest_framework.response import Response
9 from rest_framework.decorators import api_view, authentication_classes, permission_classes
10 from rest_framework.views import APIView
11
12
13 class UserViewSet(viewsets.ModelViewSet):
14 """
15 API endpoint that allows users to be viewed or edited.
16 """
17 queryset = User.objects.all().order_by('-date_joined')
18 serializer_class = UserSerializer
19 permission_classes = [permissions.IsAuthenticated]
20
21
22 class GroupViewSet(viewsets.ModelViewSet):
23 """
24 API endpoint that allows groups to be viewed or edited.
25 """
26 queryset = Group.objects.all()
27 serializer_class = GroupSerializer
28 permission_classes = [permissions.IsAuthenticated]
29
30
31 @csrf_exempt
32 @api_view(['GET'])
33 @authentication_classes([SessionAuthentication, BasicAuthentication])
34 @permission_classes([IsAuthenticated])
35 def hello_world(request):
36 """
37 Function view
38 """
39 return Response({"message": "Hello world", "user": str(request.user)})
40
41
42 class HelloWorldAnonView(APIView):
43 def get(self, request, format=None):
44 return Response({"message": "Hello world anonymous", "user": str(request.user)})
45
46
47 class HelloWorldViewSet(viewsets.ViewSet):
48 # authentication required
49 permission_classes = [permissions.IsAuthenticated]
50
51 def list(self, request):
52 return Response({"message": "Hello world view set up and running " + str(request.user)})
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 router.register(r'helloworldviewset', views.HelloWorldViewSet,basename="")
9
10 # Wire up our API using automatic URL routing.
11 # Additionally, we include login URLs for the browsable API.
12 urlpatterns = [
13 path('', include(router.urls)),
14 path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
15 path('helloworld/',views.hello_world),
16 path('helloworldanon/',views.HelloWorldAnonView.as_view()),
17 ]
tutorial/settings.py
1 """
2 Django settings for tutorial project.
3
4 Generated by 'django-admin startproject' using Django 3.2.5.
5
6 For more information on this file, see
7 https://docs.djangoproject.com/en/3.2/topics/settings/
8
9 For the full list of settings and their values, see
10 https://docs.djangoproject.com/en/3.2/ref/settings/
11 """
12
13 from pathlib import Path
14 import os
15 # Build paths inside the project like this: BASE_DIR / 'subdir'.
16 BASE_DIR = Path(__file__).resolve().parent.parent
17
18
19 # Quick-start development settings - unsuitable for production
20 # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
21
22 # SECURITY WARNING: keep the secret key used in production secret!
23 SECRET_KEY = 'django-insecure-j8vs^2rq97)%g%v4fk-nl(3pho4ve)=6%&$**0++$p%v514r8r'
24
25 # SECURITY WARNING: don't run with debug turned on in production!
26 DEBUG = True
27
28 ALLOWED_HOSTS = []
29
30
31 # Application definition
32
33 INSTALLED_APPS = [
34 'django.contrib.admin',
35 'django.contrib.auth',
36 'django.contrib.contenttypes',
37 'django.contrib.sessions',
38 'django.contrib.messages',
39 'django.contrib.staticfiles',
40 'rest_framework',
41 ]
42
43 MIDDLEWARE = [
44 'django.middleware.security.SecurityMiddleware',
45 'django.contrib.sessions.middleware.SessionMiddleware',
46 'django.middleware.common.CommonMiddleware',
47 'django.middleware.csrf.CsrfViewMiddleware',
48 'django.contrib.auth.middleware.AuthenticationMiddleware',
49 'django.contrib.messages.middleware.MessageMiddleware',
50 'django.middleware.clickjacking.XFrameOptionsMiddleware',
51 ]
52
53 ROOT_URLCONF = 'tutorial.urls'
54
55 TEMPLATES = [
56 {
57 'BACKEND': 'django.template.backends.django.DjangoTemplates',
58 'DIRS': [],
59 'APP_DIRS': True,
60 'OPTIONS': {
61 'context_processors': [
62 'django.template.context_processors.debug',
63 'django.template.context_processors.request',
64 'django.contrib.auth.context_processors.auth',
65 'django.contrib.messages.context_processors.messages',
66 ],
67 },
68 },
69 ]
70
71 WSGI_APPLICATION = 'tutorial.wsgi.application'
72
73
74 # Database
75 # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
76
77 DATABASES = {
78 'default': {
79 'ENGINE': 'django.db.backends.sqlite3',
80 'NAME': BASE_DIR / 'db.sqlite3',
81 }
82 }
83
84
85 # Password validation
86 # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
87
88 AUTH_PASSWORD_VALIDATORS = [
89 {
90 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
91 },
92 {
93 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
94 },
95 {
96 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
97 },
98 {
99 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
100 },
101 ]
102
103
104 # Internationalization
105 # https://docs.djangoproject.com/en/3.2/topics/i18n/
106
107 LANGUAGE_CODE = 'en-us'
108
109 TIME_ZONE = 'UTC'
110
111 USE_I18N = True
112
113 USE_L10N = True
114
115 USE_TZ = True
116
117
118 # Static files (CSS, JavaScript, Images)
119 # https://docs.djangoproject.com/en/3.2/howto/static-files/
120
121 STATIC_URL = '/static/'
122 STATIC_ROOT = os.path.join(BASE_DIR, 'static')
123 STATICFILES_DIRS = (
124 ("others", os.path.join(STATIC_ROOT,'others')),
125 )
126
127 # Default primary key field type
128 # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
129
130 DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
131
132 REST_FRAMEWORK = {
133 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
134 'PAGE_SIZE': 10
135 }