Tastypie 学习笔记

Tastypie是什么? 运行于Python环境中的 Django web服务器下的 Restful 风格API接口  (python 类库)

快速浏览更多在线 Demo

想查看源代码,可以自行F12,或在github中直接查看源码,或者欢迎直接留言。

1、安装下面环境或者依赖包到python库(安装过程类似django 在命令行cd 到下载的文件目录中,输入python setup.py install就可以安装了

2、安照之前django教程建立了一个名为blog的app

D:\project\tastypie\mysite\blog\models.py 数据模型文件如下:

from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from 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 definition

INSTALLED_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 User
from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.resources import ModelResource ,ALL ,ALL_WITH_RELATIONS
from blog.models import Entry class 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, url
from django.contrib import admin
from tastypie.api import Api
from blog.api.resources import EntryResource,UserResource v1_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,url
from blog import views urlpatterns=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数据
curl http://localhost:8000/api/v1/entry/schema/ 列出所有的操作权限,如get post put delete patch

3)下面我们在同个域下面用静态网页加上jquery的ajax来玩 Tastypie与jQuery互动

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="/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/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 render
from 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,url
from blog import views urlpatterns=patterns('',
url(r'^$',views.IndexView.as_view(),name='index'),
)

3.4)好,用Chrome 测试ajax调用,GET方法,输入url http://localhost:8000/blog/   

按F12看log结果

Object {body: "test1", id: 1, pub_date: "2015-01-28T12:14:49", resource_uri: "/api/v1/entry/1/", slug: "test1"…}

3.5)现在看测试,POST方法,注意用了json2类库,js代码改为

        var data = 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,逐个试过可以成功运行!

上一篇:IntelliJ IDEA 删除自定义的 Maven 框架依赖


下一篇:Spark RDD API扩展开发