[英]How can i DRY this pycode
我剛剛開始學習 python 我創建了這個 function 但正如你在“if”語句中看到的那樣,我復制了代碼我只將file_id = filename.photo[-1].file_id
為file_id = filename.video.file_id
使 function 工作並且它工作,但我怎樣才能縮短這個代碼
感謝您的時間
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
中,然后為其中的 rest 放入一個方法。
if filename.content_type == 'photo':
file_id = filename.photo[-1].file_id
elif filename.content_type == 'video':
file_id = filename.video.file_id
//call some method with file_id where you do the rest of the work.
somemeaningful_function_name(file_id)
def somemeaningful_function_name(file_id):
//work with file_id
你自己說過 DRY 原則。 當接近這樣的事情時,只需 go 即可找到重復部分。 作為一個經驗法則,如果您多次重用相同的代碼塊,只需將其放入 function 並使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.