<Response [500]> while POST request - python-3.x

Trying to get information with post request but it returns RESPONSE [500]. I have tried to use the get response and it returns response 200 code. I copied the form_data from the website and included in my code.
import requests, json
from bs4 import BeautifulSoup as bs
from requests.utils import quote
url = 'https://mpcr.cbar.az/service/mpcr.publicSearchApplication'
tax_ids = [
'1000276532',
]
data = {
'searchFilter': {"fields":"{\"orgTin\":\"%s\"}"},
'compId': 'frontend',
'access_token': '123',
'refresh_token': '123',
'token': '123',
'requestNumber': '1p5i9m5s9T9W8',
'_token': 'MQ2cZyD092qFKknKpZMV0w2ksNhqWj17PSl6iaCG',
}
with requests.Session() as s:
for i in tax_ids:
data["searchFilter"] = quote(json.dumps(data["searchFilter"]["fields"] % i))
print(data)
print("--" * 10)
r = s.post(url, data=data)
print(r)

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'}

Make multipart/form-data post requests with python

Im trying To Make post requests (multipart/form-data) in this website https://gofile.io/?t=api
every time time i got an error when i try to upload file
my code
import requests
req = requests.session()
files= {'file': open("test.txt", 'rb')}
response = req.post('https://srv-file7.gofile.io/upload', files=files)
print(response.text)
I got error every time ,are smething missing in the code
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import json
mp_encoder = MultipartEncoder(
fields={
'filesUploaded': ('file_name.txt', open('file_name.txt', 'rb'))
}
)
r = requests.post(
'https://srv-file9.gofile.io/upload',
data=mp_encoder,
headers={'Content-Type': mp_encoder.content_type}
)
scrap = r.json()
# send "Token file" 123Abc
Token = scrap['data']['code']
Check this. It will work.

Can't send proper post request with file using python3 requests

I was using Postman to send post request like on the screenshot
Now I need to implement it in python. This is what i've got for now:
import requests
data = {"sendRequest": {"apiKey": 12345, "field1": "field1value"}}
files = {"attachment": ("file.txt", open("file.txt", "rb"))}
headers = {"Content-type": "multipart/form-data"}
response = requests.post(endpoint, data=data, headers=headers, files=files)
But still it's not working - server doesn't accept it as valid request. I've tried more combinations but without any results and I really couldn't find a solution.
I need this request to be exactly like that one in postman
I finally found a solution. I used MultipartEncoder from requests_toolbelt library.
from requests_toolbelt import MultipartEncoder
import requests
import json
data = {"apiKey": 12345, "field1": "field1value"}}
mp = MultipartEncoder(
fields={
'sendRequest': json.dumps(data), # it is important to convert dict into json
'attachment': ('file.pdf', open('file.pdf', 'rb'), 'multipart/form-data'),
}
)
r = requests.post(ENDPOINT, data=mp, headers={'Content-Type': mp.content_type})

get a reuse the token for the Huawei modem E3372h

so i want to read some sms received in my huawei modem.
For that i m tryin to first get the token and session id from the 'http://192.168.8.1/api/webserver/SesTokInfo page
then try to reuse this token in the page http://192.168.8.1/api/sms/sms-list
but i got this error
<error>
<code>125002</code>
<message></message>
</error>
which mean that i don t have the right token value, what i m wondering about.
so this is how my code looks
import hashlib
import base64
import binascii
import xml.etree.ElementTree as ET
from datetime import datetime
import requests
from bs4 import BeautifulSoup
BASEURL = 'http://192.168.8.1'
session = requests.Session()
reqresponse = session.get(BASEURL + '/api/webserver/SesTokInfo')
if reqresponse.status_code == 200:
root = ET.fromstring(reqresponse.text)
for results in root.iter('SesInfo'):
sessionid = results.text
print("the sessionId is", sessionid)
for results in root.iter('TokInfo'):
token = results.text
print("The token is", token)
sessioncookies = reqresponse.cookies
post_data = '<?xml version = "1.0" encoding = "UTF-8"?>\n'
post_data += '<request><PageIndex>1</PageIndex><ReadCount>3</ReadCount><BoxType>1</BoxType><SortTyp$
headers = {'Content-Type': 'text/xml; charset=UTF-8',
'__RequestVerificationToken': token
}
api_url = BASEURL + '/api/sms/sms-list'
logonresponse = session.post( api_url, data=post_data, headers=headers, cookies=sessioncookies)
logonresponse2 = session.get( api_url, data=post_data, headers=headers, cookies=sessioncookies)
result = BeautifulSoup(logonresponse.text, 'html.parser')
for r in result:
print(r)
can someone helo me with the troubleshooting please?

Requests for Poloniex API

I trying work with Poloniex API. And I try get balances via Trading API methods. And I try do it with requests library like this:
import requests
import hmac
import hashlib
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post('https://poloniex.com/tradingApi', data=post_data, headers=headers, timeout=20)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
With this code I always get error with message: "Request: {'error': 'Invalid command.'}". What I do wrong?
From other side code below returns data without any problem! Look at this, please:
import requests
import hmac
import hashlib
import json
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
req = urllib.request.Request('https://poloniex.com/tradingApi', data=post_data, headers=headers)
res = urllib.request.urlopen(req, timeout=20)
Ret_data = json.loads(res.read().decode('utf-8'))
print('Request: {0}'.format(Ret_data))
return Ret_data
I using Python 3.6
It's best to let requests handle post data because it creates the appropriate headers. Other than that i don't see anything wrong with your code.
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(
str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512
).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post(
'https://poloniex.com/tradingApi', data=poloniex_data, headers=headers, timeout=20
)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
Or you could specify the 'Content-Type' in headers if you want to have a string in data, example,
headers = {
'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey'],
'Content-Type': 'application/x-www-form-urlencoded'
}
polo_request = requests.post(
'http://httpbin.org/anything', data=post_data, headers=headers, timeout=20
)

Resources