我如何干燥此pycode

问题描述 投票:0回答:1

我刚刚开始学习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()
python python-3.x telegram-bot dry python-telegram-bot
1个回答
0
投票

一旦获得file_id = filename.photo[-1].file_id,从那里开始基本上就是完全相同的处理。因此,只需将此行放入if else中,然后为其余部分放入一个方法。

© www.soinside.com 2019 - 2024. All rights reserved.