经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Django » 查看文章
django 配置阿里云OSS存储media文件的例子
来源:jb51  时间:2019/8/21 9:18:08  对本文有异议

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

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

windows上报错:

  1. (python3_sbs) F:\projects\virtualenv\python3_sbs\Scripts>pip install django-aliyun-oss2-storage
  2. Collecting django-aliyun-oss2-storage
  3. Using cached django-aliyun-oss2-storage-0.1.5.tar.gz
  4. Complete output from command python setup.py egg_info:
  5. Traceback (most recent call last):
  6. File "<string>", line 1, in <module>
  7. File "C:\Users\super\AppData\Local\Temp\pip-build-pb4u0qtw\django-aliyun-oss2-storage\setup.py", line 5, in <module>
  8. README = readme.read()
  9. UnicodeDecodeError: 'gbk' codec can't decode byte 0x91 in position 63: illegal multibyte sequence
  10. ----------------------------------------
  11. 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. 安装

  1. python setup.py install

2. 设置setting.py

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

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

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

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

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

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

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

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

方法:

1. 创建新文件my_processor.py

  1. from __future__ import unicode_literals
  2. import itertools
  3. from django.conf import settings
  4. from django.middleware.csrf import get_token
  5. from django.utils.encoding import force_text
  6. from django.utils.functional import SimpleLazyObject, lazy
  7. def ali_media(request):
  8. """
  9. Adds media-related context variables to the context.
  10. """
  11. return {'ALI_MEDIA_URL': settings.ALI_MEDIA_URL}

2. setting.py中

  1. ALI_MEDIA_URL = PREFIX_URL + BUCKET_NAME + "." + END_POINT + '/media/'
  2. TEMPLATES = [
  3. {
  4. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  5. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  6. 'APP_DIRS': True,
  7. 'OPTIONS': {
  8. 'context_processors': [
  9. 'django.template.context_processors.debug',
  10. 'django.template.context_processors.request',
  11. 'django.contrib.auth.context_processors.auth',
  12. 'django.contrib.messages.context_processors.messages',
  13. 'django.template.context_processors.media',
  14. 'utils.sbs_processor.ali_media',
  15. ],
  16. },
  17. },
  18. ]

3. 在模板中设置为:

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

3. 设置uediitor

在DjangoUeditor/view.py中

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

  1. # 保存上传的文件
  2. def save_upload_file(PostFile, FilePath):
  3. try:
  4. f = open(FilePath, 'wb')
  5. for chunk in PostFile.chunks():
  6. f.write(chunk)
  7. except Exception as e:
  8. f.close()
  9. return u"写入文件错误:%s" % e
  10. f.close()
  11. return u"SUCCESS"

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

  1. #保存上传文件到aliyun
  2. def save_upload_file_to_aliyun(PostFile, Outputfile):
  3. access_key = ACCESS_KEY_ID
  4. secret_key = ACCESS_KEY_SECRET
  5. bucket_name = BUCKET_NAME
  6. try:
  7. import oss2
  8. auth = oss2.Auth(access_key, secret_key)
  9. bucket = oss2.Bucket(auth, END_POINT, bucket_name)
  10. # ret, info = put_file(token, key, upload_file)
  11. result=bucket.put_object(Outputfile, PostFile)
  12. return u"SUCCESS"
  13. # if ret.get('key',None) == None:
  14. # raise Exception('upload error')
  15. # else:
  16. # return u"SUCCESS"
  17. except Exception as e:
  18. print(str(e))
  19. return str(e)

在哪调用呢? 找到:

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

替换成:

  1. state = save_upload_file_to_aliyun(file, OutputPathFormat)

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

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号