photo_upload.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. import os
  4. import re
  5. import time
  6. import datetime
  7. import random
  8. import hashlib
  9. from ufile import filemanager
  10. from ufile import config as ufile_config
  11. from ufile import logger as img_log
  12. public_key = 'ucloudyunkaopei@outlook.com13615403931104805307'
  13. private_key = 'bcfd5bb66ca527c9be9fd7f3e784fbfc90c4bba5'
  14. addr = '.cn-bj.ufileos.com' # 后缀拼接
  15. ufile_config.set_default(uploadsuffix=addr)
  16. # 公共空间名称
  17. public_bucket = 'zxhx' # 线上正式环境
  18. # public_bucket = 'zxhx-test' # 线上测试环境
  19. image_upload_log = './logs/image_log.txt' # 图片上传日志
  20. img_log.set_log_file(image_upload_log)
  21. # todo 上传图片进程
  22. def upload_img_to_ucloud(param_ucloud):
  23. put_key, localfile = param_ucloud
  24. putufile_handler = filemanager.FileManager(public_key, private_key)
  25. # 普通上传文件至公共空间
  26. ret, resp = putufile_handler.putfile(public_bucket, put_key, localfile, header=None)
  27. assert resp.status_code == 200
  28. def upload_replace_image(filename_root, sid, html):
  29. return_error = {"errcode": 1,
  30. "errmsg": "word图片上传失败。"}
  31. daytime = datetime.datetime.now().strftime('/%Y/%m/%d/')
  32. image_path = filename_root + "/files"
  33. # todo 判断试卷是否含有图片,如果有就替换上传,没有就不处理
  34. local2online_dict = {}
  35. judge_file = os.path.isdir(image_path)
  36. if judge_file: # 可以不用判断
  37. image_number = re.findall(r'<img\s*src\s*=\s*"files/image', str(html))
  38. local_images_path_list = os.listdir(image_path) # 本地图片文件名
  39. local_images_path_list = list(filter(
  40. lambda x: str(x).endswith(".png") or str(x).endswith(".gif") or str(x).endswith(".jpeg") or str(x).endswith(
  41. ".jpg"), local_images_path_list)) # 只允许特定后缀名的图片
  42. if len(image_number) != len(local_images_path_list):
  43. return return_error
  44. else:
  45. # 從大到小把圖片进行排序
  46. try:
  47. local_images_path_list.sort(key=lambda x: int(re.search(r"image(\d+)\.[pngifje]+", str(x)).group(1)))
  48. except:
  49. return return_error
  50. # logger.info("local_images_path_list==>{}".format(str(local_images_path_list)))
  51. put_key_list = [] # 线上图片地址
  52. localfile_list = [] # 本地图片地址
  53. rawpic_list = []
  54. online_image_url_list = []
  55. if local_images_path_list:
  56. try:
  57. for i, img in enumerate(local_images_path_list, start=1): # 所有的图片【image1.png,image2.png,。。。】
  58. src_pat2 = re.compile(r'<img\s*src\s*=\s*"files/image{}\.png"'.format(i))
  59. src_pat3 = re.compile(r'<img\s*src\s*=\s*"files/image{}\.gif"'.format(i))
  60. src_pat4 = re.compile(r'<img\s*src\s*=\s*"files/image{}\.jpeg"'.format(i))
  61. src_pat5 = re.compile(r'<img\s*src\s*=\s*"files/image{}\.jpg"'.format(i))
  62. if str(img).endswith("png"):
  63. pat = src_pat2
  64. # re_list.append(src_pat2)
  65. elif str(img).endswith("gif"):
  66. pat = src_pat3
  67. # re_list.append(src_pat3)
  68. elif str(img).endswith("jpeg"):
  69. pat = src_pat4
  70. # re_list.append(src_pat4)
  71. elif str(img).endswith("jpg"):
  72. pat = src_pat5
  73. # re_list.append(src_pat5)
  74. # todo 上传线上,并替换线上图片
  75. localfile = image_path + "/{}".format(img)
  76. rawfile = '<img src="files'+ "/{}".format(img)
  77. localfile_list.append(localfile)
  78. rawpic_list.append(rawfile)
  79. # todo 图片压缩
  80. # resize_img(localfile, localfile)
  81. hash_img = get_md5(img)
  82. # 上传文件在空间中的名称
  83. put_key = "teacher/uploadfiles/wording/" + str(sid) + str(daytime) + str(hash_img)
  84. put_key_list.append(put_key)
  85. # html替换为线上的地址
  86. online_image_url = "http://" + str(public_bucket) + str(addr) + "/" + str(put_key)
  87. # html = pat.sub(r'<img src={}'.format(online_image_url), str(html))
  88. online_image_url='<img src="{}'.format(online_image_url)
  89. online_image_url_list.append(online_image_url)
  90. local2online_dict = dict(zip(rawpic_list,online_image_url_list))
  91. return local2online_dict, put_key_list, localfile_list
  92. except:
  93. return return_error
  94. else:
  95. return return_error
  96. else:
  97. return local2online_dict, [], []
  98. def get_md5(image):
  99. """
  100. 由于hash不处理unicode编码的字符串(python3默认字符串是unicode)
  101. 所以这里判断是否字符串,如果是则进行转码
  102. 初始化md5、将image_name进行加密、然后返回加密字串
  103. """
  104. image_name, image_type = str(image).split(".")
  105. image_name = str(image_name) + str(time.time()) + str(random.random())
  106. if isinstance(image_name, str):
  107. image_name = image_name.encode("utf-8")
  108. md = hashlib.md5()
  109. md.update(image_name)
  110. # a = time.time()
  111. # b = random.random()
  112. return str(md.hexdigest()) + "." + str(image_type)