参考
Django rest framework官网http://www.django-rest-framework.org/
文章可能有疏漏,具体请参考代码
源码地址 github:https://github.com/luojie1024/Django_Rest_Framework_Demo
本文需要有一定的Python和Django基础,需要预先安装Ubuntu及其相关配置。
创建虚拟环境
//创建虚拟环境文件夹
mkdir tutorial
cd tutorial
//创建虚拟环境(方便后期部署)
virtualenv env
source env/bin/activate # On Windows use `env\Scripts\activate`
//安装Django和restframework框架
virtualenv
pip install django
pip install djangorestframework
安装mysql数据库
//没有安装的话迁移会出错
pip install mysqlclient
sudo apt-get install python3-dev libmysqlclient-dev
进入虚拟环境
joahluo@ubuntu:~/tutorial/env/local/bin$ source activate
创建应用(创建项目文件夹,进入文件夹)
本例在projecet07文件夹下创建项目
//创建项目
django-admin.py startproject turorial
cd tutorial
//代码运行之后创建APP snippets
django-admin.py startapp snippets
创建一个空的mysql数据库
mysql> create database restframework charset=utf8;
使用Pycharm打开自己的项目
在turorial/setting.py下加入APP,并且设置自己的数据库
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'snippets',
'rest_framework',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'restframework',
'PORT': '3306',
'HOST': 'localhost',
'USER': 'luojie',
'PASSWORD': '123456',
}
}
在turorial/urls.py中配置url
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from snippets import api
router = routers.DefaultRouter()
router.register(r'users', api.UserViewSet)
router.register(r'blogs', api.BlogViewSet)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(router.urls)),
]
在snippet/models.py下配置相应的models
本例以blog做演示
from django.db import models
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length = 50 )
content = models.TextField()
在snippets 下创建api.py文件
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from snippets import models
from rest_framework import response
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url','username','email','is_staff')
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class BlogSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Blog
depth = 1
fields = ('url','title','content',)
class BlogViewSet(viewsets.ModelViewSet):
queryset = models.Blog.objects.all()
serializer_class = BlogSerializer
生成迁移文件,并且完成迁移
python manage.py makemigrations
python manage.py migrate
运行服务器
python manage.py runserver
进入到项目目录,运行服务