i want upload a file from local server to host with api and work with requests library but i don't know how do this with aiohttp
code with requests library
url = "https://example.com/upload"
payload={'Domain': 'yourdomain','path': '/'}
files=[
('file',('test.txt',open('your file path','rb'),'text/plain'))
]
headers = {
'Authorization': 'yourtoken'
}
response = requests.request("POST", url,
headers=headers, data=payload, files=files)
print(response.text)
aiohttp code
url = "https://example.com/files/upload"
headers = {
'Authorization': 'yourtoken'
}
fields = {'Domain': 'yourdomain',
'path': '/',
'file':('test.txt',open('your file path','rb'),'text/plain')
}
async with aiohttp.ClientSession() as session :
async with session.post(url,data=fields,headers=headers) as res :
print(res.text)
just return 200 [ok]
Related
I'm using React Native and I need to send an image in base64 format using a POST method of binary type.
const session = await Auth.currentSession();
const config = {
headers: {
"Content-Type": "image/jpeg",
"x-amz-acl": "public-read",
Authorization: session.getIdToken().getJwtToken(),
},
};
const API = `event/${eventData.id}/photos`;
const HOST = "https://host.com/";
const url = `${HOST}/${API}`;
const result = await axios.post(url, photo.uri, config);
console.log("Result: ", result);
But I'm running into this error: [AxiosError: Request failed with status code 400]
My postman:
I'm trying to get the right response data from AWS S3.
I have the following method in a VueJS application:
const downloadImageBase64 = async imageUrl => {
try {
var result = await axios({
method: "get",
url: imageUrl,
responseType: 'blob',
crossdomain: true
});
return blobToBase64(result.data);
}
catch (err) {
console.log("err: ", err);
return "";
}
};
I am downloading images and returning them as a base64 strings because I'm embedding them into PDF's that I'm creating using JSPDF. The images themselves are hosted in AWS S3. I have the CORS policy set up in the appropriate S3 bucket:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET"
],
"AllowedOrigins": [
"https://mydomain.co.za"
"http://localhost:8082"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
When running the app on my localhost, the image download succeeds with both FireFox and Chrome:
However, the moment I deploy the app to my staging environment, the download starts to fail with CORS issues, but only on Chrome. Looking at the request headers, no CORS info is even being sent:
I don't know if there's a preflight that Chrome is not showing in the network traffic, but the console gives me the following error:
Access to XMLHttpRequest at 'https://my-bucket.s3-eu-west-1.amazonaws.com/my-image-path.png' from origin 'https://mydomain.co.za' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
It turns out the issue is that I display the images on the webpage where the download PDF button is placed, which means that chrome caches these images and when attempting to download the images for the PDF, chrome is returning the cached images without the CORS headers. I more or less got the answer from here:
https://www.hacksoft.io/blog/handle-images-cors-error-in-chrome
So the solution is to append a throw-away get parameter to the URL when downloading for the PDF:
const downloadImageBase64 = async imageUrl => {
try {
var result = await axios({
method: "get",
url: `${imageUrl}?not-from-cache-please`,
responseType: 'blob',
crossdomain: true
});
return blobToBase64(result.data);
}
catch (err) {
console.log("err: ", err);
return "";
}
};
Note the:
url: `${imageUrl}?not-from-cache-please`
i want to get id token from my credentials, i have an url, header, and body from client:
i do code in jupyter like this but did not work, any idea?
import requests
import json
import os
url = "https://xxxxx"
querystring = {"page":"0","limit":"50","sort":"desc"}
payload = "{'key':'value'}"
headers = {
'Content-Type': "application/json"
}
body = {
'email': "{{email}}",
'password': "{{password}}"
}
resp = requests.request("POST", url, data=payload, headers=headers, body=body)
respText = json.loads(resp.text)
respText['data']
Hi I want to upload file using React native to flask server
I sent a file using fetch function and I received response. But print(request.files) result ImmutableMultiDict([]) how to I see my file in server? I checked state was right and I got response {'state' : 'ff'}
react native
pressSumbitButtom() {
var formData = new FormData()
formData.append('file', this.state.file)
return fetch('http://127.0.0.1:8000/file/', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(res =>
res.json()
).then(data => console.log(data))
}
App.py
#app.route("/file/", methods=['GET', 'POST'])
#cross_origin(origin='*', headers=['Contect-Type'])
def get_filepath() :
response = jsonify({'state':'ee'})
if request.method == 'POST' :
print('response: ',response, 'request: ', request)
print(request.files)
response= jsonify({'state':'ff'})
return response
return response
Trying to send a post request to my Laravel API from the angular 2 app.
My method:
getCombinas(test)
{
this.loadedResult = false;
let body = JSON.stringify({
test: test,
});
this.http.request('testAPI', { body:body, method:'POST' })
.map((res:Response) => res.json())
.subscribe(
data => {
console.log(data);
},
error => {
console.log(error.text());
}
);
}
In my httpd.conf (apache configuration) I allowed cors:
Header set Access-Control-Allow-Origin "*"
And I'm using custom request options class in my angular 2 app:
import {BaseRequestOptions, RequestOptions, RequestOptionsArgs, Headers} from '#angular/http';
export class CustomRequestOptions extends BaseRequestOptions {
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = 'MY_API_URL/api/' + options.url;
if (options.method === 1) {
let headers = new Headers();
headers['Content-Type'] = 'application/json';
headers.append('Content-Type', 'application/json');
options.headers = headers;
}
return super.merge(options);
}
}
The error occured only after I added those 2 lines:
headers['Content-Type'] = 'application/json';
headers.append('Content-Type', 'application/json');
But without them, My Laravel get text/plain response and I can't use it.. I need JSON response.
What's wrong?
If missing you have to enable apache mod_header with command
a2enmod headers
then restart apache
It looks like you should additionally write Access-Control-Allow-Headers header with necessary value to response.