现在的位置: 首页 > 综合 > 正文

Django RESTfull接口之Tastypie简介(一)

2013年12月09日 ⁄ 综合 ⁄ 共 2302字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.