我刚刚开始学习python我创建了此函数,但是正如您在“ if”语句中看到的那样,我已经复制了代码我只将file_id = filename.photo[-1].file_id
更改为file_id = filename.video.file_id
使该功能正常工作,但是如何缩短此代码]
谢谢您的时间
def create_post(filename):
if filename.content_type == 'photo':
file_id = filename.photo[-1].file_id
file = bot.get_file(file_id)
downloaded_file = bot.download_file(file.file_path)
with open("image.jpg", 'wb') as new_file:
new_file.write(downloaded_file)
image = 'image.jpg'
token = store_file_temporary(image)
headers = {
"content-type": "multipart/form-data",
"Accept": "application/json",
"Content-Type": "application/json"
}
filesd = {
"title": randomString(),
"safety": 'safe',
"contentToken": token
}
r = requests.post(url=url + "/posts/", json=filesd, auth=(username, password),
headers=headers)
print(r.json())
return r.json()
elif filename.content_type == 'video':
file_id = filename.video.file_id
file = bot.get_file(file_id)
downloaded_file = bot.download_file(file.file_path)
with open("image.jpg", 'wb') as new_file:
new_file.write(downloaded_file)
image = 'image.jpg'
token = store_file_temporary(image)
headers = {
"content-type": "multipart/form-data",
"Accept": "application/json",
"Content-Type": "application/json"
}
filesd = {
"title": randomString(),
"safety": 'safe',
"contentToken": token
}
r = requests.post(url=url + "/posts/", json=filesd, auth=(username, password),
headers=headers)
print(r.json())
return r.json()
一旦获得file_id = filename.photo[-1].file_id
,从那里开始基本上就是完全相同的处理。因此,只需将此行放入if else
中,然后为其余部分放入一个方法。