Django RESTfull接口之Tastypie簡介(一)

Tastypie簡介(一)


                                                            ——版本:0.9.11

                              

1 Tastypie簡介

    1.1   什麼是tastypie?

        TastypieDjango框架的一個webservice接口。它提供了一個方便、強大而且高定製化的REST風格接口。

        Tastypie非常容易顯示您的模型,但也能完全讓你控制你所期望得到的信息。只要你需要,能讓你遠離抽象的數據庫。Tastypie也能讓你非常容易的集成非ORM的數據源。

       Tastypie is BSD licensed & plays nicely with third-party apps without needing to modify their sources.

    1.2   特點:

  •     支持GET/POST/PUT/DELETE/PATCH方式調用
  •  合理的預設值
  • 設計起來方便擴展
  • 支持多種序列化的格式(JSON/XML/YMAL/bplist
  • HATEOAS by default
  •  方便測試、文檔完整

    1.3  怎樣開始

        1)  PIP安裝: pip  install django-tasypie

        2)  添加到APP: INSTALLED_APPS += ['tastypie’]

        3)  同步數據庫:manage.py  syncdb

        4)  創建你自己的資源

        5) 配置到urlconf

 

2 快速開始

    2.1  添加tastypieINSTALLED_APPS

    2.2  創建一個含有空__init__.pyapi目錄在你的APP

    2.3  創建一個<my_app>/api/resources.py文件,並將下面一段代碼放置其中

  

from tastypie.resources import ModelResource

from my_app.models import MyModel

 

class MyModelResource(ModelResource):

    class Meta:

        queryset = MyModel.objects.all()

        allowed_methods = ['get']


 

   2.4   在的根URLconf,添加如下代碼(在admin代碼附近):

from tastypie.api import Api

from my_app.api.resources import MyModelResource

 

v1_api = Api(api_name='v1')

v1_api.register(MyModelResource())

 

urlpatterns = patterns('',

  # ...more URLconf bits here...

  # Then add:

  (r'^api/', include(v1_api.urls)),

)


 

    2.5  在瀏覽器中訪問:http://localhost:8000/api/v1/?format=json

3相關包依賴

    Tastypie需要如下一些模塊。通過PIP就可以很輕鬆的安裝。

    3.1  必須安裝包

        1)   Python2.6+

        2)  Django1.3+

        3)  Mimeparse0.1.3+ (http://code.google.com/p/mimeparse/)【備註:老的版本也了可以工作,但是對JSON/JSONP的支持不夠友好】

        4)   Dateutil(http://labix.org/python-dateutil ) >= 1.5, < 2.0

    3.2 可選包

        1)  Python_digest (https://bitbucket.org/akoha/python-digest/)

        2)  Lxml(http://lxml.de/ ) 用於xml解析

        3)  Pymaml (http://pyyaml.org/ ) 用於YAML解析

        4)  Biplist (http://explorapp.com/biplist/ ) 用於binary plist解析

    3.3  Tastypie特點

        1)  RESTful風格的APIHTTP支持

        2)  支持深層次的關係

        3)  在輸入結果時不需要自己實現序列化操作

        4) 神奇的API框架,非常靈活的解決問題

        5) XML的序列化跟JSON一樣方便

    3.4  運行與測試

        1)   最方便的方法獲得Tastypie的測試如下:

$ git clone https://github.com/toastdriven/django-tastypie.git

$ cd django-tastypie

$ virtualenv env

$ . env/bin/activate

$ ./env/bin/pip install -U -r requirements.txt


 

        2) 運行測試舉例如下:

  

# From the same directory as above:

$ ./env/bin/pip install -U -r tests/requirements.txt

$ cd tests

$ ./run_all_test.sh

 

 

https://django-tastypie.readthedocs.org/en/latest/toc.html
發佈了47 篇原創文章 · 獲贊 124 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章