Make multipart/form-data post requests with python - python-3.x

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.

Related

Download a growing log file continuously via HTTP

I managed to get data from the target (see code below), but I want to continuously download as the log file on the server is appended to.
from importlib.resources import path
import requests
import json
import shutil
import logging
logging.captureWarnings(True)
url = "https://<IP address>/wga/reverseproxy_logging/instance/wga/request.log"
headers = {'Accept': 'application/json'}
r = requests.get(url, stream=True, headers=headers, verify=False, auth=('user','password'))
with open('request.log', 'wb') as out_file:
shutil.copyfileobj(r.raw, out_file)

Unable to Access API

I am unable to access an API.
This is what I am doing:
import os, re
import requests
import logger
from requests_oauthlib import OAuth1
oauth_consumer_key = "123abc"
oauth_secret = "aaabbbccc"
url = "https://example_testing/v1/<ID_VALUE>/reports?"
oauth = OAuth1(oauth_consumer_key, oauth_secret)
output = requests.get(url,auth=oauth)
I keep getting a 500 error.
What am I doing wrong?
I didn't know this but apparently I needed to set values for headers and the payload. This solved my problem.
headers = {"Content-Type": "application/json"}
payload = json.dumps({
"report_format":"csv",
<other stuff>
}
output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
Problem Solved

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

MissingSchema - Invalid URL Error with Requests module

Trying to get data from the eBay API using GetItem. But requests isn't reading or getting the URL properly, any ideas? Getting this error:
requests.exceptions.MissingSchema: Invalid URL '<urllib.request.Request object at 0x00E86210>': No schema supplied. Perhaps you meant http://<urllib.request.Request object at 0x00E86210>?
I swear I had this code working before but now it's not, so I'm not sure why.
My code:
from urllib import request as urllib
import requests
url = 'https://api.ebay.com/ws/api.dll'
data = '''<?xml version="1.0" encoding="utf-8"?>
<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<RequesterCredentials>
<eBayAuthToken>my-auth-token</eBayAuthToken>
</RequesterCredentials>
<ItemID>any-item-id</ItemID>
</GetItemRequest>'''
headers = {
'Content-Type' : 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' : 719,
'X-EBAY-API-DEV-NAME' : 'dev-name',
'X-EBAY-API-APP-NAME' : 'app-name',
'X-EBAY-API-CERT-NAME' : 'cert-name',
'X-EBAY-API-SITEID' : 3,
'X-EBAY-API-CALL-NAME' : 'GetItem',
}
req = urllib.Request(url, data, headers)
resp = requests.get(req)
content = resp.read()
print(content)
Thank you in advance. Any good reading material for urllib would be great, too.
You are mixing the urllib and the requests library. They are different libraries that can both do HTTP-requests in Python. I'd suggest you use only the requests library.
Remove the line req = urllib.Request(url, data, headers) and replace the resp = ... line with:
r = requests.post(url, data=data, headers=headers)
Print the response body like this:
print(r.text)
Check out the Requests Quickstart here for more examples: https://2.python-requests.org//en/master/user/quickstart/

issue with aiohttp POST for a binary file upload

I have successfully used the requests module to upload a binary file (jpg), with something like the following:
upload_url = 'http:10.1.1.1:8080/api/media/photo'
headers = {'Authorization': token_string, 'Content-Type': 'image/jpg'}
data = open('photo.JPG', 'rb')
params = {'name': 'photo.JPG'}
r = requests.post(upload_url, params=params, data=data, headers=headers)
Now trying to do this with aiohttp client. This is what I have so far:
def upload_photos(token):
upload_url = '10.0.1.1:8080/api/media/photo'
headers = {'Authorization': token, 'Content-Type': 'image/jpg'}
data = {'file': open('photo.JPG', 'rb')}
params = {'name': 'photo.JPG'}
r = yield from aiohttp.request('post', upload_url, params=params, data=data, headers=headers)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(upload_photos(token))
But I am getting a 400 back, with {"detail": "Specified value is invalid: Invalid Content-Length specified"}.
It's as if it's not properly sending the photo.jpg. The aiohttp docs mentione multi-part encoded files and streaming, but that's not whant I want here.
How do I form a similar POST w/ binary file like in requests, but with aiohttp?
Thank you for a bug report. As workaround I guess to use chunked transfer encoding:
headers['Transfer-Encoding'] = 'chunked'
r = yield from aiohttp.request('post', upload_url, params=params, data=data, headers=headers, chunked=1024)
The recipe should work, at least we have very simular code in our test suite: https://github.com/KeepSafe/aiohttp/blob/master/tests/test_client_functional.py#L322
I'll try to fix Content-Length calculation for your uploading way in next aiohttp release.

Resources