You are not logged in.

Announcement

 Téléchargez la dernière version stable de GLPI      -     Et vous, que pouvez vous faire pour le projet GLPI ? :  Contribuer
 Download last stable version of GLPI                      -     What can you do for GLPI ? :  Contribute

#1 2021-09-10 18:08:04

MichaelJ
Member
Registered: 2021-08-11
Posts: 7

Using python-requests to upload documents

In the API documentation there is an example (using curl) that shows how to upload a document into GLPI.
Has anyone managed to 'convert' that to work in python-requests?

Offline

#2 2021-09-15 18:42:33

MichaelJ
Member
Registered: 2021-08-11
Posts: 7

Re: Using python-requests to upload documents

I gave up on trying to get it to work with python-requests but I did manage to get it working using PycURL.
The code looks like this:

responseBuffer = BytesIO()
uploadDocument = pycurl.Curl()
# uploadDocument.setopt(uploadDocument.VERBOSE, 2)
uploadDocument.setopt(uploadDocument.URL, BASE_URL + '/Document')
uploadDocument.setopt(uploadDocument.HTTPHEADER, ['Content-Type: multipart/form-data', 'Session-Token: ' + SESSION_TOKEN, 'App-Token: ' + APP_TOKEN, 'Accept: application/json'])
uploadDocument.setopt(uploadDocument.POST, 1)
uploadDocument.setopt(uploadDocument.WRITEDATA, responseBuffer)
ULM = "{\"input\": {\"name\": \"Uploaded document\", \"_filename\" : [\"file.txt\"]}}"
uploadDocument.setopt(uploadDocument.HTTPPOST, [
    ("uploadManifest", (uploadDocument.FORM_BUFFERPTR, ULM, uploadDocument.FORM_CONTENTTYPE, 'application/json')),
    ("filename[0]", (uploadDocument.FORM_FILE, "file.txt"))])
uploadDocument.perform()
uploadDocument.close()

My question now is, does the API allow using PUT to replace an existing document?
If it does, examples would be welcome.

Offline

#3 2024-10-17 10:41:59

rcgjoxph
Member
Registered: 2024-07-19
Posts: 7

Re: Using python-requests to upload documents

This worked for me, where png is a file-like object which has had .seek(0) called on it.
I'm not clear how to set the MIME type explicitly, it's inferred from the filename here.

imginfo = requests.post(
        'http://localhost:8181/apirest.php/Document/',
        headers = {"Session-Token": session_token, "App-Token":GLPI_APP_TOKEN},
        data = {'uploadManifest':'{"input": {"name": "Uploaded document", "_filename" : ["test.png"]} }' },
        files = { 'test.png' : png }
)

# Get the id after creation
imginfo = json.loads(imginfo.content.decode('utf8'))
imgurl = f"http://localhost:8181/front/document.send.php?docid={imginfo['id']}"

Offline

Board footer

Powered by FluxBB