Article directory
Foreword:
Because I need to access pictures when writing interface recently, I find it inconvenient to save the pictures locally, so I thought about uploading the pictures to the Internet and accessing them through the link, so I came up with this article
Sign up and create a space:
Register on the official website of Qiniu Cloud
and perform real-name authentication
to create a space, which can be used for free for 30 days:
remember this external domain name, you need this domain name to access pictures
Click the personal center in the upper right corner to get AK, SK
Code call:
We can directly use the pip command to download Qiniu Cloud's SDK.
pip install qiniu
import uuid
from qiniu import Auth, put_file
class Uploadimg:
#初始化
def __init__(self,ak='填入第一步中的AK',sk='填入第一步中的SK') -> None:
self.access_key = ak
self.secret_key = sk
#请求token
def __qiniu_token(self,bucked_name, key):
q = Auth(access_key=self.access_key,
secret_key=self.secret_key)
token = q.upload_token(bucked_name, key)
return token
#上传图片并返回图片的链接
def upload_img(self,file_path,bucked_name,domain_name):
"""
file_path:上传的图片本机地址
bucked_name:第一步自己创建的空间
domain_name:第一步中的外域链接
"""
file_name = '{}.png'.format(uuid.uuid4()) #上传后的图片的保存名
token = self.__qiniu_token(bucked_name, file_name) #获取token,上传到指定的空间
ans,_ = put_file(token, file_name, file_path)
img_key = ans.get('key') #获取返回值中的图片地址
return 'http://%s/%s'%(domain_name,img_key) #返回完整的图片链接
if __name__ == '__main__':
up = Uploadimg('ak','sk')
try:
url = up.upload_img('本机图片','空间名','域名')
print(url)
except Exception as e:
print(e)
Result:
The output value here is a link to a picture. Visit this link to see the selfie I just uploaded