首页 > 代码库 > Tastypie 学习笔记
Tastypie 学习笔记
Tastypie是什么? 运行于Python环境中的 Django web服务器下的 Restful 风格API (python 类库)
1、安装下面环境或者依赖包到python库(安装过程类似django 在命令行cd 到下载的文件目录中,输入python setup.py install就可以安装了)
- Python 2.6+ or Python 3.3+
- Django 1.5+
- python-mimeparse 0.1.4+ (http://pypi.python.org/pypi/python-mimeparse) 须下载安装
- dateutil (http://labix.org/python-dateutil) 高级点的python自带,不行的话就重新下载安装
- OPTIONAL - lxml (http://lxml.de/) and defusedxml(https://pypi.python.org/pypi/defusedxml) if using the XML serializer 可选 用于处理XML序列化
- OPTIONAL - pyyaml (http://pyyaml.org/) if using the YAML serializer 可选 用于处理YAML序列化
2、安照之前django教程建立了一个名为blog的app
D:\project\tastypie\mysite\blog\models.py 数据模型文件如下:
from tastypie.utils.timezone import nowfrom django.contrib.auth.models import Userfrom django.db import modelsfrom django.utils.text import slugify# Create your models here.class Entry(models.Model): user = models.ForeignKey(User) pub_date = models.DateTimeField(default=now) title = models.CharField(max_length=200) slug = models.SlugField()#当你看见当下网页url后面出现a-b-c-d-f类似的字符串,就是被slugify了 body = models.TextField() def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)[:50] return super(Entry,self).save(*args, **kwargs)
3、在blog项目中配置tastypie
D:\project\tastypie\mysite\mysite\settings.py配置文件加入tastypie[非必要的]
# Application definitionINSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘blog‘, ‘tastypie‘,)
4、创建API资源
D:\project\tastypie\mysite\blog\api\resources.py(手动创建的目录及文件)
from django.contrib.auth.models import Userfrom tastypie.authorization import Authorizationfrom tastypie import fieldsfrom tastypie.resources import ModelResource ,ALL ,ALL_WITH_RELATIONSfrom blog.models import Entryclass UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = ‘user‘ excludes = [‘email‘,‘password‘,‘is_active‘,‘is_staff‘,‘is_superuser‘] #fields=[‘username‘,‘first_name‘,‘last_name‘,‘last_login‘] #allowed_methods = [‘get‘] authorization = Authorization() filtering={ ‘username‘:ALL, }class EntryResource(ModelResource): user = fields.ForeignKey(UserResource,‘user‘) class Meta: queryset = Entry.objects.all() resource_name = ‘entry‘ authorization = Authorization() filtering = { ‘user‘ : ALL_WITH_RELATIONS, ‘pub_date‘:[‘exact‘,‘lt‘,‘lte‘,‘gte‘,‘gt‘], }
5、url配置
主url配置,D:\project\tastypie\mysite\mysite\urls.py
from django.conf.urls import patterns, include, urlfrom django.contrib import adminfrom tastypie.api import Apifrom blog.api.resources import EntryResource,UserResourcev1_api = Api(api_name=‘v1‘)v1_api.register(UserResource())v1_api.register(EntryResource())urlpatterns = patterns(‘‘, # Examples: (r‘^blog/‘, include(‘blog.urls‘,namespace="blog")), (r‘^api/‘, include(v1_api.urls)), (r‘^admin/‘, include(admin.site.urls)),)
子url配置(主要是用来玩ajax调用等会使用),D:\project\tastypie\mysite\blog\urls.py
from django.conf.urls import patterns,urlfrom blog import viewsurlpatterns=patterns(‘‘, url(r‘^$‘,views.IndexView.as_view(),name=‘index‘),)
6、下载个cURL工具加入到环境变量中使用,用于测试链接
7、开始玩API了
1)用命令行输入
curl http://localhost:8000/api/v1/
得到如下json内容
{ "entry": { "list_endpoint": "/api/v1/entry/", "schema": "/api/v1/entry/schema/" }, "user": { "list_endpoint": "/api/v1/user/", "schema": "/api/v1/user/schema/" }}
2)输入
curl http://localhost:8000/api/v1/entry/
列出所有的json数据
3)下面我们在同个域下面用静态网页加上jquery的ajax来玩
3.1)先加个template文件:D:\project\tastypie\mysite\blog\templates\blog\index.html 记得在setting文件中加路径引用TEMPLATE_DIRS = [os.path.join(BASE_DIR,‘templates‘)]
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head> <meta charset="utf-8" /> <title></title></head><body> <script type="text/javascript" src=http://www.mamicode.com/"/static/js/jquery-1.8.3.min.js"></script><script type="text/javascript" src=http://www.mamicode.com/"/static/js/json2.js"></script><script> $(document).ready(function () { $.ajax({ url: ‘http://localhost:8000/api/v1/entry/1/‘, type: ‘GET‘, dataType: ‘json‘, success: function (data) { console.log(data); } }); });</script> </body></html>
3.2)绑定个view:D:\project\tastypie\mysite\blog\views.py
from django.shortcuts import renderfrom django.views import generic# Create your views here.class IndexView(generic.ListView): template_name=‘blog/index.html‘ context_object_name=‘‘ def get_queryset(self): """Return the last five published question""" return ‘‘
3.3)前面提到的配置子url:D:\project\tastypie\mysite\blog\urls.py
from django.conf.urls import patterns,urlfrom blog import viewsurlpatterns=patterns(‘‘, url(r‘^$‘,views.IndexView.as_view(),name=‘index‘),)
3.4)好,用Chrome 测试ajax调用,GET方法,输入url http://localhost:8000/blog/
按F12看log结果
3.5)现在看测试,POST方法,注意用了json2类库,js代码改为
var data =http://www.mamicode.com/ JSON.stringify({ "title": "Another Post 3", "body": "This will prbbly be my 1st post.", "pub_date": "2015-01-29T11:07:30", "slug": "another-post", "user": "/api/v1/user/1/" }); $.ajax({ url: ‘http://localhost:8000/api/v1/entry/‘, type: ‘POST‘, contentType: ‘application/json‘, data: data, dataType: ‘json‘, processData: false, success: function (data) { console.log(data); }, error: function (data) { console.log(data); } });
用浏览器看结果:输入http://localhost:8000/api/v1/entry/?format=json
{"body": "This will prbbly be my 1st post.", "id": 7, "pub_date": "2015-01-29T11:07:30", "resource_uri": "/api/v1/entry/7/", "slug": "another-post", "title": "Another Post 3", "user": "/api/v1/user/1/"} 记录已经POST成功了!
3.6)
PUT 、PATCH 、DELETE,逐个试过可以成功运行!
Tastypie 学习笔记