SlideShare une entreprise Scribd logo
1  sur  44
Télécharger pour lire hors ligne
Tastypie

第一次寫 Web API 就上手
by 信傑
Outline
● 為什麼要用 Web API ?
● Tastypie 能幫我們作什麼?
● 如何開始寫 Tastypie?
● 如何強化你的 Web API?
● 如何調校你的 Tastypie?
● Tastypie 還可以怎樣改?
為什麼要用 Web API ?
● 回顧一下 Request 週期
url
Request

view
model
Response
template
為什麼要用 Web API ? (cont'd)
● 那如果系統要在不同平台上使用呢?

?
為什麼要用 Web API ? (cont'd)

這個專案需要更
高級的 Package
為什麼要用 Web API ? (cont'd)
● 所以我們使用『Tastypie』來製作 Web API
Tastypie 能幫我們作什麼?
● 首先必須先介紹什麼是 RESTful?

註:http://zh.wikipedia.org/wiki/REST
Tastypie 能幫我們作什麼?(cont’d)
● Tastypie 就是幫你完成 django - model 到
Web api 中間的轉換
● 以 django.contrib.auth 的 Group, User,
Permission 作範例
Tastypie 能幫我們作什麼?(cont’d)
user_set

user_permissions

permissions
groups
group_set

user_set
如何開始寫 Tastypie?
1. pip install django django-tastypie mysqlpython mimeparse
2. django-admin.py startproject myApp
3. cd ./myApp
4. python manage.py startapp myApi
5. mkdir ./myApi/api && touch .
/myApi/api/__init__.py
6. vim ./myApi/api/resources.py
如何開始寫 Tastypie?(cont’d)
● vim ./myApi/api/resources.py
from tastypie.resources import ModelResource
from django.contrib.auth.models import Group, User

class UserModelResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
allowed_methods = ['get']
如何開始寫 Tastypie?(cont’d)
● vim ./myApp/myApi/urls.py
from django.conf.urls import patterns, include, url
from api.resources import UserModelResource
urlpatterns = patterns('',
(r'', include(UserModelResource().urls)),
)
如何開始寫 Tastypie?(cont’d)
● vim ./myApp/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myApp',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '',
}
}
…
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
...
'tastypie',
myApi,
)
如何開始寫 Tastypie?(cont’d)
● vim ./myApp/urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
…
(r'^api/', include('myApi.urls')),
)
如何開始寫 Tastypie?(cont’d)
1. python manage.py syncdb
2. python manage.py runserver
3. GET http://localhost:8000/api/user/ or http:
//localhost:8000/api/user/?format=json
如何開始寫 Tastypie?(cont’d)
如何開始寫 Tastypie?(cont’d)

什麼?
Web API 完成了?

是的,你的第一個
Web API 完成了
如何強化你的 Web API?
● 先多增加兩個 API: api/resources.py
from django.contrib.auth.models import Group, User, Permission
…
class GroupModelResource(ModelResource):
class Meta:
queryset = Group.objects.all()
resource_name = 'group'
allowed_methods = ['get']
class PermissionModelResource(ModelResource):
class Meta:
queryset = Permission.objects.all()
resource_name = 'permission'
allowed_methods = ['get']
如何強化你的 Web API?(cont’d)
● 再新增/修改 url:api/urls.py
from api.resources import UserModelResource,
GroupModelResource, PermissionModelResource
…
urlpatterns = patterns('',
(r'', include(UserModelResource().urls)),
(r'', include(GroupModelResource().urls)),
(r'', include(PermissionModelResource().urls)),
)
如何強化你的 Web API?(cont’d)
● 現在已經又多兩了 Web API 了http:
//localhost:8000/api/group/ & http://localhost:
8000/api/permission/
如何強化你的 Web API?(cont’d)
● 疑?總覺的哪裡怪怪的
● 多了很多不想被看到的欄位資料
● 表單之間的關聯都沒看到
● 繼續對 resources.py 作努力
如何強化你的 Web API?(cont’d)
from tastypie import fields
class UserModelResource(ModelResource):
groups = fields.ToManyField('api.resources.GroupModelResource', 'groups')
permissions = fields.ToManyField('api.resources.PermissionModelResource',
'user_permissions')
class Meta:
queryset = User.objects.all()
resource_name = 'user'
allowed_methods = ['get']
#detail_allowed_methods = ['get']
#fields = ['username', 'first_name', 'last_name', 'last_login']
excludes = ['id', 'is_active', 'date_joined', 'password', 'is_staff', 'is_superuser']
如何強化你的 Web API?(cont’d)
class GroupModelResource(ModelResource):
permissions = fields.ToManyField('api.resources.
PermissionModelResource', 'permissions')
#users = fields.ToManyField('api.resources.UserModelResource', 'user_set')
users = fields.ToManyField(UserModelResource, 'user_set')
class Meta:
queryset = Group.objects.all()
resource_name = 'group'
allowed_methods = ['get']
#detail_allowed_methods = ['get']
如何強化你的 Web API?(cont’d)
如何強化你的 Web API?(cont’d)
● 現在已經可以隱藏部分欄位,以及顯示相關聯
的資料了
● 那 API 除了查詢,新增、修改與刪除功能勒?
● 繼續修改 resources.py
如何強化你的 Web API?(cont’d)
…
from tastypie.authorization import Authorization
class UserModelResource(ModelResource):
groups = fields.ToManyField('api.resources.GroupModelResource', 'groups', null=True)
permissions = fields.ToManyField('api.resources.PermissionModelResource',
'user_permissions', null=True)
class Meta:
...
#allowed_methods = ['get']
list_allowed_methods = ['get', 'post']
detail_allowed_methods = ['get', 'put']
...
always_return_data = True
#authentication = Authentication() # BasicAuthentication, ApiKeyAuthentication
authorization = Authorization() # ReadOnlyAuthorization, DjangoAuthorization
如何強化你的 Web API?(cont’d)
class GroupModelResource(ModelResource):
permissions = fields.ToManyField('api.resources.PermissionModelResource',
'permissions', null=True)
users = fields.ToManyField('api.resources.UserModelResource', 'user_set', null=True)
class Meta:
...
list_allowed_methods = ['get', 'post']
detail_allowed_methods = ['get', 'put', 'delete']
always_return_data = True
authorization = Authorization()
如何強化你的 Web API?(cont’d)
● 現在可以完整的測試 CRUD 了
如何調校你的 Tastypie?
● 如果對 Tastypie 預設的樣板不滿意的話,那
就覆寫(修改)它吧
如何調校你的 Tastypie?(cont’d)
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
from tastypie.utils.urls import trailing_slash
from django.conf.urls import url
...
class UserModelResource(ModelResource):
…
class Meta:
...
detail_uri_name = 'username'
filtering = {
'groups': ALL_WITH_RELATIONS,
}
如何調校你的 Tastypie?(cont’d)
class GroupModelResource(ModelResource):
...
class Meta:
…
detail_uri_name = 'name'
filtering = {
'name': 'exact',
}
如何調校你的 Tastypie?(cont’d)
● 試試看加個參數:
http://localhost:8000/api/user/
?groups__name=a

● 這樣查詢好像有點 low
● 那改 URL 如何?
如何調校你的 Tastypie?(cont’d)
class UserModelResource(ModelResource):
def base_urls(self):
return [
url(r"^(?P<resource_name>%s)%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('dispatch_list'), name="api_dispatch_list"),
url(r"^(?P<resource_name>%s)/(?P<%s>w[w/-]*)%s$" %
(self._meta.resource_name, self._meta.detail_uri_name, trailing_slash()),
self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
url(r"^group/(?P<groups__name>%s)/(?P<resource_name>%s)%s$" %
(r'[w]{,80}', self._meta.resource_name, trailing_slash()),
self.wrap_view('dispatch_list'), name="api_dispatch_list"),
url(r"^group/(?P<groups__name>%s)/(?P<resource_name>%s)/(?P<%s>w[w/-]*)%s$" %
(r'[w]{,80}', self._meta.resource_name, self._meta.detail_uri_name, trailing_slash()),
self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
如何調校你的 Tastypie?(cont’d)
● 似乎還差一點點
○ GET http://localhost:8000/api/group/a/user/ :
1.

"meta": {

2.

"limit": 10,

3.

"next": "/api/user/?limit=10&offset=10",

4.

"offset": 0,

5.

"previous": null,

6.

"total_count": 13

7.

}

● 需要對 get_list 作點修正,同樣
vim resources.py
如何調校你的 Tastypie?(cont’d)
class BaseModelResource(ModelResource):
pass
…
class UserModelResource(BaseModelResource):
…
class GroupModelResource(BaseModelResource):
…
class PermissionModelResource(BaseModelResource):
...
如何調校你的 Tastypie?(cont’d)
class BaseModelResource(ModelResource):
def get_list(self, request, **kwargs):
base_bundle = self.build_bundle(request=request)
objects = self.obj_get_list(bundle=base_bundle, **self.remove_api_resource_names(kwargs))
sorted_objects = self.apply_sorting(objects, options=request.GET)
paginator = self._meta.paginator_class(request.GET, sorted_objects,
原程式修改這邊
resource_uri=self.get_resource_list_uri(**kwargs),
limit=self._meta.limit, max_limit=self._meta.max_limit,
collection_name=self._meta.collection_name)
to_be_serialized = paginator.page()
bundles = []
for obj in to_be_serialized[self._meta.collection_name]:
bundle = self.build_bundle(obj=obj, request=request)
bundles.append(self.full_dehydrate(bundle, for_list=True))
to_be_serialized[self._meta.collection_name] = bundles
to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized)
return self.create_response(request, to_be_serialized)
如何調校你的 Tastypie?(cont’d)
class BaseModelResource(ModelResource):
…
def get_resource_list_uri(self, **kwargs):
if self._meta.api_name is not None:
kwargs['api_name'] = self._meta.api_name
try:
return self._build_reverse_url("api_dispatch_list", kwargs=kwargs)
except Exception:
return None
如何調校你的 Tastypie?(cont’d)
● 這樣就修正完畢了
○ GET http://localhost:8000/api/group/a/user/ :
1.

"meta": {

2.

"limit": 10,

3.

"next": "/api/group/a/user/?limit=10&offset=10",

4.

"offset": 0,

5.

"previous": null,

6.

"total_count": 13

7.

}
Tastypie 還可以怎樣改?
● 再介紹一個核心資料『bundle』
● 『bundle』貫串了 Tastypie 的資料處理過程,
其中包含了
○ data :
資料
○ obj :
model 物件
○ request : 就 request
Tastypie 還可以怎樣改?(cont’d)

hydrate
data

obj

dehydrate
bundle
Tastypie 還可以怎樣改?(cont’d)
bundle

bundle

full_hydrate

full_dehydrate

hydrate

field.dehydrate

hydrate_%s

dehydrate_%s

field.hydrate

dehydrate

hydrate
bundle

dehydrate
bundle
Tastypie 還可以怎樣改?(cont’d)
Request

URL
dispatch
(list/detail)

[get/post/put/delete]_[list/detail]

hydrate

Response

dehydrate
Tastypie 還可以怎樣改?(cont’d)
● 你想要的功能,找出最適合的位置(function),
覆寫它吧!
註:對不起,我只會這麼多而已。

Contenu connexe

Similaire à Tastypie

探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan
探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan
探索 API 開發的挑戰與解決之道 | .NET Conf 2023 TaiwanAlan Tsai
 
美团点评技术沙龙011 - 移动app兼容性测试工具Spider
美团点评技术沙龙011 - 移动app兼容性测试工具Spider 美团点评技术沙龙011 - 移动app兼容性测试工具Spider
美团点评技术沙龙011 - 移动app兼容性测试工具Spider 美团点评技术团队
 
10 Things to Make API Users Like You
10 Things to Make API Users Like You10 Things to Make API Users Like You
10 Things to Make API Users Like YouDavid Yun
 
利用 ASP.NET MVC 提升您的 Web 應用程式
利用 ASP.NET MVC 提升您的 Web 應用程式利用 ASP.NET MVC 提升您的 Web 應用程式
利用 ASP.NET MVC 提升您的 Web 應用程式Chui-Wen Chiu
 
Angular js twmvc#17
Angular js twmvc#17Angular js twmvc#17
Angular js twmvc#17twMVC
 
Vlog02 [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
Vlog02  [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...Vlog02  [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
Vlog02 [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...SernHao TV
 
富文本编辑器在互联网上的应用
富文本编辑器在互联网上的应用富文本编辑器在互联网上的应用
富文本编辑器在互联网上的应用luolonghao
 
Net 6 的 blazor 開發新視界
Net 6 的 blazor 開發新視界Net 6 的 blazor 開發新視界
Net 6 的 blazor 開發新視界Gelis Wu
 
KISSY Editor Design 2
KISSY Editor Design 2KISSY Editor Design 2
KISSY Editor Design 2yiming he
 
Rest Ruby On Rails
Rest Ruby On RailsRest Ruby On Rails
Rest Ruby On Railsshaokun
 
Non-MVC Web Framework
Non-MVC Web FrameworkNon-MVC Web Framework
Non-MVC Web FrameworkFred Chien
 
Res tful api design tw-2.0
Res tful api design tw-2.0Res tful api design tw-2.0
Res tful api design tw-2.0昀陞 李
 
Ibmzf2
Ibmzf2Ibmzf2
Ibmzf2daoopp
 
Using google appengine_1027
Using google appengine_1027Using google appengine_1027
Using google appengine_1027Wei Sun
 
twMVC#01 | ASP.NET MVC 的第一次親密接觸
twMVC#01 | ASP.NET MVC 的第一次親密接觸twMVC#01 | ASP.NET MVC 的第一次親密接觸
twMVC#01 | ASP.NET MVC 的第一次親密接觸twMVC
 
twMVC#08 | Web API
twMVC#08 | Web APItwMVC#08 | Web API
twMVC#08 | Web APItwMVC
 
ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8twMVC
 
价值中国网站开发、管理经验探讨、分享、交流
价值中国网站开发、管理经验探讨、分享、交流价值中国网站开发、管理经验探讨、分享、交流
价值中国网站开发、管理经验探讨、分享、交流hizhubo
 

Similaire à Tastypie (20)

探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan
探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan
探索 API 開發的挑戰與解決之道 | .NET Conf 2023 Taiwan
 
美团点评技术沙龙011 - 移动app兼容性测试工具Spider
美团点评技术沙龙011 - 移动app兼容性测试工具Spider 美团点评技术沙龙011 - 移动app兼容性测试工具Spider
美团点评技术沙龙011 - 移动app兼容性测试工具Spider
 
10 Things to Make API Users Like You
10 Things to Make API Users Like You10 Things to Make API Users Like You
10 Things to Make API Users Like You
 
利用 ASP.NET MVC 提升您的 Web 應用程式
利用 ASP.NET MVC 提升您的 Web 應用程式利用 ASP.NET MVC 提升您的 Web 應用程式
利用 ASP.NET MVC 提升您的 Web 應用程式
 
淺談後端概念
淺談後端概念淺談後端概念
淺談後端概念
 
Angular js twmvc#17
Angular js twmvc#17Angular js twmvc#17
Angular js twmvc#17
 
Vlog02 [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
Vlog02  [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...Vlog02  [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
Vlog02 [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
 
富文本编辑器在互联网上的应用
富文本编辑器在互联网上的应用富文本编辑器在互联网上的应用
富文本编辑器在互联网上的应用
 
Net 6 的 blazor 開發新視界
Net 6 的 blazor 開發新視界Net 6 的 blazor 開發新視界
Net 6 的 blazor 開發新視界
 
KISSY Editor Design 2
KISSY Editor Design 2KISSY Editor Design 2
KISSY Editor Design 2
 
Rest Ruby On Rails
Rest Ruby On RailsRest Ruby On Rails
Rest Ruby On Rails
 
Non-MVC Web Framework
Non-MVC Web FrameworkNon-MVC Web Framework
Non-MVC Web Framework
 
Res tful api design tw-2.0
Res tful api design tw-2.0Res tful api design tw-2.0
Res tful api design tw-2.0
 
Ibmzf2
Ibmzf2Ibmzf2
Ibmzf2
 
Using google appengine_1027
Using google appengine_1027Using google appengine_1027
Using google appengine_1027
 
twMVC#01 | ASP.NET MVC 的第一次親密接觸
twMVC#01 | ASP.NET MVC 的第一次親密接觸twMVC#01 | ASP.NET MVC 的第一次親密接觸
twMVC#01 | ASP.NET MVC 的第一次親密接觸
 
twMVC#08 | Web API
twMVC#08 | Web APItwMVC#08 | Web API
twMVC#08 | Web API
 
ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8
 
价值中国网站开发、管理经验探讨、分享、交流
价值中国网站开发、管理经验探讨、分享、交流价值中国网站开发、管理经验探讨、分享、交流
价值中国网站开发、管理经验探讨、分享、交流
 
Asp.Net Mvc 1.0
Asp.Net Mvc 1.0Asp.Net Mvc 1.0
Asp.Net Mvc 1.0
 

Tastypie