Python Django API (rest)

編輯 : Frank
日期 : 2019/09/09
參考網址


最終成果

op (?a=1&b=2)

op2 (/a/b)

組織圖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
restapi
+
|
+-----> manage.py
|
+-----> db.sqlite3
|
+-----> restapi
| +
| |
| +-----> __init__.py
| |
| +-----> setting.py
| |
| +-----> urls.py
| |
| +-----> wsgi.py
|
+-----> api
+
|
+-----> admin.py
|
+-----> __init__.py
|
+-----> models.py
|
+-----> urls.py
|
+-----> views.py
|
+-----> apps.pu
|
+-----> tests.py

啟動 : python3 manage.py runserver
連接 : 127.0.0.1:8000/api
畫圖工具 : http://stable.ascii-flow.appspot.com/#Draw

環境

python 3
django 2.2

套件

1
2
pip3 install django
pip3 install djangorestframework

Django專案

django-admin startproject restapi

/restapi/settings.py 添加restframework與自定義的apps

1
2
3
4
5
INSTALLED_APPS = [
...
'rest_framework',
'api.apps.ApiConfig',
]

/restapi/urls.py 添加網址路徑

1
2
3
4
5
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/',include('rest_framework.urls')),
path('api/',include('api.urls'))
]

Django Apps

python3 manage.py startapp api

/api/views

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.shortcuts import render
from rest_framework.decorators import api_view,throttle_classes,permission_clas$
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.permissions import IsAuthenticated

# Create your views here.

# 每天只能使用一次
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'

@api_view(['GET'])
@permission_classes((IsAuthenticated, )) # 授權設置,需登入使用
#@throttle_classes([OncePerDayUserThrottle]) # 設定調用限制
def op(request,format=None):
number1 = request.GET.get('number1')
number2 = request.GET.get('number2')

add = int(number1) + int(number2)
return Response({"add":add})

@api_view(['GET'])
@permission_classes((IsAuthenticated, )) # 授權設置,需登入使用
#@throttle_classes([OncePerDayUserThrottle]) # 設定調用限制
def op2(request,a=0,b=0):
add = int(a) + int(b)
return Response({"add":add})

/api/urls.py

1
2
3
4
5
6
7
from django.urls import path, include
from . import views

urlpatterns = [
path('op',views.op,name='op'),
path('op2/<int:a>/<int:b>',views.op2,name='op2')
]

授權

由於有對於api進行授權設置,因此在需先提前為django註冊用戶

python3 manage.py createsuperuser

如若無進行登入則無法使用api,如下圖: