Size: 6381
Comment:
|
Size: 6901
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 100: | Line 100: |
""" Django settings for tutorial project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ |
|
Line 101: | Line 113: |
import os | |
Line 103: | Line 116: |
Line 105: | Line 120: |
Line 107: | Line 123: |
Line 109: | Line 126: |
Line 110: | Line 128: |
Line 111: | Line 131: |
Line 120: | Line 141: |
Line 129: | Line 151: |
Line 130: | Line 153: |
Line 145: | Line 169: |
Line 146: | Line 171: |
Line 148: | Line 175: |
Line 154: | Line 182: |
Line 156: | Line 186: |
Line 170: | Line 201: |
Line 172: | Line 205: |
Line 173: | Line 207: |
Line 174: | Line 209: |
Line 175: | Line 211: |
Line 176: | Line 213: |
Line 177: | Line 215: |
Line 179: | Line 219: |
Line 180: | Line 221: |
STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( ("others", os.path.join(STATIC_ROOT,'others')), ) |
|
Line 182: | Line 228: |
Line 183: | Line 230: |
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/
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 from django.views.decorators.csrf import csrf_exempt
6 from django.http import JsonResponse
7
8 class UserViewSet(viewsets.ModelViewSet):
9 """
10 API endpoint that allows users to be viewed or edited.
11 """
12 queryset = User.objects.all().order_by('-date_joined')
13 serializer_class = UserSerializer
14 permission_classes = [permissions.IsAuthenticated]
15
16 class GroupViewSet(viewsets.ModelViewSet):
17 """
18 API endpoint that allows groups to be viewed or edited.
19 """
20 queryset = Group.objects.all()
21 serializer_class = GroupSerializer
22 permission_classes = [permissions.IsAuthenticated]
23
24 @csrf_exempt
25 def hello_world(request):
26 return JsonResponse({"message":"Hello world"}, safe=False)
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 """
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 }