django图片上传到oss_django 配置阿里云OSS存储media文件的例子
1. 安裝django-aliyun-oss2-storage包
linux上用 pip install django-aliyun-oss2-storage 無報(bào)錯(cuò),順利安裝
windows上報(bào)錯(cuò):
(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 "", line 1, in
File "C:\Users\super\AppData\Local\Temp\pip-build-pb4u0qtw\django-aliyun-oss2-storage\setup.py", line 5, in
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\
解決方法:
2. 解壓進(jìn)入解壓后的文件夾
3. 打開README.md 刪除所有內(nèi)容
4. 安裝
python setup.py install
2. 設(shè)置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"
順便提一下,當(dāng)在xadmin后臺(tái)上傳文件, filename的時(shí)候,文件會(huì)上傳到路徑
PREFIX_URL + BUCKET_NAME+"."END_POINT+MEDIA_URL+filename
但是在django 模板渲染html的時(shí)候,我們?nèi)ilename是按照格式:
前端html render出來后,其實(shí)看到的路徑是:
根本取不到阿里云服務(wù)器上的文件。所以需要設(shè)置個(gè)新的變量,如 ALI_MEDIA_URL在模板渲染的時(shí)候替換MEDIA_URL.
方法:
1. 創(chuàng)建新文件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. 在模板中設(shè)置為:
3. 設(shè)置uediitor
在DjangoUeditor/view.py中
之前存儲(chǔ)到本地的代碼是:
# 保存上傳的文件
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"寫入文件錯(cuò)誤:%s" % e
f.close()
return u"SUCCESS"
我們模仿這個(gè)寫一個(gè)上傳到阿里云:
#保存上傳文件到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)
在哪調(diào)用呢? 找到:
state = save_upload_file(file, os.path.join(OutputPath, OutputFile))
替換成:
state = save_upload_file_to_aliyun(file, OutputPathFormat)
配置結(jié)束。ueditor和xadmin上傳的圖片都會(huì)上傳到阿里云oss中
以上這篇django 配置阿里云OSS存儲(chǔ)media文件的例子就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持龍方網(wǎng)絡(luò)。
總結(jié)
以上是生活随笔為你收集整理的django图片上传到oss_django 配置阿里云OSS存储media文件的例子的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 罗永浩称仍要收购苹果冲上热搜!网友:苹果
- 下一篇: mac java版本 不一致_mac实现