I'm trying to upload a picture to a python-eve server using the requests library. In order to do that, I send a multipart/form-data request. This seems to be a problem for my schema, which looks like this:
schema = {
'name': {
'type': 'string',
'required': True
},
'description': {
'type': 'string'
},
'picture': {
'type': 'media'
},
'properties': {
'type' : 'dict'
}
}
The request looks like this:
import requests
file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}}
r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file})
What I get is a ResourceInvalid exception:
ResourceInvalid: Failed. Response status: 422. Response message: UNPROCESSABLE ENTITY. Error message: {"_status": "ERR", "_issues": {"properties": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s) contain(s) error(s)", "code": 422}}
Is there any solution for this? Am I missing something about the request format?
Something like this should work just fine:
import requests
file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello'}
r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file})
I have just had a similar issue. I suggest you try to change your code this way: dump your dictionary into a json object, and add an header to describe the content you are sending.
import requests
import json
file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}}
headers = {'Content-type': 'application/json; charset=utf-8'}
r = requests.post("http://localhost:5001/node", data=json.dumps(payload), files={'picture': file}, headers=headers)
Related
code
d = { 'operationName': 'CreateMessage', 'variables': { 'message': { 'content': 'hello world', 'pictureKeys': [], 'syncToPersonalUpdate': True } }, 'query': query }
print(d)
resp = requests.post(url, data=d, headers = headers, cookies = cookies)
print(resp)
print(resp.content.decode('utf-8'))
stdout:
{'operationName': 'CreateMessage', 'variables': {'message': {'content': 'hello world', 'pictureKeys': [], 'syncToPersonalUpdate': True}}, 'query': 'mutation CreateMessage($message: CreateMessageInput!) {\n createMessage(input: $message) {\n success\n toast\n __typename\n }\n}\n'}
<Response [400]>
Variables are invalid JSON.
I'm new to graphql, what does this mean and how could I fix it?
Convert your dict to json
import json
resp = requests.post(url, data=json.dumps(d), headers = headers, cookies = cookies)
I am trying to verify webhooks for subscriptions in paypal using django python. I am receiving the webhooks but when i send them to get verified i get this error: {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'ccc873865982', 'details': [{'field': '/', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []}. I have checked what the status code is for the response which gives a 400 response. By looking at the API Docs i see that invalid request + 400 response is either a validation error (which is to do with the Json format, so most likely a syntax error) or an authorization error (which says i need to change the scope). I think it is the validation error because the error points to the body.
Here is the relevant code:
header_params = {
"Accept": "application/json",
"Accept-Language": "en_US",
}
param = {
"grant_type": "client_credentials",
}
cid = settings.PAYPAL_CLIENT_ID
secret = settings.PAYPAL_CLIENT_SECRET
token_i = requests.post('https://api-m.sandbox.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=header_params, data=param).json()
token = token_i["access_token"]
bearer_token = "Bearer x".replace('x', token)
headers = {
"Content-Type": "application/json",
"Authorization": bearer_token,
}
print(request.body)
webhook_event = request.body.decode("utf-8")
data = {
"transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"],
"transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"],
"cert_url": request.headers["PAYPAL-CERT-URL"],
"auth_algo": request.headers["PAYPAL-AUTH-ALGO"],
"transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"],
"webhook_id": "3AJ143072C221060T",
"webhook_event": webhook_event,
}
print(json.dumps(data))
response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=json.dumps(data)).json()
print('worked')
print(response)
if response["verification_status"] == "SUCCESS":
print('success')
Here is the print of the print(json.dumps(data)) (i removed some ids):
{
"transmission_id": "id_is_here",
"transmission_time": "2021-07-04T23:37:29Z",
"cert_url": "https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-7a8abba8",
"auth_algo": "auth_algo",
"transmission_sig": "EODOx5y8kIDycYiBYcIgByiBzHyEfu1/NS2nsumOIksVuw/2vJwHj2FcuHYxIa4n/s+s25xkeqk0CXPiSuqtNUGv4pvFtpwbCVAOCU+Msn304+wBgyb7G24rwUPwrof/5jHYQxqKKX5RzxTrff4oPnisKBDUUXV4s2+KO3h2RYAhrXtwTSPt7cK5ZbGZ6SmfpYJ8qDnYFh4PIesLeflSPQ4vHQrFbgr3NiW63sZruGFJc0hTWWc8L3BhzDuUfiSrxBJLAtrqReC8R0HSV8D+Ywmdeipep54yZeJZXfbmUUGvSYbmVMsVggyzZnltyl1hP5xUd3iIi2jdNWYpLESZzA==",
"webhook_id": "Webhook_id_is_here",
"webhook_event": "{\"id\":\"id_here\",\"event_version\":\"1.0\",\"create_time\":\"2021-07-04T23:37:26.733Z\",\"resource_type\":\"subscription\",\"resource_version\":\"2.0\",\"event_type\":\"BILLING.SUBSCRIPTION.CREATED\",\"summary\":\"Subscription created\",\"resource\":{\"start_time\":\"2021-07-04T23:37:26Z\",\"quantity\":\"1\",\"create_time\":\"2021-07-04T23:37:26Z\",\"custom_id\":\"custom_id_here\",\"links\":[{\"href\":\"https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=BA-2UF06918UT180770Y\",\"rel\":\"approve\",\"method\":\"GET\"},{\"href\":\"https://api.sandbox.paypal.com/v1/billing/subscriptions/I-4S15814RUE18\",\"rel\":\"edit\",\"method\":\"PATCH\"},{\"href\":\"https://api.sandbox.paypal.com/v1/billing/subscriptions/I-4S15814RUE18\",\"rel\":\"self\",\"method\":\"GET\"}],\"id\":\"sub_id_here_\",\"plan_overridden\":false,\"plan_id\":\"P-0DA33732CG980003EMDQJ6BA\",\"status\":\"APPROVAL_PENDING\"},\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-91E32247D9338170B-4RF07261WK370823W\",\"rel\":\"self\",\"method\":\"GET\"},{\"href\":\"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/id_here/resend\",\"rel\":\"resend\",\"method\":\"POST\"}]}"
}
Your data for the key webhook_event is double encoded as JSON.
You have to decode it with
webhook_event = json.loads(webhook_event)
or not encode it in the first place.
I'm trying to take the first download 'str' zip link. I don't need more than one file of information. When I tried a not famous movie such as Shame 2011 My code worked but when I tried Avatar doesn't work. I think the code trying to take a lot of 'str' files information, API after that blocks this request.
**How I can reach the first English str file download link? **
from xmlrpc.client import ServerProxy
from pprint import pprint
imdb='tt0499549'#-->Avatar
#'tt1723811'-->Shame 2011
server = ServerProxy("http://api.opensubtitles.org/xml-rpc")
token = server.LogIn('yourusername', 'yourpassword', 'eng', 'TemporaryUserAgent')['token']
response = server.SearchSubtitles(token, [{'sublanguageid': 'eng', 'query':imdb }])#'moviehash':"0"
pprint(response)
You only have five attempts with TemporaryUserAgent.
Check out opensubtitle's new API - here's the documentation. It's way easier to use than the older API.
Grabbing subtitles is as easy as
headers = {
'Api-Key': api_key,
}
params = (
('imdb_id', movie_id),
)
response = requests.get('https://www.opensubtitles.com/api/v1/subtitles', headers=headers, params=params)
Where api_key is your api_key from their website, and movie_id is the movie's IMDB id (e.g., Titanic's ID is 0120338, and can be found within the URL of its movie page on IMDb - https://www.imdb.com/title/tt0120338/)
An example of the response returned looks like this:
{'id': '5164746',
'type': 'subtitle',
'attributes': {'subtitle_id': '5164746',
'language': 'en',
'download_count': 9608,
'new_download_count': 46,
'hearing_impaired': False,
'hd': True,
'format': None,
'fps': 23.976,
'votes': 0,
'points': 0,
'ratings': 0.0,
'from_trusted': False,
'foreign_parts_only': False,
'auto_translation': False,
'ai_translated': False,
'machine_translated': None,
'upload_date': '2020-02-09T13:59:42Z',
'release': '2160p.4K.BluRay.x265.10bit.AAC5.1-[YTS.MX]',
'comments': "Slightly resynced the 1080p.WEBRip.x264-[YTS.LT] version by explosiveskull to this 4K release. HI removed. I didn't do 4K sync for Infinity War, as they're already on site here:\r\nHi: https://www.opensubtitles.org/en/subtitles/7436082/avengers-infinity-war-en\r\nNo HI: https://www.opensubtitles.org/en/subtitles/7436058/avengers-infinity-war-en",
'legacy_subtitle_id': 8092829,
'uploader': {'uploader_id': 66694,
'name': 'pooond',
'rank': 'bronze member'},
'feature_details': {'feature_id': 626618,
'feature_type': 'Movie',
'year': 2019,
'title': 'Avengers: Endgame',
'movie_name': '2019 - Avengers: Endgame',
'imdb_id': 4154796,
'tmdb_id': 299534},
'url': 'https://www.opensubtitles.com/en/subtitles/legacy/8092829',
'related_links': {'label': 'All subtitles for Avengers: Endgame',
'url': 'https://www.opensubtitles.com/en/movies/2019-untitled-avengers-movie',
'img_url': 'https://s9.osdb.link/features/8/1/6/626618.jpg'},
'files': [{'file_id': 5274788,
'cd_number': 1,
'file_name': 'Avengers.Endgame.2019.2160p.4K.BluRay.x265.10bit.AAC5.1-[YTS.MX].srt'}]}}
To download a file you would take the 'file_id' and input it into a download request to the Open Subtitle API like this:
headers = {
'Api-Key': api_key,
'Authorization': auth,
'Content-Type': 'application/json',
}
data = '{"file_id":5274788}'
response = requests.post('https://www.opensubtitles.com/api/v1/download', headers=headers, data=data)
Where auth is the authorization key you get from their API (/api/v1/login endpoint):
headers = {
'Api-Key': api_key,
'Content-Type': 'application/json',
}
data = '{"username":"__USERNAME","password":"__PASSWORD"}'
response = requests.post('https://www.opensubtitles.com/api/v1/login', headers=headers, data=data)
and __USERNAME and __PASSWORD is your account's username and password.
There is a solution
import requests
import json
from pprint import pprint
url = "https://www.opensubtitles.com/api/v1/login"
headers = {'api-key':'YOUR API KEY', 'content-type': 'application/json'}
user = {'username': 'YOUR USERNAME', 'password': "YOUR USER PASSWORD"}
try:
login_response = requests.post(url, data=json.dumps(user), headers=headers)
login_response.raise_for_status()
login_json_response = login_response.json()
login_token = login_json_response['token']
except:
print("Something wrong check again...")
imdb_id="tt0499549"
headers = {
'Api-Key': 'YOUR API KEY',
}
params = (
('imdb_id', imdb_id),
)
query_response = requests.get('https://www.opensubtitles.com/api/v1/subtitles?', params=params, headers=headers)
query_json_response = query_response.json()
print("Report:",query_response)
#pprint(query_json_response)# All data here...
query_file_name = query_json_response['data'][0]['attributes']['files'][0]['file_name']
query_file_no = query_json_response['data'][0]['attributes']['files'][0]['file_id']
movie_img = query_json_response['data'][0]['attributes']['related_links']['img_url']
print ("Movie Image url:",movie_img)
print("File Number:",query_file_no)
print("Subtile File Name:",query_file_name)
download_url = "https://www.opensubtitles.com/api/v1/download"
download_headers = {'api-key': 'YOUR API KEY',
'authorization':login_token,
'content-type': 'application/json'}
download_file_id = {'file_id': query_file_no}
download_response = requests.post(download_url, data=json.dumps(download_file_id), headers=download_headers)
download_json_response = download_response.json()
print("Report:",download_response)
print(download_json_response)
link=download_json_response['link']
saved_file_name = "subtitle.srt"
r = requests.get(link)
with open(saved_file_name, 'wb') as f:
f.write(r.content)
I'm sending form data and images in a POST request to my backend:
data = {
'username': self.ids['username'].text,
'email': self.email_field.text,
'password': self.ids['password'].text,
'data': json.dumps({
'first_photo': open(f'{self.selfies_path}/first.png', 'rb'),
'second_photo': open(f'{self.selfies_path}/second.png', 'rb'),
'third_photo': open(f'{self.selfies_path}/third.png', 'rb')
})
}
response = requests.post('http://5.10.203.170/auth/register', files=data)
The above throws python : TypeError: Object of type BufferedReader is not JSON serializable
How can I make it work ?
You can change your file to base64
I went with:
data = {
'first_photo': open(f'{self.selfies_path}/first.png', 'rb'),
'second_photo': open(f'{self.selfies_path}/second.png', 'rb'),
'third_photo': open(f'{self.selfies_path}/third.png', 'rb'),
'data': json.dumps({
'username': self.ids['username'].text,
'email': self.email_field.text,
'password': self.ids['password'].text
})
}
response = requests.post('http://5.10.203.170/auth/register', files=data)
convert bytes into base64 and decrypt it in your website code
I am going to post phone in the app but I am getting error again and again. Because the structure of the post looks like that
data = {
'login': 'login',
'password': 'password',
'data': '[{"user_id": "user_id","text": "key"}]'
}
response = requests.post('url', data=data)
the problem with this code is that user_id and key because they are not default values they can be different. if I remove apostrophe from the list. Error occurs Array is not Json. If I put this like that
data = [
{
'login': 'login',
'password': 'password',
'data': {"user_id": user_id, "text": key}
}
]
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
response = requests.post('url', json=data, headers=headers)
It throws another error Login or Password is null. How can I solve this problems any help plz? thank you in advance!
If I understand the question correctly, you want to replace the hard-coded user id and key with values from a pair of variables. This shouldn't require any change in the structure of the payload. Just try
import json
user_id = "..."
key = "..."
request_data = [{"user_id": user_id, "text": key}]
data = {
'login': 'login',
'password': 'password',
'data': json.dump(request_data)
}
response = requests.post('url', data=data)