django mysql数据库及图片上传接口详解

  • 时间:
  • 浏览:32

媒介

我们正在 django-rest-framework剖析要求参数 文章中完成了接心文档到参数剖析, 1个完全的流程中借贫乏对数据库的操纵. 本篇内容为django毗连数据库, 并编写1个image表用去存储图片途径, 编写图片上传接心战检察数据库中一切图片途径的接心.

后期筹办

django操纵图片需求装置1个3圆库叫做,Pillow

workon Python35
pip install pillow
pip install pymysql

Pillow那个库能够对图片停止操纵, 比方死成缩略图等等, 十分壮大.

pymysql是python3顶用去毗连数据库的1个库.

装置mysql数据库. 装置MySQLWorkBench(做用战navicat1样,利用其他硬件也能够)

选好面击apply 提交创立新库.

django若何存储图片

1般图片没有存数据库零丁存储于某个途径, 开辟进程中便存正在项目标某个途径下.

iOS开辟中有个http 304成绩. 便是要求图片时, 若是有缓存间接与缓存的图片. 现实上苹果早已帮我们处置好了. 现实开辟中没有需求针对http 304编写任何代码.

闭于http 304的成绩

那1篇文章写的十分具体了.

如今我们停止办事端编程, 办事端是若何死成etag, last-modify那些参数的呢?

那个成绩触及到办事端框架对静态资本的办理办法.

正在现实将项目摆设到办事器上时, 我们对静态资本战静态资本是分隔办理的. 我利用nginx+uwsgi 摆设, nginx 办理静态资本,ETag 之类的, nginx 会主动死成,办理, 没有需求办事端法式员为此编写甚么代码.....

图片上传接心, 领受到图片文件, 范例, 巨细校验, 将图片保留到静态文件目次下, 死成此图片的url存储到mysql数据库.

编写存储图片途径战id的表.

修正models.py文件.

from django.db import models
import datetime
class Image(models.Model):
 # url = models.TextField(null=True)
 image = models.ImageField(upload_to=str('image/{time}'.format(time=str(datetime.date.today().strftime("%Y%m/%d")))))
 create_time = models.DateTimeField(auto_now_add=True, null=True)
 update_time = models.DateTimeField(auto_now=True, null=True)

 class Meta:
 pass

ImageField中的upload_to暗示图片上传的详细途径.

修正数据库设置装备摆设毗连mysql

修正settings.py文件中的DATABASES 到上面的款式. name是方才创立mysql新库的称号. user password 是mysql用户的用户名战稀码. mysql端标语默许为3306

DATABASES = {
 'default': {
  'ENGINE': 'django.db.backends.mysql',
  'NAME': 'test',
  'USER': 'root',
  'PASSWORD': '111111',
  'HOST': '127.0.0.1',
  'PORT': '3306',
 }
}

记得删除 migrations目次下除__init__.py 以外的一切文件.

那些文件记载了对数据库界说个全部修正流程. 切换数据库后那个流程战新库底子对没有上号. 需求全数删除.

修正取settings.py 统一目次的__init__.py 文件

增加两止代码

import pymysql
pymysql.install_as_MySQLdb()

cd到项目manage.py文件的途径下,运转

workon python35
python manage.py makemigrations
python manage.py migrate

利用mysqlworkbench 毗连3306翻开之前创立的库能够看到表皆已被创立出去

编写图片上传接心

from rest_framework import serializers
class ImageUploadSerializer(serializers.Serializer):
  token = serializers.CharField(max_length=100)
  image = serializers.ImageField()

from .models import *
from django.views.decorators.csrf import csrf_exempt
import time
import hashlib
class ImageUpload(APIView):
  '''
  图片上传接心 \n
  "http://127.0.0.1:8000/pages/uploadImage"   (我简朴写了个页里做提交)\n
  '''

  # coreapi_fields = (DocParam(name='token', description='token'),
  #          DocParam(name='image', description='文件', type='file'),)

  @csrf_exempt
  def post(self, request, *args, **kwargs):

    image = request.FILES['image']
    data = get_parameter_dic(request)
    # 需求判定文件范例是不是是图片.
    serial = ImageUploadSerializer(data={"token": data["token"],
                       "image": image})
    if serial.is_valid():
      print("校验胜利")
    else:
      return JsonError("参数校验失利")

    image = serial.validated_data.get("image")

    new_image = Image(image=image)
    imageName = str(new_image.image.name)
    location = str(imageName).find('.')
    extension = imageName[location:]

    name = imageName[:location]
    namestring = name+str(time.time())
    md5 = hashlib.md5(namestring.encode('utf⑻')).hexdigest()
    new_image.image.name = md5[:10] + extension
    new_image.save()


    return JsonResponse(data=new_image)

运转项目

挪用上传图片接心, 我用了postman测试接心

图片存储地位

图片的完全拜候途径为

http://localhost:8000/image/201710/20/d527b242d1.jpg

此时要求会失利由于那个途径没有许可拜候, 需求停止简朴设置装备摆设
setting.py 文件中增加

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')

urls.py文件中增加

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.schemas import get_schema_view
from mytest.views import ReturnJson
import mytest
from mytest.views import SwaggerSchemaView
from mytest.views import ImageUpload
from django.views.static import serve
from django.conf import settings

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
  url(r'^docs/', SwaggerSchemaView.as_view(), name='apiDocs'),
  url(r'^api/getjson', ReturnJson.as_view()),
  url(r'^api/uploadimage', ImageUpload.as_view()),
  # url(r'^static/(?P.*)$', serve, {'document_root': settings.STATIC_ROOT}),
  url(r'^media/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]

此次图片链接变成

http://localhost:8000/media/image/201710/20/d527b242d1.jpg

写1个查询一切图片并前往json的接心

from .models import Image
class GETAllImages(APIView):

  def get(self, request, *args, **kwargs):
    imagesset=Image.objects.all()
    return JsonResponse(data=imagesset)

修正urls.py文件增加此接心

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.schemas import get_schema_view
from mytest.views import ReturnJson
import mytest
from mytest.views import SwaggerSchemaView
from mytest.views import ImageUpload, GETAllImages
from django.views.static import serve
from django.conf import settings

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
  url(r'^docs/', SwaggerSchemaView.as_view(), name='apiDocs'),
  url(r'^api/getjson', ReturnJson.as_view()),
  url(r'^api/uploadimage', ImageUpload.as_view()),
  url(r'^api/getallimage', GETAllImages.as_view()),
  url(r'^static/(?P.*)$', serve, {'document_root': settings.STATIC_ROOT}),
  url(r'^media/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]

全数弄定

以上便是本文的全数内容,期望对各人的进修有所帮忙,也期望各人多多撑持剧本之家。