我怎么能干这个pycode

How can i DRY this pycode

刚开始学习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 中,其余的则放入一个方法。

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原则。当接近这样的事情时,只需去寻找重复的部分。作为一个经验法则,如果您多次重复使用相同的代码块,只需将它放在一个函数中并使用它。