How can I update an object metadata through Google Cloud Storage using Python aiohttp PATCH request? - google-api

I'm trying to update an object metadata through Google Cloud Storage using Python aiohttp PATCH request, code attempt as follow.
async def send_init_value_map(sequence_name):
"""Update a blob's metadata."""
initial_value_map = {"metadata", "value": {'test':0}}
async with ClientSession() as session:
await session.patch(url=api_url, headers=headers, data=initial_value_map)
return initial_value_map
The url and headers in the patch request are good, as they worked in GET request. However, I'm not sure if I'm passing the data field right, the change didn't take effect.
Info on PATCH within aiohttp documentation is limited, as the format for data field input is not specified.
I'm not going with the Google API Client option because I need to use aiohttp for async function implementation.
Thank you in advance for you inputs.

I had to convert the data dictionary to json first. After that, the data was successfully updated.
async def send_init_value_map(sequence_name):
"""Update a blob's metadata."""
initial_value_map = {"metadata", "value": {'test':0}}
async with ClientSession() as session:
await session.patch(url=api_url, headers=headers, data=json.dumps(initial_value_map))
return initial_value_map

Related

How to upload the image in the API request through the groovy

In my API request, with the request payload the complete image is also getting loaded. Is there any way I can script it through JMeter using Groovy?
UI Call where I am uploading image:
enter image description here
Main Request POST Call: enter image description here
Image in the request payload: enter image description here
Can it be done through groovy on JMeter.
Out of interest, why do you want to do this in Groovy? I believe using normal HTTP Request sampler would be much easier, moreover you will be able to even record the request(s) using HTTP(S) Test Script Recorder, this way you will get more metrics and won't need to handle the request and response.
If you still want to do this in Groovy I believe the best option would be calling relevant Apache HttpComponents functions, example code:
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.HttpMultipartMode
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.impl.client.HttpClientBuilder
def imageFileName = "/path/to/your/image.png"
def post = new HttpPost("http://your-server");
def file = new File(imageFileName);
def builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, imageFileName);
def entity = builder.build();
post.setEntity(entity);
def response = HttpClientBuilder.create().build().execute(post)
//do what you need with the response here
More information: How to Send Groovy HTTP and HTTPS Requests

Using a lambda API as a reverse proxy for content stored in S3?

I would like to apply a reverse proxy on top of S3 to make content serving decisions based on the incoming request.
The S3 bucket is set to website mode and hosted publically.
I'll obviously have more logic to determine where I am getting the files from, but hopefully this will illustrate my desire.
This is using JavaScript, happy to use Go as well.
The following code does not work, but I'm not sure how best to get it working. Can I just send an arrayBuffer through?
module.exports.handler = async (event, context) => {
const data = await fetch(S3WebsiteURL + event.path)
const buffer = await data.arrayBuffer()
return {
headers: data.headers,
body: buffer,
statusCode: 200
}
}
I would use https://www.npmjs.com/package/request-promise
var rp = require('request-promise');
const htmlString = await rp(S3WebsiteURL + event.path);
return {
body: htmlString,
statusCode: 200
}
Try without headers and if it works, add header support.
I've found it difficult to use Lambda to proxy data - using API gateway, at least, it expects binary data in base-64 format at various points depending on how you set it up. They've improved things since I tried to do it that way last, so hopefully someone else can answer based on more recent experience.
If your content serving decisions are limited to access control (you don't need to transform the data you're serving), then you can use your lambda as a URL provider instead of a content provider - switch public sharing of the S3 bucket off, access the items using the S3 API, and have your lambda call S3.getSignedUrl() to get a link to the actual content. This means that only the callers of the lambda will have a valid URL to the content you want to protect, and depending on your application you can set the timeout on the pre-signed URL to be short enough you don't have to worry about it being shared.
The advantage here is that since the content itself doesn't get proxied through the lambda, your lambda runtime and memory costs can be lower and performance should be better.

Send object with axios get request [duplicate]

This question already has answers here:
Axios get in url works but with second parameter as object it doesn't
(4 answers)
Closed 5 years ago.
I want to send a get request with an object. The object data will be used on the server to update session data. But the object doesn't seem to be sent correctly, because if I try to send it back to print it out, I just get:
" N; "
I can do it with jQuery like this and it works:
$.get('/mysite/public/api/updatecart', { 'product': this.product }, data => {
console.log(data);
});
The object is sent back from server with laravel like this:
public function updateCart(Request $request){
return serialize($request->product);
The same thing doesn't work with axios:
axios.get('/api/updatecart', { 'product': this.product })
.then(response => {
console.log(response.data);
});
I set a default baseURL with axios so the url is different. It reaches the api endpoint correctly and the function returns what was sent in, which was apparently not the object. I only get "N; " as result.
Axios API is a bit different from the jQuery AJAX one. If you have to pass some params along with GET request, you need to use params property of config object (the second param of .get() method):
axios.get('/api/updatecart', {
params: {
product: this.product
}
}).then(...)
You can pass either a plain object or a URLSearchParams object as params value.
Note that here we're talking about params appended to URL (query params), which is explicitly mentioned in the documentation.
If you want to send something within request body with GET requests, params won't work - and neither will data, as it's only taken into account for PUT, POST, DELETE, and PATCH requests. There're several lengthy discussions about this feature, and here's the telling quote:
Unfortunately, this doesn't seem to be an axios problem. The problem
seems to lie on the http client implementation in the browser
javascript engine.
According to the documentation and the spec XMLHttpRequest ignores the
body of the request in case the method is GET. If you perform a
request in Chrome/Electron with XMLHttpRequest and you try to put a
json body in the send method this just gets ignored.
Using fetch which is the modern replacement for XMLHtppRequest also
seems to fail in Chrome/Electron.
Until it's fixed, the only option one has within a browser is to use POST/PUT requests when data just doesn't fit into that query string. Apparently, that option is only available if corresponding API can be modified.
However, the most prominent case of GET-with-body - ElasticSearch _search API - actually does support both GET and POST; the latter seems to be far less known fact than it should be. Here's the related SO discussion.

I want to show progress bar in django template, on the basis of django post process/progress(form is ajax submit). is it possible?

def post(self, request, *args, **kwargs):
if attorney_data_list:
for i in len(attorney_data_list):
if(index%3 == 0):
process_percent = int(100 * float(index) / float(len(case_data_list)+1))
else:
pass
i want this process_percent value in django template on every for loop.is it possible?
No. Standard HTTP connections are request / response based, meaning that you only send the response to the browser once the function completely ran.
To provide the current process from within this function, you would probably need to use websockets, though I am not really familiar with them.
With standard HTTP-requests, you could use the database to store the process_percentage and use another ajax-request to retrieve the process_percentage from the database and send it to the browser.

Django: Is it possible create and send Json from a view to another server?

If i have a link like this one Get User Data who points in a view inside my own server, is there any way to send a json object (maybe just maybe with ajax?) to another external server and retrieve an answer? Something like this:
from django.shortcuts import render
def profile(request):
#send a json object to another server like http://www.myotherserver.com/user
#get the answer and process it
return render(request, 'accounts/profile.html' ,
{'profile_user': data_from_the_external_server})
The above i can implement it of course with jquery-ajax but i just was wondering if i can do it this way...
Thanks in advance.
Of course you can. Why wouldn't it be possible?
Don't code this in AJAX if that's not necessary.
There are 2 things you need, you need to prepare the JSon to send and then you need to send it to the API you want:
Look at "simplejson" to create the json data to send.
Look at "urllib" to send a request to another server in Python (like here: How to send a POST request using django?)
Also do not put it straight in your view. Create a new class for it. So in your view you'll have something like that:
def profile(request):
# instantiate your service here (better with DI)
profile_user = my_service.get_profile_user()
return render(
request,
'accounts/profile.html' ,
{
'profile_user': profile_user
}
)
If you need to send HTTP data (via a POST or GET) to another server and receive a result from within your view, you can use Python's urllib2 library. However there is an easier third party library called Requests which can handle this task for you.

Resources