文章目录

目前需要把一些图片上传到图床进行托管,看了一圈,感觉聚合类的图床很不错,而且很多也包含了我之前用过的imgur这类非常稳定的图床资源。

最后选择了 遇见图床 ,感觉挺正规的,自称2018年就开始运营,而且强制开启鉴黄接口,保证了干净整洁,不容易被封。

选择它也是因为api比较完善。我这次只会用到图片上传,参看 遇见图床api文档

之所以会写这一篇,是因为遇见图床的api必须使用表单的文件类型上传图片,于是又学习了一下。

其中关键代码如下:

1
2
3
4
imgOpen = open(localImg, 'rb')
files = {'image': imgOpen}
r = requests.post(hualigs_url, data={'apiType': hualigs_api_type, 'privateStorage': '', 'token': hualigs_token}, files=files)
imgOpen.close()

这里面重点就是file需要读取二进制文件,而不能直接填入文件名。同时,图床文档里明确了图片的字段为image,因此不能随便写个file之类的上去。

然后根据文档中的响应解释,构造对响应的解析。

1
2
3
4
5
6
7
8
9
10
11
12
13
try:
respJson = r.json()
except json.decoder.JSONDecodeError as e:
logger.exception("接口解析错误:"+str(e)+"\n返回信息:"+r.text)
return src_url
except Exception as e:
logger.exception("未知的接口调用错误:"+str(e))
return src_url
urls = {}
if str(respJson['code']).strip() == '200' and str(respJson['msg']).strip() == 'success':
urls = respJson['data']['url']
else:
return False

最后贴上整个方法的全部代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def dealImage(src_url):
a = urlparse(src_url)
file_name = os.path.basename(a.path)
if not os.path.exists("tmp"):
os.mkdir("tmp")
if not os.path.exists("tmp/images"):
os.mkdir("tmp/images")
img_path = 'tmp/images/'+file_name
if not os.path.exists(img_path):
tmp = requests.get(src_url, headers=getRandomUA(), timeout=2)
with open(img_path, 'wb') as f:
f.write(tmp.content)
logger.info('Uploading 2 imgur: '+img_path)
imgOpen = open(img_path, 'rb')
files = {'image': imgOpen}
r = requests.post(hualigs_url, data={'apiType': hualigs_api_type, 'privateStorage': '', 'token': hualigs_token}, files=files)
imgOpen.close()
try:
respJson = r.json()
except json.decoder.JSONDecodeError as e:
logger.exception("接口解析错误:"+str(e)+"\n返回信息:"+r.text)
return src_url
except Exception as e:
logger.exception("未知的接口调用错误:"+str(e))
return src_url
urls = {}
if str(respJson['code']).strip() == '200' and str(respJson['msg']).strip() == 'success':
urls = respJson['data']['url']
else:
return False
if urls["distribute"]:
logger.info('[url]'+src_url+' uploaded! [new url]'+urls["distribute"])
if os.path.exists(img_path):
os.remove(img_path)
return urls["distribute"]
if hualigs_api_type in urls:
logger.info('[url]'+src_url+' uploaded! [new url]'+urls[hualigs_api_type])
if os.path.exists(img_path):
os.remove(img_path)
return urls[hualigs_api_type]
return src_url

以上内容主要参考了 魔芋红茶 / markdown-img

♦ 本文固定连接:https://www.gsgundam.com/2022/2022-11-24-python-upload-image-to-hualigs/

♦ 转载请注明:GSGundam 2022年11月24日发布于 GSGUNDAM砍柴工

♦ 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

♦ 原创不易,如果页面上有适合你的广告,不妨点击一下看看,支持作者。(广告来源:Google Adsense)

♦ 本文总阅读量