python

超轻量级php框架startmvc

django 配置阿里云OSS存储media文件的例子

更新时间:2020-07-25 15:06:01 作者:startmvc
1.安装django-aliyun-oss2-storage包linux上用pipinstalldjango-aliyun-oss2-storage无报错,顺利安装windows上

1. 安装django-aliyun-oss2-storage包

linux上用 pip install django-aliyun-oss2-storage 无报错,顺利安装

windows上报错:


(python3_sbs) F:\projects\virtualenv\python3_sbs\Scripts>pip install django-aliyun-oss2-storage
Collecting django-aliyun-oss2-storage
 Using cached django-aliyun-oss2-storage-0.1.5.tar.gz
 Complete output from command python setup.py egg_info:
 Traceback (most recent call last):
 File "<string>", line 1, in <module>
 File "C:\Users\super\AppData\Local\Temp\pip-build-pb4u0qtw\django-aliyun-oss2-storage\setup.py", line 5, in <module>
 README = readme.read()
 UnicodeDecodeError: 'gbk' codec can't decode byte 0x91 in position 63: illegal multibyte sequence
 
 ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\super\AppData\Local\Temp\pip-build-pb4u0qtw\django-aliyun-oss2-storage\

解决方法:

1. 下载源码 django-aliyun-oss2-storage-0.1.5.tar.gz 地址: https://github.com/xiewenya/django-aliyun-oss2-storage

2. 解压进入解压后的文件夹

3. 打开README.md 删除所有内容

4. 安装


python setup.py install

2. 设置setting.py


 ACCESS_KEY_ID = "xxxx"
 ACCESS_KEY_SECRET = "xxxx"
 END_POINT = "oss-cn-beijing.aliyuncs.com"
 PREFIX_URL = 'http://'
 BUCKET_NAME = "xxx"
 ALIYUN_OSS_CNAME = "" # 自定义域名,如果不需要可以不填写
 BUCKET_ACL_TYPE = "public-read" # private, public-read, public-read-write
 DEFAULT_FILE_STORAGE = 'aliyun_oss2_storage.backends.AliyunMediaStorage'
 MEDIA_URL = '/media/'
 MEDIA_ROOT = "media"

顺便提一下,当在xadmin后台上传文件, filename的时候,文件会上传到路径


PREFIX_URL + BUCKET_NAME+"."END_POINT+MEDIA_URL+filename

但是在django 模板渲染html的时候,我们取filename是按照格式:


<img src="{{ MEDIA_URL }}{{ object.image }}"

前端html render出来后,其实看到的路径是:


<img src="/media/image/2017/12/timg.jpg"

根本取不到阿里云服务器上的文件。所以需要设置个新的变量,如 ALI_MEDIA_URL在模板渲染的时候替换MEDIA_URL.

方法:

1. 创建新文件my_processor.py


from __future__ import unicode_literals
 
import itertools
 
from django.conf import settings
from django.middleware.csrf import get_token
from django.utils.encoding import force_text
from django.utils.functional import SimpleLazyObject, lazy
 
def ali_media(request):
 """
 Adds media-related context variables to the context.
 """
 return {'ALI_MEDIA_URL': settings.ALI_MEDIA_URL}

2. setting.py中


ALI_MEDIA_URL = PREFIX_URL + BUCKET_NAME + "." + END_POINT + '/media/'
 
TEMPLATES = [
 {
 'BACKEND': 'django.template.backends.django.DjangoTemplates',
 'DIRS': [os.path.join(BASE_DIR, 'templates')],
 'APP_DIRS': True,
 'OPTIONS': {
 'context_processors': [
 'django.template.context_processors.debug',
 'django.template.context_processors.request',
 'django.contrib.auth.context_processors.auth',
 'django.contrib.messages.context_processors.messages',
 'django.template.context_processors.media',
 'utils.sbs_processor.ali_media',
 ],
 },
 },
]

3. 在模板中设置为:


<img src="{{ ALI_MEDIA_URL }}{{ object.image }}" 

3. 设置uediitor

在DjangoUeditor/view.py中

之前存储到本地的代码是:


# 保存上传的文件
def save_upload_file(PostFile, FilePath):
 try:
 f = open(FilePath, 'wb')
 for chunk in PostFile.chunks():
 f.write(chunk)
 except Exception as e:
 f.close()
 return u"写入文件错误:%s" % e
 f.close()
 return u"SUCCESS"

我们模仿这个写一个上传到阿里云:


#保存上传文件到aliyun
def save_upload_file_to_aliyun(PostFile, Outputfile):
 access_key = ACCESS_KEY_ID
 secret_key = ACCESS_KEY_SECRET
 bucket_name = BUCKET_NAME
 try:
 import oss2
 auth = oss2.Auth(access_key, secret_key)
 bucket = oss2.Bucket(auth, END_POINT, bucket_name)
 # ret, info = put_file(token, key, upload_file)
 result=bucket.put_object(Outputfile, PostFile)
 return u"SUCCESS"
 # if ret.get('key',None) == None:
 # raise Exception('upload error')
 # else:
 # return u"SUCCESS"
 except Exception as e:
 print(str(e))
 return str(e)

在哪调用呢? 找到:


state = save_upload_file(file, os.path.join(OutputPath, OutputFile))

替换成:


state = save_upload_file_to_aliyun(file, OutputPathFormat)

配置结束。ueditor和xadmin上传的图片都会上传到阿里云oss中

以上这篇django 配置阿里云OSS存储media文件的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

django 配置 阿里云OSS media