2

Python : curl command option with -d to python

I have the following curl bash script that returns multiple lines in terminal.

curl 'http://localhost/_search?pretty' -d '
{
  "query" :{ 
    "range" : {
      "created_at" : {
        "gte": "now-2h",
        "lte": "now"
      }
    }
  }
}'

I want to run this bash script or curl command in python and receive the output in python. What should I do? requests does not seem to support options for curl command.

  • Do you just want to call `curl` as an external program? – hlt Aug 19 '14 at 23:27
  • See also [Calling an external command in Python](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – hlt Aug 19 '14 at 23:27
  • No I want to call inside script that I can edit the command –  Aug 19 '14 at 23:34
  • What do you mean by *"edit the command"*? – hlt Aug 19 '14 at 23:35
  • 2
    See also [Convert post request performed by curl to python request based on requests module](https://stackoverflow.com/questions/15009332/convert-post-request-performed-by-curl-to-python-request-based-on-requests-modul) – hlt Aug 19 '14 at 23:36

1 Answers1

1

As I have understand, you want to send JSON in post-data with Python. In requests you can do it like this:

import requests, json

data =  {
   "query": { 
    "range" : {
      "created_at" : {
        "gte": "now-2h",
        "lte": "now"
      }
    }
  }
}

url = "http://localhost/_search?pretty"

response = requests.post(url, data = json.dumps(data))

Requesting ElasticSearch in python was discussed here.

Community
  • 1
  • 1
uhbif19
  • 3,139
  • 3
  • 26
  • 48