I have a Rails 4 application which uses token based authentication for APIs and need to be able to update records through Python 3 script.
My current script looks like this
import requests
import json
url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
payload = {'expt_name' : 'A60E001', 'status' : 'done' }
r = requests.patch(url, payload)
which works OK if I disable API authentication.
I can't figure out how to add headers to it, requests.patch
only takes two parameters according to docs.
I would need to get to the point where the following header info would added
'Authorization:Token token="xxxxxxxxxxxxxxxxxxxxxx"'
This type of header works OK in curl. How can I do this in Python 3 and requests?
patch takes kwargs, just pass headers = {your_header}:
def patch(url, data=None, **kwargs):
"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
So something like this:
head = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxxxxx"}
url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
payload = {'expt_name' : 'A60E001', 'status' : 'done' }
r = requests.patch(url, payload, headers=head)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With