十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
django-admin startproject drfdemo1
python manage.py startapp app
pip install djangorestframework
INSTALLED_APPS = [
# 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
'app',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
上述配置保留了Auth认证系统和Session功能,当django运行时只会加载Auth认证系统和Session功能,这样能减少django占用服务器的系统资源,除此之外还要注释掉配置属性TEMPLATES和STATIC_URL,因为API接口无需使用模板功能和静态资源
庄河网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。成都创新互联于2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联。
在drfdemo1的urls.py中编写以下内容:
from django.urls import path, include
urlpatterns = [
path('api/',include('app.urls')),
]
在app里创建urls.py,并写入如下内容:
from django.urls import path
from .views import *
urlpatterns = [
path('students/',students.as_view())
]
from django.db import models
class studentsInfo(models.Model):
name = models.CharField(max_length=12, verbose_name='姓名')
sex = models.CharField(max_length=1, verbose_name='性别')
age = models.IntegerField(verbose_name='年龄')
classroom = models.CharField(max_length=10, verbose_name='教室')
info = models.CharField(max_length=100, verbose_name='个人简介')
from rest_framework import serializers
from .models import *
class studentSerializer(serializers.ModelSerializer):
class Meta:
model = studentsInfo
fields = "__all__"
from .models import *
from django.http import JsonResponse
from .serializer import studentSerializer
from rest_framework.views import APIView
class students(APIView):
def get(self, request):
data = studentsInfo.objects.all()
serializer = studentSerializer(instance=data,many=True)
return JsonResponse(serializer.data,safe=False)
python manage.py makemigrations
python manage.py migrate
迁移之后插入测试数据
python manage.py runserver 8000
访问127.0.0.1/api/students,结果如下:
[
{
"id": 1,
"name": "小明",
"sex": "男",
"age": 22,
"classroom": "301",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 2,
"name": "小红",
"sex": "女",
"age": 18,
"classroom": "301",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 3,
"name": "张三",
"sex": "男",
"age": 25,
"classroom": "307",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 4,
"name": "李四",
"sex": "男",
"age": 24,
"classroom": "308",
"info": "这个人很懒,什么也没有留下"
}
]