How to send POST request after form submit 302 in Django? - python-3.x

I have an implementation as follows:
There is a payment form wherein user fills all the details.(API1), here I'm getting an error 302:
On submit of that form one of the function in my views is called.
In the backend implementation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)
But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request.
Following is the code.
views.py -->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
content = response.url
return_config = {
"type": "content",
"content": redirect(content)
}
return return_config
How do I send the 2nd request(API2) as POST request along with all parameters? What am I doing wrong here?
Thank you for your suggestions.

If the requests returns a 302 status, the new url is available in response.headers['Location']. You can keep following the new url, till you end up with a valid response.
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
while response.status_code == 302:
response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)
content = response.text
return_config = {
"type": "content",
"content": content
}
return return_config

# here you are assigning the post url to content ie. 'https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****'
content = response.url
return_config = {
"type": "content",
"content": redirect(content) # calling redirect with the response.url
}
change to:
# check status code for response
print(response)
content = response.json() # if response is of json in format
content = response.text # if response is of plain text
return_config = {
"type": "content",
"content": content
}
return return_config
request.post() returns requests.Response object. inorder to get the response data you need to access it using .text or .json() depending on the format in which the response is sent.

Related

How to resolve 400 Client Error when mapping uniprot IDs programatically?

Here's the code:
API_URL = "https://rest.uniprot.org"
def submit_id_mapping(from_db, to_db, ids):
request = requests.get(
f"{API_URL}/idmapping/run",
data={"from": from_db, "to": to_db, "ids": ",".join(ids)},
)
#request.raise_for_status()
return request.json()
submit_id_mapping(from_db="UniProtKB_AC-ID", to_db="ChEMBL", ids=["P05067", "P12345"])
Taken directly from the official example
And returning the following 404 client error. I tried accessing the url myself and it doesn't seem to work. Given that this is the official documentation I don't really know what to do. Any suggestions are welcomed.
{'url': 'http://rest.uniprot.org/idmapping/run',
'messages': ['Internal server error']}
I also have another script for this but it no longer works! And I don't know why :(
in_f = open("filename")
url = 'https://www.uniprot.org/uploadlists/'
ids=in_f.read().splitlines()
ids_s=" ".join(ids)
params = {
'from': 'PDB_ID',
'to': 'ACC',
'format': 'tab',
'query': ids_s
}
data = urllib.parse.urlencode(params)
data = data.encode('utf-8')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as f:
response = f.read()
print(response.decode('utf-8'))
Error:
urllib.error.HTTPError: HTTP Error 405: Not Allowed
Try to change .get to .post:
import requests
API_URL = "https://rest.uniprot.org"
def submit_id_mapping(from_db, to_db, ids):
data = {"from": from_db, "to": to_db, "ids": ids}
request = requests.post(f"{API_URL}/idmapping/run", data=data)
return request.json()
result = submit_id_mapping(
from_db="UniProtKB_AC-ID", to_db="ChEMBL", ids=["P05067", "P12345"]
)
print(result)
Prints:
{'jobId': 'da05fa39cf0fc3fb3ea1c4718ba094b8ddb64461'}

How to read the status from a response in python when a call to an api is made

I'm using urllib3 in python like this
urllib3.disable_warnings()
https = urllib3.PoolManager(cert_reqs=ssl.CERT_NONE)
I am calling an api like this
a = {"name": joy.txt, "parent":{"id": 4567}}
resp = https.request(method='POST',
url = https://zoola.com/content,
headers=headers,
fields = {
"attributes": json.dumps(a),
"file": (joy.txt, file),
"filename": joy.txt
}
)
I am getting my response like this
myresponse = resp.data.decode('UTF-8')
I need to be able to test a status of the response like this
if resp.status == "201":
#Do something
This gives me an internal server error. How can I read the status? resp does not have a status property

Create variable string for request API payload

I have a list of URLs that all refer to images. I want to loop through the list and call a face recognition API that accepts these URLs. To call the API, I need to provide the payload dictionary. However, the example code from the API requires the following form for the payload dictionary:
payload = "{\"url\":\"https://inferdo.com/img/face-3.jpg\",\"accuracy_boost\":3}"
The URL in this example payload dictionary would look like this in my list:
list_of_urls = ["https://inferdo.com/img/face-3.jpg", ...]
How can I insert the entries of my list into the payload dictionary with a for loop?
I tried to use a "regular" payload dictionary, but it did not work:
for url_path in list_of_urls:
payload = {'url' : url_path,'accuracy_boost':3}
I went to the API documentation and found you need to send the payload as JSON. Something like this will do the job:
import requests
import json
endpoints = {
'face': 'https://face-detection6.p.rapidapi.com/img/face'
'face_age_gender': 'https://face-detection6.p.rapidapi.com/img/face-age-gender'
}
urls = [
'https://inferdo.com/img/face-3.jpg'
]
headers = {
'x-rapidapi-host': 'face-detection6.p.rapidapi.com',
'x-rapidapi-key': 'YOUR-API-KEY',
'content-type': 'application/json',
'accept': 'application/json'
}
for url in urls:
payload = {
'url': url,
'accuracy_boost': 3
}
r = requests.post(
endpoints.get('face'), # or endpoint.get('face_age_gender')
data=json.dumps(payload),
headers=headers
)
if r.ok:
# do something with r.content or r.json()
I hope it helps.

How do i post python varaibles using curl?

for instance i have the following
title = "some title"
name = "name"
headers = {
'Content-Type': 'application/json',
}
data = '{"title": title,"name":name,"action":"save"}'
response = requests.post('http://192.168.1.7:8080/news/save.json', headers=headers, data=data)
i want to post the title and the name to a database with those fields, and they both will keep on changing .
I execute this statement and it works without any errors, but when i see my database, these fields arent there yet.
If i hardcode the title and the name then it works fine.
Not sure what does this have to do with curl
You are sending an hardcoded string that has nothing to do with the defined variables. You should create a json and send that:
import json
title = "some title"
name = "name"
headers = {
'Content-Type': 'application/json',
}
data = json.dumps({"title": title, "name": name, "action":"save"})
response = requests.post('http://192.168.1.7:8080/news/save.json',
headers=headers, data=data)

Get Survey Response Survey Monkey (Python)

Im quite new to http request. Im having abit of troubleshooting trying to get survey results/responses from survey monkey api 3.
Here is the following code i have:
import requests
import json
client = requests.session()
headers = {
"Authorization": "bearer %s" % "VVZEO3u35o3JVDdd8z5Qhl-eRR5Er2igaV1gf8GS4dvRfYVk3SWu9nHginwyNnU.tAHEr-AtikR9Zpg7vL3-jIg3-6yuQkPBvVIw0AkpYN5807SCLIrGojsii3ihdGV-",
"Content-Type": "application/json"
}
data = {}
HOST = "https://api.surveymonkey.net"
#SURVEY_LIST_ENDPOINT = "/v3/surveys/%s/responses/%s/details" %("85160626","161")
SURVEY_LIST_ENDPOINT = "/v3/surveys/85160626/responses"
uri = "%s%s" % (HOST, SURVEY_LIST_ENDPOINT)
response = client.post(uri, headers=headers, data=json.dumps(data))
response_json = response.json()
#survey_list = response_json["data"]["surveys"]
print(response_json)
I keep getting error:
{'error': {'docs': 'https://developer.surveymonkey.com/api/v3/#error-codes', 'message': 'There was an error retrieving the requested resource.', 'id': '1020', 'name': 'Resource Not Found', 'http_status_code': 404}}
Any help is much appreciated, thanks,
Pon
If you're trying to fetch data, then you should be doing a GET request, not a post.
response = client.get(uri, headers=headers)
Otherwise it looks fine, just make sure the Survey ID is correct.

Resources