ALLOWED_HOSTS = ["*"] # 允许任何人访问
DEBUG = True # 开表示可以看见日志,上线时要关了
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "AXF",
"USER": "root",
"PASSWORD": "",
"HOST": "localhost",
"POST": "3306",
}
}
CACHES = {
'default': {
"BACKEND": "django.core.cache.backends.db.DatabaseCache",
"LOCATION": "my_cache_table",
"TIMEOUT": 60 * 5
},
"redis": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
给了两个缓存,用户可以自己选择
LANGUAGE_CODE = 'zh-hans' # 汉语
TIME_ZONE = 'Asia/Shanghai' # 上海时间
USE_I18N = True
USE_L10N = True
USE_TZ = False # 时区
import pymysql
pymysql.install_as_MySQLdb() # 切换引擎
STATICFILES_DIRS = {
os.path.join(BASE_DIR, "static")
}
MEDIA_ROOT = os.path.join(BASE_DIR, "static/uploads")
urlpatterns = [
path('admin/', admin.site.urls),
path('axf/', include(("AXF.urls", "AXF"), namespace="axf")),
]
namespace在后面的页面跳转中很重要,前面要给个元组
urlpatterns = [
url(r"^index$", views.index, name="index")
]
给每个路由一个命名空间,彼此隔离,方便将来调试
python manage.py makemigrations
python manage.py migrate
python manage.py runserver 8888
8888端口起项目
断言:返回Hello Django
并不是最完整的文件格式,依赖需求文件,uwsgi.ini文件,dockerfile文件,jenkinsfile文件等后续需要自己补充
进到CBV 里面进行反射匹配
qs=obj.all()拿到qrueyset
将Bookserializer 将要序列化的数据放进去many=true代表要序列化单条数据还是多条数据,返回值是一个序列化后的数据,
.data属性可以拿到里面的内容
request不是Django中的request,是drf中重新自己写的request
在Bookserializer 里面data=request.data获取到的是提交上来的body里面的数据进行save
save后会返回本身,可以拿到pk属性
response.Response这么进行返回数据
mdoel在Bookserializer 里面做了映射关系
分别对model进行序列化,在里面可以进行添加字段
在里面进行class Meta:定义元数据,有model属性和fields属性对应model里面的字段 __all__是全部都拿到
put更新操作先获取实例
static文件引入的方式 https://www.cnblogs.com/yangxiaolan/p/5826661.html
a = 2
isinstance(a,int) # 结果返回 True
Python中的 isinstance() 函数,是Python中的一个内置函数,用来判断一个函数是否是一个已知的类型,类似 type()
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import views, response
from rest_framework import serializers
# Create your views here.
from AXF.models import Book
'''
慢既是快
'''
class ImagePathField(serializers.FileField): # 自定义字段
def __init__(self, domin, *args, **kwargs):
self.domin = domin # 传来个域名进行实例化
super(ImagePathField, self).__init__(*args, **kwargs)
# 抽象方法必须重写实现
def to_representation(self, value): # 序列化会走这个方法
# print("111", value)
if not self.domin:
self.domin = "www.bilibili.com" # 没有给个默认值
return "{}/{}.png".format(self.domin, value) # 自定义字段返回加工后的方法
def to_internal_value(self, data): # 暂时不关心
print("222", data)
return data
# 序列化Book表model
class BookSerializer(serializers.ModelSerializer):
# book_time = serializers.DateTimeField(format="%Y-%m-%d %X")
image = ImagePathField(domin="", source="pk") # 实现自定义字段
class Meta: # 元数据
model = Book # 指定model类
fields = "__all__" # 代表所有字段都序列化
# fields = (
# "price", # 这里必须有个","代表是元组
# )
class BookView(views.APIView): # CBV,对django的view进行扩充
'''
查询数据
'''
def get(self, request): # 内部用反射来做的方法判断
book_qrueyset = Book.objects.all() # 返回一个qrueyset
serializer = BookSerializer( # 实例化序列化的类
book_qrueyset.all(), # 数据库操作拿多少
many=True) # many=True返回一个列表
return response.Response({ # response.Response返回序列化后的数据
"code": 800,
"data": serializer.data
})
def post(self, request): # post方法进来
serializer = BookSerializer(data=request.data) # post的body里面的数据放进来
if serializer.is_valid(): # form表单的校验
instance = serializer.save() # 保存到数据库
return response.Response({
"code": 801,
"data": instance.pk # 返回pk
})
else: # 校验失败返回错误状态码
return response.Response({
"code": 802,
"data": serializer.errors
})
def index(request):
return HttpResponse("Hello Django")
class BookDetailView(views.APIView):
def put(self, request, pk):
instance = Book.objects.filter(pk=pk).first() # 先获取
# print(instance)
if not instance:
return response.Response({
"code": 803,
"data": "数据不存在"
})
serializer = BookSerializer(
instance=instance,
data=request.data) # 将instance传过来进行检验
if serializer.is_valid(): # 开始校验
instance = serializer.save() # 判断是否存在,存在就修改
return response.Response({
"code": 804,
"data": instance.pk
})
else: # 校验失败返回错误状态码
return response.Response({
"code": 805,
"data": serializer.errors
})
def delete(self, request, pk):
instance = Book.objects.filter(pk=pk).delete()
return response.Response({
"code": 808,
"data": "success"
})
from django.db import models
# Create your models here.
class Book(models.Model):
# tel = models.CharField(max_length=11)
book_name = models.CharField(max_length=20)
# password = models.CharField(max_length=20)
# s_token = models.CharField(max_length=50)
# name = models.CharField(max_length=20)
# gender = models.BooleanField(default=True)
price = models.IntegerField(null=True)
book_time = models.CharField(max_length=20)
book_zuozhe = models.CharField(max_length=20)
book_num = models.IntegerField(null=True)
from django.conf.urls import url
from AXF import views
urlpatterns = [
url(r"^index$", views.index, name="index"),
url(r"^book$", views.BookView.as_view(), name="book"),
url(r"^book_del/(?P\d+)/$" , views.BookDetailView.as_view(), name="book_del")
]