Search code examples
pythonparameterspycurl

Custom pycurl call


I'm trying to implement push notifications. I can trigger notifications with this call that I need to make from python:

curl -X POST -H "Content-Type: application/json" -H "X-Thunder-Secret-Key: secret2" --data-ascii "\"Hello World\"" http://localhost:8001/api/1.0.0/key2/channels/mychannel/

This works ok from the command line.

First I tried using the subprocess, but it gave me this strange error:

curl: (1) Protocol "http not supported or disabled in libcurl

So I gave up on that and I'm trying to use pycurl. But the problem is that I don't know what to do with -X and with --data-ascii options.

import pycurl
c = pycurl.Curl()
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','X-Thunder-Secret-Key: secret2'])
c.setopt(c.URL, 'http://localhost:8001/api/1.0.0/key2/channels/mychannel/')
c.perform()
print("Done")

So how do I add -X option and how do I send the text message with the request?


Solution

  • If you need to do HTTP POST request, see documentation example.

    I think something like this should work (I've used python 2):

    import pycurl    
    
    c = pycurl.Curl()
    
    postfields = '"Hello World"'
    c.setopt(c.URL, 'http://pycurl.sourceforge.net/tests/testpostvars.php')
    c.setopt(c.HTTPHEADER, ['Content-Type: application/json','X-Thunder-Secret-Key: secret2'])
    # Here we set data for POST request
    c.setopt(c.POSTFIELDS, postfields)
    
    c.perform()
    c.close()
    

    This code produces following HTTP packet:

    POST /tests/testpostvars.php HTTP/1.1
    User-Agent: PycURL/7.19.5.1 libcurl/7.37.1 SecureTransport zlib/1.2.5
    Host: pycurl.sourceforge.net
    Accept: */*
    Content-Type: application/json
    X-Thunder-Secret-Key: secret2
    Content-Length: 13
    
    "Hello World"