使用Django模型在DB中存储图像 [英] Storing Images In DB Using Django Models

查看:125
本文介绍了使用Django模型在DB中存储图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Django创建一个Web服务,我希望该Web服务返回图像。我决定我的Web服务的基本架构。在google上绊倒后我得出的结论是:


  1. 我应该将图片编码为Base64格式后存储在DB中。

  2. 直接传输Bases64解码字符串时,传输图片会很容易。

但我有一个问题如何使用Django模型存储base64编码字符串在DB中?此外,如果你看到我的基本架构中的任何缺陷,请指导我。



我是新的Web服务和Django



谢谢!!

解决方案

有些人说使用DB存储图像不是一个好主意,但这不是真的。我的建议是使用Django与 AppEngine Blobstore服务以这种方式: / p>

首先,创建 Django自定义存储

 来自django.core.files.storage import Storage 

class AppEngineBlobStorage(Storage):

def exists(self,name):
...

def size(self,name):
...

def url(self,name):
...

def delete(self,name):
.. 。

def listdir(self,path):
raise NotImplementedError()


$ b b

此自定义存储可以接收Django图像,将它们转换为Base64字符串并将其发送到AppEngine Blobstore Service应用程序(例如通过xmlrpc)。



创建一个Django图片模型:

 从django.db导入模型
from django.db.models.fields.files import ImageField
from .storage import AppEngineBlobStorage

class Photo(models.Model):
caption = models.CharField(max_length = 64,blank = True)
blob = ImageField(
upload_to ='BlobStorage',
storage = AppEngineBlobStorage(),
max_length = 255,
blank = False,

serving_url = models.URLField()
...

然后,您必须创建AppEngine应用程序用于接收用于存储图像的Django请求,将Base64字符串变换为raw并将它们存储在Blob中。例如:

 #coding = utf-8 

from __future__ import with_statement

import webapp2

来自base64 import b64decode
来自StringIO import StringIO
来自xmlrpcserver import XmlRpcServer

来自google.appengine.api import files
来自google.appengine.api import images
来自google.appengine.ext import blobstore
来自google.appengine.ext.webapp import blobstore_handlers


ImageRpcServer(object):

def upload(self,meta,photo,mime_type):
data = b64decode(photo)
file_name = files.blobstore.create(mime_type = mime_type )
with files.open(file_name,'a')as f:
f.write(data)
files.finalize(file_name)
key = files.blobstore.get_blob_key (file_name)
return str(key)

def serving_url(self,meta,key):
return images.get_serving_url(blobstore.BlobKey(key))

...

提供Blob



关键是函数 get_serving_url 。从Google文档:


如果您要提供图片,更高效且潜在的
更便宜的方法是使用get_serving_url App Engine
Images API而不是send_blob。 get_serving_url函数允许
直接提供图片,而无需浏览您的App
Engine实例。


最后,通过使用AppEngine提供图片,您可以使用调整大小和裁剪图片的真棒功能(检查 get_serving_url 函数的文档),例如:


//将图片大小调整为32像素(保留纵横比)
http://your_app_id.appspot.com/randomStringImageId=s32


希望它有帮助。祝你好运!


I am using Django for creating one Web service and I want that web service to return Images. I am deciding the basic architecture of my Web service. What I came up to conclusion after stumbling on google is:

  1. I should store Images in DB after encoding them to Base64 format.
  2. Transferring the Images would be easy when directly Bases64 decoded string is transmitted.

But I have one issue how can I store bases64 encoded string in DB using Django models? Also, if you see any flaw in my basic architecture please guide me.

I am new to Web services and Django

Thanks!!

解决方案

Some people states that using DB for storing images is not a good idea but that's no true. My advice is to use Django with AppEngine Blobstore Service in this way:

First, create a Django Custom Storage:

from django.core.files.storage import Storage 

class AppEngineBlobStorage(Storage):

    def exists(self, name):
       ...   

    def size(self, name):
       ...

    def url(self, name):
       ...

    def delete(self, name):
       ...

    def listdir(self, path):
       raise NotImplementedError()

This custom storage can receive Django images, convert them to Base64 strings and send them to your AppEngine Blobstore Service application (via xmlrpc for example).

Then, create a Django Image model:

from django.db import models
from django.db.models.fields.files import ImageField
from .storage import AppEngineBlobStorage

class Photo(models.Model):
    caption = models.CharField(max_length=64, blank=True)
    blob = ImageField(
        upload_to='BlobStorage',
        storage=AppEngineBlobStorage(),
        max_length=255,
        blank=False,
    )
    serving_url = models.URLField()
    ...

Then, you have to create an AppEngine application for receiving Django requests for storing images, transform Base64 strings to raw and store them in a Blob. For example:

# coding=utf-8

from __future__ import with_statement

import webapp2

from base64 import b64decode
from StringIO import StringIO
from xmlrpcserver import XmlRpcServer

from google.appengine.api import files
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers


class ImageRpcServer(object):

    def upload(self, meta, photo, mime_type):
        data = b64decode(photo)
        file_name = files.blobstore.create(mime_type=mime_type)
        with files.open(file_name, 'a') as f:
            f.write(data)
        files.finalize(file_name)
        key = files.blobstore.get_blob_key(file_name)
        return str(key)

    def serving_url(self, meta, key):
        return images.get_serving_url(blobstore.BlobKey(key))

      ...

Serving a blob

The key is the function get_serving_url. From Google docs:

If you are serving images, a more efficient and potentially less-expensive method is to use get_serving_url using the App Engine Images API rather than send_blob. The get_serving_url function lets you serve the image directly, without having to go through your App Engine instances.

Finally, by serving images with AppEngine, you can use the awesome feature of resize and crop images (check the documentation of get_serving_url function), for example:

// Resize the image to 32 pixels (aspect-ratio preserved) http://your_app_id.appspot.com/randomStringImageId=s32

Hope it helps. Good luck!

这篇关于使用Django模型在DB中存储图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆