django restful webservice返回json数据

做这个demo的前提是你已经配好了python ,django ,djangorestframwork(在我的上一篇博客中有介绍,大家也可以google),mysql-python等。

djangorestframwork的官网点击打开链接http://django-rest-framework.org/ 

工程目录:

django restful webservice返回json数据_第1张图片

下面开始:

models.py 主要负责数据库对象的映射

'''
Created on 2013-9-19

@author: lele
'''
from django.db import models
 

 
# Create your models here.
class Student(models.Model):
    
    id=models.IntegerField(primary_key=True)
    Pname= models.CharField(max_length=500)
    age=models.IntegerField()

    class Meta:
        ordering = ('id',)

序列化:

serializers.py

# -*- coding: UTF-8 -*-
'''
Created on 2013-9-19

@author: lele
'''
from django.forms import widgets
from rest_framework import serializers
from models import Student,Content
class StudentSerializer(serializers.ModelSerializer):
    mystudentsdetail = serializers.HyperlinkedRelatedField(many=True, view_name='student-detail')
    class Meta:
        model = Student
        fields = ('id', 'Pname','age')
    id = serializers.IntegerField()  # Note: `Field` is an untyped read-only field.
    Pname= serializers.CharField(max_length=100)
    age=serializers.IntegerField()
        
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance.
        """
        if instance:
            # Update existing instance
            instance.Panme = attrs['Pname']
            instance.id = attrs['id']
            instance.age = attrs['age']
            
            return instance

        # Create new instance
        return Student(**attrs)
    
    

views.py:

'''
Created on 2013-9-19

@author: lele
'''

from django.http import HttpResponse
from models import Student,Content
from serializers import StudentSerializer
from rest_framework import viewsets

    
    
class StudentViewSet(viewsets.ModelViewSet):
    
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
修改配置文件:

在settings.py中修改databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'test',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '3306',                      # Set to empty string for default.
    }
}


还是在settings.py中添加:

REST_FRAMEWORK = {
    # Use hyperlinked styles by default.
    # Only used if the `serializer_class` attribute is not set on a view.
    'DEFAULT_MODEL_SERIALIZER_CLASS':
        'rest_framework.serializers.HyperlinkedModelSerializer',
   
    'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.AllowAny',
    ),

    'PAGINATE_BY': 3,  #every  number in page 
    'PAGINATE_BY_PARAM': 'page_size',
    'MAX_PAGINATE_BY': 100  
}

设置访问连接:

在urls.py设置

from django.conf.urls import patterns, include, url
from rest_framework import viewsets, routers
from views import StudentViewSet



router = routers.DefaultRouter()
router.register(r'mystudents',StudentViewSet)



urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)



就剩最后一步了在mysql数据库中添加 数据

注意:数据库的名字与setting.py中的一致,table的名字格式是:项目名_对象名  

例如我的项目名为:djangodemo2 models.py中的model对象名为student  ,所以我的表名为:djangodemo2_student

有三个字段 id,Pname ,age   要与serializers.py中的fields字段相同

本例中的字段如下:

django restful webservice返回json数据_第2张图片

运行测试:

在浏览器中输入:http://localhost:8000 即可看到如下页面:

django restful webservice返回json数据_第3张图片

点击链接进入具体信息页面:

django restful webservice返回json数据_第4张图片



转载请注明:

新浪微博:http://weibo.com/u/3202802157















你可能感兴趣的:(django restful webservice返回json数据)