简体   繁体   中英

convert curl post to rest api to python

I have this curl command:

curl -X POST -s -k -u "admin:Password" -d '

{
"add_content": {
    "errata_ids": ["RHSA-2016:2124","RHBA-2016:2889"]
},
"content_view_version_environments": [{
    "content_view_version_id": 28
}]
}
' \

-H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ https://satellite.example.com/katello/api/content_view_versions/incremental_update

I need to convert it to python

this is what I have got so far:

def post_json(location, json_data):


result = requests.post(
    location,
    data=json_data,
    auth=(USERNAME, PASSWORD),
    verify=SSL_VERIFY,
    headers=POST_HEADERS)

return result.json()

json_data = {
    "add_content": {
        "errata_ids": ["RHSA-2016:2124","RHBA-2016:2889"]
    },
    "content_view_version_environments": [{
        "content_view_version_id": 301
    }]
}

push_errata = post_json(katello_api + "content_view_versions + "/incremental_update/" + "content_view_version_environments/" + "add_content['RHSA-2016:1912'])

I am getting SyntaxError: invalid syntax

can you please help me to "convert" the curl command to python properly ?

With Authorization header, you can do:

import requests, base64, json

url = 'https://satellite.example.com/katello/api/content_view_versions/incremental_update'

headers = {
    'Accept': 'application/json,version=2',
    'Content-Type': 'application/json',
    'Authorization': 'Basic {}'.format(base64.b64encode('admin:Password'))}

data = {
    "add_content": {
        "errata_ids": ["RHSA-2016:2124","RHBA-2016:2889"]},
    "content_view_version_environments": [
        {"content_view_version_id": 28 }]}

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

You can also use auth param without Authorization header like this

from requests.auth import HTTPBasicAuth

headers = {
    'Accept': 'application/json,version=2',
    'Content-Type': 'application/json'}

response = requests.post(url, auth=HTTPBasicAuth('admin', 'Password'), data=json.dumps(data), headers=headers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM