Jira rest api get issue attachment via python - python-3.x

So, I need to download attachments to the issue in Jira using python. I have next code
from atlassian import Jira
issue = jira.issue(issuekey, fields='summary,comment,attachment')
for attachment in issue['fields']['attachment']:
with open((attachment.filename), 'wb') as file:
file.write(attachment.get(b'', b''))
After running the code I'm getting 3 empty files(txt, png, png) without any data inside..
How can I get(download) files from issue to my current folder?

Try using expand="attachment"
Ex:
issue = jira.issue(issuekey, expand="attachment")
for attachment in issue['fields']['attachment']:
with open(attachment.filename, 'wb') as file:
file.write(attachment.get())

You need the link to the contents of the attachment which is stored under the key 'content'. Then just use .get() request, that is in Jira library:
for attachment in issue['fields']['attachment']:
link = attachment['content']
link = link.split("https://jira.companyname.com/")[1]
b_str = jira.get(link, not_json_response=True)
with open((attachment['filename']), 'wb') as file:
file.write(b_str)
Notice that you need to trim the link, because jira.get() automatically includes the domain to the request url.

Get the attachment details:
get the jira attachment file URL
download the file using Request Module.
Check the file in file list.
issue = jira.issue(jira_ticket, expand='changelog')
attach = issue.fields.attachment
file_url = attach[0].content
file_path = "filename"
r = requests.get(file_url, auth=('jira_user', 'jira_pass'))
with open(file_path, 'wb') as f:
f.write(r.content)

Related

Trying to download a file from a link but failed (using python request)

I got a link that downloads a pdf file:
https://eclass.cccmyc.edu.hk/home/imail/downloadattachment.php?CampusMailID=441933&b_filename=TEkgSE8gWVVFTjREMTAucGRm
But instead of downloading the pdf, it redirects me to the login page of that platform. I am now trying to use python to login and download the file, here is my code:
import requests
url = "https://eclass.cccmyc.edu.hk/login.php"
download_url = "https://eclass.cccmyc.edu.hk/home/imail/downloadattachment.php?CampusMailID=441933&b_filename=TEkgSE8gWVVFTjREMTAucGRm"
data = {
"UserLogin": "myUsername",
"UserPassword": "secret"
}
r = requests.get(url, data=data)
I suppose I have logged in by now, so I download that file:
r = requests.get(download_url, allow_redirects=True)
open('my_pdf', 'wb').write(r.content)
Sadly, instead of downloading the pdf file, the program gives me some bunches of HTML codes. What should I do? I am pretty sure that I have made a big error in the program.
Thanks!
Here is a code snippet you can use and try.
with requests.get(download_url, allow_redirects=True, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
# If you have chunk encoded response uncomment if
# and set chunk_size parameter to None.
if chunk:
f.write(chunk)

How to send a pdf object from Databricks to Sharepoint?

INTRO: I have a Databricks notebook where I create a pdf file based on some data.
In order to generate the file I am using the fpdf library:
from fpdf import FPDF, HTMLMixin
Thanks to the library I generate a pdf file which is of type: <__main__.HTML2PDF at 0x7f3b73720fd0>.
My goal now is to send this pdf to a sharepoint folder. To do so I am using the following lines of code:
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
# paths
sharepoint_site = "MySharepointSite"
sharepoint_folder = "Shared Documents/General/PDFs/"
sharepoint_user = "aaa#bbb.onmicrosoft.com"
sharepoint_user_pw = "xyz"
sharepoint_folder = sharepoint_folder.strip("/")
# set environment variables
SITE_URL = f"https://sharepoint.com/sites/{sharepoint_site}"
RELATIVE_URL = f"/sites/{sharepoint_site}/{sharepoint_folder}"
# connect to sharepoint
ctx = ClientContext(SITE_URL).with_credentials(UserCredential(sharepoint_user, sharepoint_user_pw))
web = ctx.web
ctx.load(web).execute_query()
# Generate PDF
pdf = generate_pdf(ctx, row['ServerRelativeUrl'])
# HERE IS MY ISSUE!
ctx.web.get_folder_by_server_relative_url(sharepoint_folder).upload_file('test.pdf', pdf).execute_query()
PROBLEM: When I reach the last row I get the following error message:
TypeError: Object of type HTML2PDF is not JSON serializable
I believe that pdf objects cannot be serialized to be JSON and therefore I am stuck and I do not know how to send the PDF to the sharepoint.
QUESTION: Would you be able to suggest a smart and elegant way to achieve my goal i.e sending the pdf file to the sharepoint please?
I was able to solve this problem by saving the pdf as a string, then encoding it and finally pushing it to the sharepoint:
pdf_binary = pdf.output(dest='S').encode("latin1")
ctx.web.get_folder_by_server_relative_url(sharepoint_folder).upload_file("test.pdf", pdf_binary).execute_query()
Note: If it does not work, try to change the encoding type.

Is there a way to send a file using POST from a Python script, with specific name, that I can catch from api?

I want to use the requests package to make a post request, passing on a file with a specific name.
I already tried following, but it says "no file by name resume found":
with open('resume.pdf', 'rb') as f:
r = requests.post(url, files={'resume.pdf': f})
Below is the way I am trying to fetch file named resume in my API:
resume = request.files.get('resume')
Using the post request in postman with form-data as 'resume', type as file in dropdown, and then selecting file works fine though.
Try resume = request.files.get('resume.pdf'). File name includes extension.
Such view echoes file contents:
from flask import request
#app.route('/file', methods=['POST'])
def file_endpoint():
resume = request.files.get('resume.pdf')
return resume.read()

Getting the absolute filename of file uploaded through Python Flask App

I am trying to create a flask app that can be used to upload any user selected file to my azure storage. For some reason, the mime-type of the uploaded file is always set to 'application/octet-stream'. If I directly upload the file to azure using its UI, then the mime-type is correct. To solve this problem, I am trying to manually calculate the mimetype of the file and pass it as metadata.
The issue I am having is that I am not able to figure out a way to get the absolute filepath of the user selected file to be uploaded.
What I am looking for is the absolute path: path/to/file/doctest2.txt
Here is how the flask app looks like:
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
filename = secure_filename(file.filename)
fileextension = filename.rsplit('.',1)[1]
Randomfilename = id_generator()
filename = Randomfilename + '.' + fileextension
try:
blob_service.create_blob_from_stream(container, filename, file)
except Exception:
print 'Exception=' + Exception
pass
ref = 'http://'+ account + '.blob.core.windows.net/' + container + '/' + filename
seems like we can get the filename using f.filename, but I am not sure how to get the full path here.
Complete code can be found here:
https://github.com/codesagar/Azure-Blobs/blob/master/blob.py
The ultimate goal is to calculate the mimetype of the file to be uploaded.
I do have the file-blob(variable f). IS there a better way to get the mime from blob rather than hunting for the absolute file-path?
I solved my problem by using the following line of code:
mime_type = f.content_type
This gives me the mimetype of the file and eliminates the need for getting the file's absolute path.

Restructure data loaded from dropbox file in python

I am trying to download data from a CSV file stored in a dropbox folder. So far I do like this:
import dropbox
#Get access to my dropbox folder
dbx = dropbox.Dropbox('SOME_ACCESS_TOKEN')
dbx.users_get_current_account()
#Download file
metadata, res = dbx.files_download('/Test.csv')
#Get the file content
data=res.content
print(data)
data is of the this form: b'1,2,3,4,5\r\nA,B,C,D,E\r\n1,2,3,4,5\r\nA,B,C,D,E\r\n1,2,3,4,5\r\nA,B,C,D,E\r\n'
Is there an easy way to restructure this into a list of lists?
The solution to the above mentioned problem is:
import dropbox
#Connect to dropbox folder
dbx = dropbox.Dropbox('SOME_ACCESS_TOKEN')
dbx.users_get_current_account()
#Get metadata
metadata, res = dbx.files_download('/Test.txt')
#Get and decode data
data=res.content.decode('utf-8')
#Restructure data
lines = data.split('\r\n')
lines.pop()
print(lines)

Resources