Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

python - How to filter filenames with extension on API call?

I was working on the python confluence API for downloading attachment from confluence page, I need to download only files with .mpp extension. Tried with glob and direct parameters but didnt work.

Here is my code:

file_name = glob.glob("*.mpp")
attachments_container = confluence.get_attachments_from_content(page_id=33110, start=0, limit=1,filename=file_name)
print(attachments_container)
attachments = attachments_container['results']
for attachment in attachments:
    fname = attachment['title']
    download_link = confluence.url + attachment['_links']['download']
    r = requests.get(download_link, auth = HTTPBasicAuth(confluence.username,confluence.password))
    if r.status_code == 200:
        if not os.path.exists('phoenix'):
            os.makedirs('phoenix')
        fname = ".\phoenix\" +fname
question from:https://stackoverflow.com/questions/65859124/how-to-filter-filenames-with-extension-on-api-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

glob.glob() operates on your local folder. So you can't use that as a filter for get_attachments_from_content(). Also, don't specify a limit of since that gets you just one/the first attachment. Specify a high limit or whatever default will include all of them. (You may have to paginate results.)

However, you can exclude the files you don't want by checking the title of each attachment before you download it, which you have as fname = attachment['title'].

attachments_container = confluence.get_attachments_from_content(page_id=33110, limit=1000)
attachments = attachments_container['results']
for attachment in attachments:
    fname = attachment['title']
    if not fname.lower().endswith('.mpp'):
        # skip file if it's not got that extension
        continue
    download_link = ...
    # rest of your code here

Also, your code looks like a copy-paste from this answer but you've changed the actual "downloading" part of it. So if your next StackOverflow question is going to be "how to download a file from confluence", use that answer's code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...