背景
此文是接着上一篇的延续。
一、一个登录接口的实现和文章的增删改查逻辑的完成
1. 创建实体类
这里需要创建两个实体: 用户实体和文章实体;
在项目根目录 hello下,找到 blog这个app,在modeles.py 这类中创建
完整代码如下:
from django.db import models
# Create your models here.
class UserInfo(models.Model):
username = models.CharField(max_length=32,null=True,blank=True) # 用户名
password = models.CharField(max_length=64) # 密码
nickname = models.CharField(max_length=32,default='用户') # 昵称
status = models.BooleanField(default=True) # 状态
email = models.EmailField(null=True) # 邮箱
re_time = models.DateTimeField(auto_now_add=True,null=True,blank=True) # 注册时间
last_login = models.DateTimeField(auto_now=True,null=True,blank=True) # 最后登录
class Meta:
verbose_name = '用户'
verbose_name_plural = '用户 '
db_table = "UserInfo"
# null:如果为True,表示允许为空,默认值是False
# blank:如果为True,则该字段允许为空白,默认值是False。
# 要注意,这与 null 不同。null纯粹是数据库范畴的,而blank是数据验证范畴的。
#如果一个字段的blank=True,表单的验证将允许该字段是空值。如果字段的blank=False,该字段就是必填的。
class Blog(models.Model):
title = models.CharField(max_length=32,null=True,blank=False) # 名称
url = models.CharField(max_length=32,null=True,blank=False) # 图片地址
type = models.IntegerField(max_length=5,null=False)
class Meta:
verbose_name = '咨询'
verbose_name_plural = '咨询'
db_table = "blog"
根据模型,创建表,执行以下两句语句:
- python manage.py makemigrations
- python manage.py migrate
2. 项目根目录 hello下,找到 blog这个app,在views.py 中增加方法
- Login 登录方法
- 文章的增删改查四个方法
完整代码如下:
from django.shortcuts import render
import json
import os
# Create your views here.
from .models import *
from django.views import View
from django.http.response import HttpResponse
from django.http import JsonResponse
from django.conf import settings
# Create your views here.
def Login(request):
if request.method == 'POST':
print(request)
username = request.POST.get('username')
data = UserInfo.objects.filter(username=username).values('email', "username", "nickname","last_login")
print(data)
return JsonResponse({"code": 200, "message": username,"data":list(data)},safe=False)
class Blogs(View):
def post(self, req):
data = json.loads(req.body)
print(data)
try:
Blog.objects.create(title=data['title'], url=data['url'], type=data['type'])
return JsonResponse({"code": 200, "message": "添加成功"})
except:
return JsonResponse({"code": 403, "message": "数据有误"})
def get(self, req):
print("参数",req.GET.get("title"))
data = req.GET.get("title")
print(data)
if data:
data = Blog.objects.filter(title=data).values('title', "type", "url")
print("结果",data)
return JsonResponse({"code": 200, "data": list(data), "message": "获取成功"})
else:
data = Blog.objects.all().values('title', "type", "url")
return JsonResponse({"code": 200, "data": list(data), "message": "获取成功"})
def delete(self, req):
id = req.GET.get("id")
Blog.objects.filter(id=id).delete()
return JsonResponse({"code": 200, "message": "删除成功"})
def put(self, req):
data = json.loads(req.body)
print(data)
if data:
Blog.objects.filter(id=data['id']).update(title=data['title'], url=data['url'], type=data['type'])
obj = Blog.objects.filter(id=data['id']).first()
return JsonResponse({"code": 200, "message": "修改成功"})
else:
return JsonResponse({"code": 304, "message": "不可为空"})
3. 配置路由
在根目录hello下,默认的app 即 hello 中的urls.py 中添加
完整代码如下:
from django.contrib import admin
from django.urls import path
from django.views.static import serve
from django.conf import settings
from blog.views import Login,upload
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', Login),
path('upload/', upload),
path("userinfo", views.Blogs.as_view()),
path(r'^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT},name='media'),
]
4. 在根目录hello下,默认的app 即 hello settings.py 中添加
添加如下代码即可:
APPEND_SLASH=False
5. 测试
请求路径: http://127.0.0.1:8000/login/
http://127.0.0.1:8000/userinfo post 方法
指定参数查询: get
全部查询: get
指定参数删除:delete
修改: put
二、图片上传接口的完成
1. 项目根目录 hello下,找到 blog这个app,在views.py 中增加方法 upload
#上传文件
def upload(request):
if request.method == "POST":
#上传文件在request.FILES
print(request.POST)
print(request.FILES)
#获取上传文件对象
files = request.FILES.get("file")
#文件对象属性,文件名,文件大小
print(files.name,files.size)
path = "media/"
if not os.path.exists(path):
os.makedirs(path)
#新建文件句柄
db_file_path = os.path.join(settings.MEDIA_ROOT,files.name)
endPath = os.path.join(path + files.name)
f = open(os.path.join(path + files.name),"wb")
for line in files.chunks():
f.write(line);
f.close()
return JsonResponse({"code": 200, "message": "OK","data":db_file_path})
2. 配置路由
路由代码如下: 在第一步中已经添加了。
path("userinfo", views.Blogs.as_view()),
3. 测试
三、对接oss
对接需要的东西:
- 必须参数: yourAccessKeyId, 可以称为key,即账号
- 必须参数: yourAccessKeySecret, 可以称为密码,即密码
- 必须参数:yourBucketName, 可以称为目标地址,因为一般情况下一个账号里会创建多个bucket,以应对不同的业务场景。所以必须指定某一个bucket。通俗的理解就是你上传的图片,要存在哪一个文件夹里。
- 必须参数:Endpoint, 地区,不同地区的访问速度不同,比如说你的用户在杭州,存放在杭州用户访问应该是最快的。
以下代码是阿里云oss的示例简单修改:
# -*- coding: utf-8 -*-
import oss2
# 阿里云账号AccessKey
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# Endpoint以杭州为例,根据自己的实际地址修改。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
# 上传文件到OSS。
# <yourObjectName>由包含文件后缀,不包含Bucket名称组成的Object完整路径,例如abc/efg/123.jpg。
# <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
bucket.put_object_from_file('<yourObjectName>', '<yourLocalFile>')
四、知识补充
模型
一般来说,每一个模型都映射一张数据库表。
基础:
- 每个模型都是一个 Python 的类(对应java 中的实体),这些类继承 [
django.db.models.Model
] - 模型类的每个属性都相当于一个数据库的字段。
默认的字段类型:
AutoField 自动增长的IntegerField,通常不用指定,不指定时Django会自动创建属性名为id的自动增长属性。
BooleanField 布尔字段,值为True或False。
NullBooleanField 支持Null、True、False三种值。
CharField(max\_length=最大长度) 字符串。参数max\_length表示最大字符个数。
TextField 大文本字段,一般超过4000个字符时使用。
IntegerField 整数
DecimalField(max\_digits=None, decimal\_places=None) 十进制浮点数。
参数max\_digits表示总位。
参数decimal\_places表示小数位数。
常用于商品价格(精确度高)。
FloatField 浮点数。参数同上(精确度比上一个低)
DateField:(\[auto\_now=False, auto\_now\_add=False])日期。
TimeField 时间,参数同DateField。
DateTimeField 日期时间,参数同DateField。
FileField 上传文件字段。
ImageField 继承于FileField,对上传的内容进行校验,确保是有效的图片。
常用的类型:
- CharField
- BooleanField
- DateTimeField
- EmailField
- IntegerField
代码地址:
分享一下chatgpt 的体验网站和账号
微信搜索:游牧人坎布里奇,回复口号获取: 011231