Django是Python语言中目前功能最全面的网站框架,特别适合Python全栈开发者使用,下面我们实际用Django来实现一个带收费功能的书籍信息查询API。
API具体需求如下,
- 通过书籍ISBN编号返回一本书的基本信息
- 返回结果用Json实现系列化
- 每成功调用API一次,按用户账号扣减一次余额
00 准备工作
-
首先下载最新版本的Python安装程序,并安装。
-
安装好Django以及Django REST framework
pip install django djangorestframework markdown django-filter
注意安装好后,需要配置path环境变量
- 下载并安装PyCharm
01 创建一个名称为book的Django项目及一个users的App
进入到Python 项目的根目录(我设置的是D:\documents\sourcecode),执行如下指令
cd D:\documents\sourcecode
django-admin startproject employee
cd D:\documents\sourcecode\book
python manage.py startapp users
02 配置项目
a. 在settings.py INSTALLED_APPS 字符串定义中增加如下两行
'users.apps.UsersConfig'
'rest_framework'
b. 在users\models.py中重构用户表UserProfile
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
"""
用户
"""
APIkey=models.CharField(max_length=30,verbose_name='APIkey',default='abcdefghigklmn')
money=models.IntegerField(verbose_name='余额',default=10)
class Meta:
verbose_name = '用户'
verbose_name_plural=verbose_name
def __str__(self):
return self.username
c. 在setting.py中配置用户表的继承代码
AUTH_USER_MODEL='users.UserProfile'
d. 在users目录下的models.py文件中,新建书籍信息表book
from django.db import models
from datetime import datetime
class Book(models.Model):
"""
书籍信息
"""
title=models.CharField(max_length=30,verbose_name='书名',default='')
isbn=models.CharField(max_length=30,verbose_name='isbn',default='')
author=models.CharField(max_length=20,verbose_name='作者',default='')
publish=models.CharField(max_length=30,verbose_name='出版社',default='')
rate=models.FloatField(default=0,verbose_name='豆瓣评分')
add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
class Meta:
verbose_name='书籍信息'
verbose_name_plural = verbose_name
def __str__(self):
return self.title
03 生成项目数据
a. 初始化项目数据,执行如下两行指令
python manage.py makemigrations
Output 如下:
Migrations for 'users':
users\migrations\0001_initial.py
- Create model Book
- Create model UserProfile
python manage.py migrate
Output如下:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, users
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying users.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying sessions.0001_initial... OK
b. 创建一个超级用户
python manage.py createsupersuer
按提示如下用户名,邮箱及密码
c. 录入book数据
用数据库客户端连接项目目录下的db.sqlite3文件,插入几条测试数据,我用的是DBeaver客户端,执行SQL如下
insert into users_book(id,title,isbn,author,publish,rate,add_time)
values (3,'cory book3','10003','cory','cory publisher',1,'2022-03-06')
04 用Django REST framework实现序列化
a. 在users目录下新建文件serializers.py
from rest_framework import serializers
from .models import UserProfile,Book
class BookSeriallizer (serializers.Serializer):
title=serializers.CharField(required=True,max_length=100)
isbn = serializers.CharField(required=True, max_length=100)
auther = serializers.CharField(required=True, max_length=100)
publish = serializers.CharField(required=True, max_length=100)
rate = serializers.FloatField(default=0)
b. 在users\views.py中,编写如下视图代码
from .serializers import BookSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile,Book
class BookAPIView1(APIView):
"""
使用Serializer
"""
def get(self, request, format=None):
APIKey=self.request.query_params.get("apikey", 0)
developer=UserProfile.objects.filter(APIkey=APIKey).first()
if developer:
balance=developer.money
if balance>0:
isbn = self.request.query_params.get("isbn", 0)
books = Book.objects.filter(isbn=int(isbn))
books_serializer = BookSerializer(books, many=True)
developer.money-=1
developer.save()
return Response(books_serializer.data)
else:
return Response("余额不足,请充值")
else:
return Response("查无此账号")
c. 在urls.py中配置路由
from django.contrib import admin
from django.urls import path
from users.views import BookAPIView1
urlpatterns = [
path('admin/', admin.site.urls),
path('apibook1/',BookAPIView1.as_view(),name='book1'),
]
05 大功告成测试效果
启动项目
python manage.py runserver
在浏览器中访问API访问如下数据
api返回页面http://127.0.0.1:8000/apibook1/?apikey=abcdefghigklmn&isbn=10003
连续访问10次后返回如下
余额不足页面
网友评论