main.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # coding=utf-8
  2. import flask
  3. import imgkit
  4. import json
  5. import os
  6. import oss2
  7. import random
  8. from flask import request
  9. # 创建一个服务,把当前这个python文件当做一个服务
  10. server = flask.Flask(__name__)
  11. # 端口配置
  12. port = 5008
  13. host = '127.0.0.1'
  14. debug = True
  15. # 工具配置
  16. tool_path = r'/usr/local/bin/wkhtmltoimage'
  17. # tool_path = r'E:\wkhtmltopdf\bin\wkhtmltoimage.exe'
  18. # OSS配置
  19. oss_end_point = 'oss-cn-shanghai.aliyuncs.com'
  20. oss_bucket = 'hzchart'
  21. oss_key_id = 'LTAIFMZYQhS2BTvW'
  22. oss_key_secret = '12kk1ptCHoGWedhBnKRVW5hRJzq9Fq'
  23. resource_host = 'https://hzstatic.hzinsights.com/'
  24. # server.config['JSON_AS_ASCII'] = False
  25. # @server.route()可以将普通函数转变为服务 登录接口的路径、请求方式
  26. @server.route('/htm2img', methods=['post'])
  27. def htm2img():
  28. # 获取参数
  29. req_data = request.get_json()
  30. if req_data is None:
  31. return json.dumps({'code': 5004, 'msg': '参数有误', 'data': ''}, ensure_ascii=False)
  32. # 参数校验
  33. contents = req_data['html_content']
  34. if contents is None or contents == '':
  35. return json.dumps({'code': 5004, 'msg': '获取html文本内容失败', 'data': ''}, ensure_ascii=False)
  36. width = req_data['width']
  37. if width <= 0:
  38. return json.dumps({'code': 5004, 'msg': '图片宽度有误', 'data': ''}, ensure_ascii=False)
  39. height = req_data['height']
  40. if height <= 0:
  41. return json.dumps({'code': 5004, 'msg': '图片长度有误', 'data': ''}, ensure_ascii=False)
  42. # 生成html文件
  43. rand_name = get_rand_string()
  44. html_path = 'html/' + rand_name + '.html'
  45. res = html2file(contents, html_path)
  46. if not res:
  47. return json.dumps({'code': 5004, 'msg': '生成html失败', 'data': ''}, ensure_ascii=False)
  48. # html转图片
  49. img_name = rand_name + '.jpg'
  50. img_path = html_to_img(html_path, img_name, width, height)
  51. if img_path == '':
  52. return json.dumps({'code': 400, 'msg': '生成图片失败', 'data': ''}, ensure_ascii=False)
  53. # 上传OSS
  54. upload_dir = 'static/images/yb/htm2img/'
  55. save_path = upload_dir + img_name
  56. upload_res = upload_oss_file(save_path, img_path)
  57. # 清除本地生成的html及图片
  58. clear_local_file(img_path, html_path)
  59. if upload_res.status == 200:
  60. resource_url = resource_host + save_path
  61. return json.dumps({'code': 200, 'msg': '生成图片成功', 'data': resource_url}, ensure_ascii=False)
  62. else:
  63. return json.dumps({'code': 400, 'msg': '生成图片失败', 'data': ''}, ensure_ascii=False)
  64. # html文件转为图片
  65. def html_to_img(html_url, img_name, width=100, height=100):
  66. path_wkimg = tool_path # 工具路径
  67. cfg = imgkit.config(wkhtmltoimage=path_wkimg)
  68. opt = {"width": width, "height": height, "quality": 100, "format": "jpg"}
  69. img_path = 'img/' + img_name
  70. imgkit.from_file(html_url, img_path, config=cfg, options=opt)
  71. try:
  72. os.path.isfile(img_path)
  73. return img_path
  74. except Exception as e:
  75. # print(e)
  76. return ''
  77. # 上传图片至OSS
  78. def upload_oss_file(save_path, file_path):
  79. auth = oss2.Auth(oss_key_id, oss_key_secret)
  80. bucket = oss2.Bucket(auth, oss_end_point, oss_bucket)
  81. return bucket.put_object_from_file(save_path, file_path)
  82. # 生成指定长度的随机字符串
  83. def get_rand_string(size=28):
  84. random_str = ''
  85. base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
  86. length = len(base_str) - 1
  87. for i in range(size):
  88. random_str += base_str[random.randint(0, length)]
  89. return random_str
  90. # 清除本地生成的文件
  91. def clear_local_file(img_path, html_path):
  92. try:
  93. os.remove(img_path)
  94. os.remove(html_path)
  95. return True
  96. except OSError as e:
  97. # print(e)
  98. return False
  99. # html文本生成文件
  100. def html2file(content, file_path):
  101. try:
  102. f = open(file_path, 'w', encoding='UTF-8')
  103. f.write(content)
  104. f.close()
  105. return True
  106. except Exception as e:
  107. # print(e)
  108. return False
  109. if __name__ == '__main__':
  110. server.run(debug=debug, port=port, host=host)