Django REST framework 安装及简单示例

Django python的一个后端服务器框架,用来写web API接口简单且方便。

Djangorestframework 是构建web api的一个强大而灵活的工具包。

 

Django 官网文档:https://docs.djangoproject.com/en/5.0/ref/settings/

Djangorestframework 官网文档:https://docs.djangoproject.com/en/5.0/ref/settings/

Django安装:

pip3 install django

 默认安装最新版本

安装djangorestframework及相关组件:

pip3 install djangorestframework

pip3 install markdown

 pip3 install django-filter

 

创建django项目:

语法格式:django-admin startproject [项目名称]

django-admin startproject myweb

在当前工作目录生成一个myweb项目文件

进入myweb项目中,创建相关应用:

语法格式:python manage.py startapp [应用名称]

python3 manage.py startapp users

 修改项目配置文件setting.py文件将新建的项目加上,便于启用django是自动加载相关的应用。

 同时把restframework也添加到应用中。

settings.py中还需要添加REST_FRAMEWORK的配置信息。新建一个REST_FRAMEWORK如下:

REST_FRAMEWORK = {

    # Use Django's standard `django.contrib.auth` permissions,

    # or allow read-only access for unauthenticated users.

    'DEFAULT_PERMISSION_CLASSES': [

        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'

    ]

}

接着配置数据库信息,如果使用的是默认的sqlite3,可以不用配置:

配置mysql数据库:

参数说明:

HOST: 数据库服务器地址

NAME: 数据库名称,对应database

USER: 用户名

PASSWORD: 密码

PORT: 端口号

default-character-set: 默认字符集

 

 

问题1

保存后会报错误:django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.

由于django默认没有引入数据库包导致,在settings.py 所在的目录中新建init.py文件,并引入mysql数据库组件。

import pymysql
pymysql.install_as_MySQLdb()

创建模型models

users应用下models.py中创建user_info

from django.db import models

# Create your models here.
class UserInfoModels(models.Model):
    user_id = models.CharField(max_length=100,primary_key=True,db_index=True,blank=False,null=False)
    login_name = models.CharField(max_length=50,db_index=True,blank=False,null=False)
    username = models.CharField(max_length=50,blank=False,null=False)
    password = models.CharField(max_length=200,db_index=True,blank=False,null=False)
    phone = models.CharField(max_length=11,db_index=True,blank=False,null=False)
    email = models.CharField(max_length=100,blank=True,null=True)
    gender = models.BooleanField(default=0)
    address = models.TextField(blank=True,null=True)
    img = models.FileField(blank=True,null=True)
    status = models.BooleanField(default=0)
    is_del = models.BooleanField(default=0)
    create_time = models.DateTimeField(auto_now_add=True)
    create_userId = models.CharField(max_length=100,blank=True,null=True)
    create_userName = models.CharField(max_length=50,db_index=True,blank=False,null=False)
    update_time = models.DateTimeField(auto_now=True)
    update_userId = models.CharField(max_length=100,blank=True,null=True)
    update_userName = models.CharField(max_length=50,db_index=True,blank=False,null=False)
    remark = models.CharField(max_length=200,blank=True,null=True)
    account = models.OneToOneField(to_field="account_id",to="UserAccountModels",db_column="account",on_delete=models.SET_NULL,blank=True,null=True)

    class Meta :
        # 创建user_info表信息
        db_table = "user_info"


class UserAccountModels(models.Model):
    account_id = models.CharField(max_length=100,primary_key=True,db_index=True,blank=False,null=False)
    user_id = models.CharField(max_length=100,db_index=True,blank=False,null=False)
    vip_level = models.IntegerField(default=1,blank=False,null=False)
    vip_name = models.CharField(max_length=20,blank=False,null=False)
    integral = models.FloatField(blank=False,null=False)
    price = models.FloatField(blank=True,null=True)
    status = models.BooleanField(default=0)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    remark = models.CharField(max_length=200,blank=True,null=True)
    
    class Meta:
        #创建账号等级表
        db_table = "user_account"

 

生成建表文件:

语法格式:python manage.py makemigrations [应用名称]

python manage.py makemigrations users

执行migrate生成数据库表

python manage.py migrate

 数据表创建成功

 

users应用下新建序列化文件Serial.py

内容如下:

#encoding:utf-8
from rest_framework import serializers
from users.models import UserInfoModels,UserAccountModels

class UserInfoSerial(serializers.ModelSerializer):
    class Meta:
        model = UserInfoModels
        fields = ["user_id","login_name","username","phone",
                  "email","address","gender","img","status","account",
                  "create_time","update_time","remark"]

        depth = 1


class UserAccountSerial(serializers.ModelSerializer):
    class Meta:
        model = UserAccountModels
        fields = "__all__"

user应用下views.py 中创建查询视图

内容如下:

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from users.models import UserInfoModels,UserAccountModels
from users.Serial import UserInfoSerial,UserAccountSerial


class UserInfoViews(APIView):

    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self,request):
        queryset = UserInfoModels.objects.all()
        serializer_data = UserInfoSerial(instance=queryset,many=True)
        return Response(serializer_data.data)



class UserAccountViews(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self,request):
        queryset = UserAccountModels.objects.all()
        serializer_data = UserAccountSerial(instance=queryset,many=True)
        return Response(serializer_data.data)

users应用下创建urls.py 路由文件

内容如下:

from django.urls import path,include
from users.views import UserInfoViews,UserAccountViews


urlpatterns = [
    path('user_info/', UserInfoViews.as_view()),
    path("user_account/",UserAccountViews.as_view()),
]
最后配置myweb项目下的路由urls.py,如下:
from django.contrib import admin
from django.urls import path
from django.urls import include


urlpatterns = [
    # path('admin/', admin.site.urls),
    path("users/",include("users.urls")),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))

]

启动django服务

python manage.py runserver

访问user_info接口如下:

访问user_account接口如下:

 

posted @ 2024-03-03 13:32  西夏一品唐  阅读(132)  评论(0编辑  收藏  举报