- 数据库中有user表如下:
- 新建一个Django项目:
django-admin.py startproject myDjango
myDjango/
├── manage.py # 管理文件
└── myDjango # 项目目录
├── __ init __.py
├── settings.py # 配置文件
├── urls.py # 路由 --> URL和函数的对应关系
└── wsgi.py # runserver命令就使用wsgiref模块做简单的web server
INSTALLED_APPS = [
...
'rest_framework'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bigdatatest',
'USER': 'root',
'HOST': '127.0.0.1',
'PASSWORD': '1009',
'PORT': 3306,
'OPTIONS': {'charset': 'utf8mb4'},
}
}
import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()
python manage.py startapp users
users/
├── migrations # 用于在之后定义引用迁移功能
├── __ init __.py
├── __ init __.py
├── admin.py # 管理站点模型的声明文件,默认为空
├── apps.py # 应用信息定义文件。在其中生成了类Appconfig,类用于定义应用名等Meta数据
├── models.py # 添加模型层数据类的文件
├── tests.py # 测试代码文件
└── views.py # 定义URL响应函数
INSTALLED_APPS = [
...
'users'
]
python manage.py inspectdb
- 将我们表的model拷贝到users下的models.py里
from django.db import models
class User(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user'
- 创建一个序列化Serializer类,使之可以转化为,某种表现形式如json
- 在users目录下,创建文件serializers.py
from rest_framework import serializers
from users.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
from __future__ import unicode_literals
from rest_framework.decorators import api_view
from rest_framework.response import Response
from user.models import User
from user.serializers import UserSerializer
@api_view(['GET'])
def getlist(request):
if request.method == 'GET':
users = User.objects.values('id', 'name', 'age').distinct()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
@api_view(['GET'])
def getlistpic(request):
id = request.GET['id']
if id is not None:
users = User.objects.filter(id=id)
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
else:
return Response(str('请传id'))
@api_view(['POST'])
def addUser(request):
ser = UserSerializer(data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
return Response(ser.errors)
@api_view(['GET'])
def deleteUser(request):
id = request.GET['id']
if id is not None:
if User.objects.filter(id=id):
User.objects.get(id=id).delete()
return Response(str('success'))
else:
return Response(str('没有此id'))
else:
return Response(str('请传id'))
@api_view(['POST'])
def updateUser(request):
if User.objects.filter(id=request.data['id']):
user = User.objects.get(id=request.data['id'])
ser = UserSerializer(instance=user, data=request.data)
if ser.is_valid():
ser.save()
return Response(str('success'))
return Response(ser.errors)
return Response(str('没有此id'))
from django.conf.urls import url
from users import views as users_views
urlpatterns = [
url(r'^getlistpic', users_views.getlistpic, name='home'),
url(r'^getlist', users_views.getlist, name='home'),
url(r'^addUser', users_views.addUser, name='home'),
url(r'^deleteUser', users_views.deleteUser, name='home'),
url(r'^updateUser', users_views.updateUser, name='home')
]
python manage.py runserver 127.0.0.1:8000
访问结果:
- 源码地址: myDjango
- 参考:
创建第一个Django项目
Python用Django写restful api接口