django开发api

Ikko Lv3

django开发api

1.安装django

1
pip install django

2.创建项目

1
django-admin startproject api

3.创建应用

1
python manage.py startapp api

安装rest_framework

1
pip install djangorestframework

4.配置settings.py

1
2
3
4
INSTALLED_APPS = [
'rest_framework',
'api',
]

5.创建model

1
2
3
from django.db import models


6.创建序列化器

1
2
3
4
5
6
7
from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email']

7.创建视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from django.shortcuts import render
from django.contrib.auth.models import User
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .serializers import UserSerializer

class UserAPIView(APIView):
# permission_classes = [IsAuthenticated]

def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)

  • Title: django开发api
  • Author: Ikko
  • Created at : 2023-06-03 14:34:06
  • Updated at : 2023-06-03 15:30:27
  • Link: https://redefine.ohevan.com/2023/06/03/django开发api/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments