django-rest 之 api (一)

原创 赤水  2016年1月4日 06:57 阅读 178 次
环境要求:
	Python (2.7, 3.2, 3.3, 3.4, 3.5)
	Django (1.7+, 1.8, 1.9)
在wgl apps 中创建models
# cat wgl/models.py
from django.db import models
class lssin(models.Model):
    username = models.CharField(max_length=20,null=True)
    password = models.CharField(max_length=20,default='')
    email = models.CharField(max_length=20,default='')

    def __unicode__(self):
        return self.username
创建测试数据
In [1]: from wgl.models import lssin

In [2]: lssin.objects.create(username='test1')
Out[2]: <lssin: test1>

In [3]: lssin.objects.create(username='test2')
Out[3]: <lssin: test2>
编写 views.py
# cat wgl/views.py
#coding=utf8
from django.shortcuts import render
from django.http import HttpResponse
from wgl.models import lssin
from wgl.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer

class JSONResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


def Lssin(request):
    if request.method == 'GET':
        User = request.GET.get('user',None)
        if User:
            try:
                snippets = lssin.objects.get(username=User) #snippets 必须是对象而不是一个列表
            except Exception,e:
                return HttpResponse(status=404)
            serializer = SnippetSerializer(snippets)
            return JSONResponse(serializer.data)
    return HttpResponse(status=404)
编写serializers.py
# cat wgl/serializers.py
from rest_framework import serializers
from wgl.models import lssin

class SnippetSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    email = serializers.CharField()
配置urls.py
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^test$', 'wgl.views.Lssin'),
]

测试
# http http://127.0.0.1:8080/test?user=test1
HTTP/1.0 200 OK
Content-Type: application/json
Date: Mon, 04 Jan 2016 06:50:28 GMT
Server: WSGIServer/0.1 Python/2.7.6
X-Frame-Options: SAMEORIGIN

{
    "email": "", 
    "password": "", 
    "username": "test1"
}

# http http://127.0.0.1:8080/test?user=test11
HTTP/1.0 404 NOT FOUND
Content-Type: text/html; charset=utf-8
Date: Mon, 04 Jan 2016 06:50:31 GMT
Server: WSGIServer/0.1 Python/2.7.6
X-Frame-Options: SAMEORIGIN

构建的api,还是比较简单不使用django-rest,也可以构建api,继续学习!

资料:http://www.django-rest-framework.org/



 

本文地址: https://blog.lssin.com/readblog/46.html
版权声明:本文为原创文章,版权归  赤水 所有,欢迎分享本文,转载请保留出处!

发表评论


表情