2021-12-16 Ubuntu下創(chuàng)建 Django Restframework 項(xiàng)目

Django REST Framework 可以在Django 的基礎(chǔ)上迅速實(shí)現(xiàn) RESTFul API,并且自身還帶有WEB的測(cè)試頁(yè)面,可以方便的測(cè)試自己的API。

官網(wǎng): https://www.django-rest-framework.org/

1. 系統(tǒng)環(huán)境

? Ubuntu :18.04.x LTS (x86_64)

? MySQL:5.7.x

? Python: >= 3.6.x

? Pip: >= 9.0.x

? 系統(tǒng)環(huán)境的安裝,參考 http://www.itdecent.cn/p/bbd9dfd4c41e

2. 安裝 Django 相關(guān)

? ? $ sudo pip install django? ? # 安裝 Django

? ? $ sudo pip install djangorestframework

? ? $ sudo pip install django-oauth-toolkit? ? # OAuth2.0,非必選

3. 創(chuàng)建 Django 項(xiàng)目

? ? $ django-admin startproject 'restdemo'

4. 添加 app

? ? 進(jìn)入 'restdemo', 運(yùn)行:

? ? $ python manage.py startapp 'restapi'

5. 修改 settings.py

? ? DATABASES = {

? ? ? ? 'default': {

? ? ? ? ? ? 'ENGINE': 'django.db.backends.mysql',

? ? ? ? ? ? 'NAME': 'restdemo',

? ? ? ? ? ? 'USER': 'root',

? ? ? ? ? ? 'PASSWORD': '123456',

? ? ? ? ? ? 'HOST': 'localhost',

? ? ? ? ? ? 'PORT': '3306',

? ? ? ? }

? ? }

? ? INSTALLED_APPS = [

? ? ? ? ...

? ? ? ? 'rest_framework',

? ? ? ? 'oauth2_provider',

? ? ? ? 'restapi',

? ? ]

? ? # Django restframework & oauth2.0 settings

? ? OAUTH2_PROVIDER = {

? ? ? # this is the list of available scopes

? ? ? ? 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}

? ? }

? ? REST_FRAMEWORK = {

? ? ? ? 'DEFAULT_AUTHENTICATION_CLASSES': (

? ? ? ? ? ? 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',

? ? ? ? ),

? ? ? ? 'DEFAULT_PERMISSION_CLASSES': (

? ? ? ? ? ? 'rest_framework.permissions.IsAuthenticated',

? ? ? ? )

? ? }

? ? 運(yùn)行:

? ? $ python manage.py migrate

? ? $ python manage.py createsuperuser? ? #? 創(chuàng)建用戶 admin,密碼 123456

? ? $ python manage.py runserver localhost:8000


6. 添加/修改文件

? ? 1) 修改 restapi/models.py

? ? ? from django.db import models

? ? ? # Create your models here.

? ? ? class Testbed(models.Model):

? ? ? ? created = models.DateTimeField(auto_now_add=True)

? ? ? ? name = models.CharField(max_length=50, blank=True, default='')

? ? ? ? platform = models.CharField(max_length=50, blank=True, default='windows')

? ? ? comments = models.CharField(max_length=100, blank=True, default='')

? ? ? class Meta:

? ? ? ? ordering = ('created',)

? 2)添加 restapi/serializers.py

? ? ? from rest_framework import serializers

? ? ? from restapi.models import Testbed

? ? ? class TestbedModelSerializer(serializers.ModelSerializer):

? ? ? ? ? class Meta:

? ? ? ? ? ? ? model = Testbed

? ? ? ? ? ? ? fields = ('id', 'name', 'platform', 'comments')


? ? 3)修改 restapi/urls.py

? ? ? from django.urls import path, include

? ? ? from restapi import views

? ? ? urlpatterns = [

? ? ? ? path('testbeds/', views.TestbedList.as_view(), name='testbeds_list'),

? ? ? ? path('testbeds/<int:pk>/', views.TestbedDetail.as_view(), name='testbeds_detail'),

? ? ? ? #path('demo/', views.demo),

? ? ]

? ? 4) 修改 restapi/views.py

? ? ? from django.shortcuts import render

? ? ? from rest_framework import generics

? ? ? from restapi.models import Testbed

? ? ? from restapi.serializers import TestbedModelSerializer

? ? ? def demo(request):

? ? ? ? ? return render(request, "demo.html")

? ? ? class TestbedList(generics.ListCreateAPIView):

? ? ? ? ? queryset = Testbed.objects.all()

? ? ? ? ? serializer_class = TestbedModelSerializer

? ? ? class TestbedDetail(generics.RetrieveUpdateDestroyAPIView):

? ? ? ? ? queryset = Testbed.objects.all()

? ? ? ? ? serializer_class = TestbedModelSerializer

? ? ? 5)修改 restdemo/urls.py

? ? ? from django.contrib import admin

? ? ? from django.urls import path, include

? ? ? urlpatterns = [

? ? ? ? ? path('admin/', admin.site.urls),

? ? ? ? ? path('v1/', include('restapi.urls')),

? ? ? ? ? path('oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),?

? ? ? ? #path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),

? ? ? ]

? ? 6) 添加 init_db.json

? ? ? [

? ? ? ? {

? ? ? ? ? "model": "restapi.testbed",

? ? ? ? ? "pk": "1",

? ? ? ? ? "fields": {

? ? ? ? ? ? "name": "testbed_01",

? ? ? ? ? ? "platform": "windows",

? ? ? ? ? ? "comments": "Test for windows app",

? ? ? ? ? ? "created": "2018-6-17"

? ? ? ? ? }

? ? ? ? },

? ? ? ...

? ? ? ]


? ? ? $ python manage.py makemigrations

? ? ? $ python manage.py migrate

? ? ? $ python manage.py loaddata init_db.json? ? ? # demo data for testbeds

? ? ? $ python manage.py runserver localhost:8000


7. 訪問 API (沒有OAuth2驗(yàn)證的版本)

? http://localhost:8000/v1/testbeds/

? Return:

? {

? ? ? "detail": "Authentication credentials were not provided."

? }


8. 注冊(cè) OAuth2 客戶端

? 1) 登錄

? ? ? http://localhost:8000/admin

? ? ? Username: admin

? ? ? Password: 123456

? 2) 注冊(cè)

? ? ? http://localhost:8000/oauth2/applications/register/

? ? ? -- For example --

? ? ? Name: RestAPI Demo

? ? ? Client id: 8F0R4FdXfYg6FQjd0rSPnY0tsg4GE7FwuB9kGM5Y

? ? ? Client secret: 6Y5TGseG6eFXr9C6j4LB9w04MT1ZAzCrrUOXtnJgnSxmlHqZciMMYYQOScEZPLV3bYrTZuj2d8pymJXDQl8YfFvSxzJTX6xBZdMTpWpxqRhcSNzsbjNhny7pDGS4PKdc

? ? ? Client type: Confidential

? ? ? Authorization grant type: Resource owner password-based

? ? ? Redirect uris:

? ? * client id/secret 是 register 頁(yè)面自動(dòng)生成的, grant type 是 password, OAuth2.0 grant 其它訪問方式,這里不討論。


9. 訪問 API

? ? http://localhost:8000/v1/testbeds/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容