[rt-users] Downloading attachments via REST

Thomas Oddsund thomas.oddsund at usit.uio.no
Wed Oct 12 15:14:41 EDT 2016


Hello,

I am currently in the process of writing a script for simple transferring of tickets from one instance to another. Both instances run 4.2.8, and I'm using Python for the script. Unfortunately, I have met a problem when it comes to attachments.

The script uses the requests-library, and rt_get is just a wrapper around the session.get() function.

Text files seem fine, but other files(i.e. pdf) aren't stored correctly.

>From what I've gathered, even though the Content-Transfer-Encoding says base64, this is not the case, as base64.decoding outputs a 98 byte file. It's not correct to output it as utf-8 encoded either, because that gives a file of 475957 bytes. The original file is 236633 bytes. Also, decoding/encoding the string buffer as Latin-1 throws an error.

Have anyone done this before?
Is the problem that the pdf file has some other encoding then UTF-8/Latin-1? Will this be different from all files?
Are there any ways to just treat the content-response as bits and bytes, and write them directly to a file?

A simple example of the code can be seen below, and all kinds of decode/encode attempts have been resultless.
#!/usr/bin/env python2

from __future__ import print_function
import requests
import getpass
import re
import base64
from rtrequestlib import rt_get, rt_post

# Fix Python 2.x.
try:
    input = raw_input
except NameError:
    pass

fromSess = requests.Session()
fromBase = "https://rt.uio.no/REST/1.0/"

username = input("Username: ")
password = getpass.getpass()

payload = {"user": username, "pass": password}

loginS = rt_post(fromSess, fromBase, "", payload)

attHead = rt_get(fromSess, fromBase, "ticket/2305592/attachments/26780830/content") # PDF attachment to a ticket

# Remove REST-response and last three newlines
pdfFile = attHead.text[17:-3]

with open("test1.pdf", "wb") as f:
    f.write(pdfFile.encode("utf-8"))

# only 98 bytes
with open("test64.pdf", "wb") as f:
    f.write(base64.decodestring(pdfFile.encode("utf-8")))

with open("test2.pdf", "wb") as f:
    f.write(pdfFile.encode("iso-8859-1")) # THROWS UnicodeEncodeError


Med vennlig hilsen,
Thomas Oddsund
SDS/USIT



More information about the rt-users mailing list