I am writing a POST request where a user tags a picture, therefore an instance of the Tagging table should be created. The picture is sent to the user through the GET request. How to I access for example the resource object that was sent through the GET request in the POST request so that I assign a Tag to a specific resource?
This is what I have tried so far:
views.py
if not isinstance(request.user, CustomUser):
current_user_id = 1
else:
current_user_id = request.user.pk
random_resource = request.GET.data.get('resource')
tag = request.data.get('tag')
created = datetime.now()
language = request.data.get('language')
Related
For a get request, I am trying to user order by like below but always get a 400 bad request. Here, multiple users can have multiple blog posts each with a unique id like b1 in screenshot below. The long sequence of characters is the uid of a user under blogs. Each user has their own uid.
https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json?orderBy="createdAt"
I followed the documentation here
https://firebase.google.com/docs/database/rest/retrieve-data
All I am doing is issuing a simple GET request in react js as follows:
const resp = await fetch(`https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json?orderBy="createdAt"``)
const data = await resp.json()
if(!resp.ok) { ... }
Below is the database single entry for schema reference
As I said in my previous comment, this URL is invalid:
https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json/orderBy="createdAt"
^
The query portion of a URL starts with a ? character.
https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app/blogs.json?orderBy="createdAt"
^
Firebase Realtime Database - Adding query to Axios GET request?
I followed the above similar issue resolution to solve my problem
I am trying to use DropBox API to get a thumbnail from DropBox and show them on Lightning Web Component in Salesforce, but can not do it because in a response Apex receiving body with black rhombs and question marks inside.
I use standard HTTP method to call
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer sl.validToken');
req.setHeader('Dropbox-API-Arg', '{"resource": {".tag": "path","path": "/folderName/pictureName.jpg"},"format": "jpeg","size": "w64h64","mode": "strict"}');
req.setHeader('Content-Type', 'text/plain; charset=utf-8');
req.setEndpoint('https://content.dropboxapi.com/2/files/get_thumbnail_v2');
req.setMethod('POST');
Http httpreq = new Http();
HttpResponse res = httpreq.send(req);
this is what I receive in body of response in Apex. The same response I have in Postman.
https://i.stack.imgur.com/90yjI.png
This is what I have in DropBox explorer with same values and headers (JSON)
https://i.stack.imgur.com/ytDxv.png
File scope is Read to everyone. SF Remote Site Settings & CSP Trusted Sites are set.
Short update:
I`ve been able to get JSON From header. I did use that piece of code:
List<String> headers = new List<String>(res.getHeaderKeys());
for(String key : headers){
System.debug('key ->>> '+key+' = '+res.getHeader(key));
}
String jsonString = res.getHeader('Dropbox-Api-Result');
System.debug('->>>ddd '+jsonString);
But still do not understand how to use it as a thumbnail in LWC.
Thank you in advance for your help.
The /2/files/get_thumbnail_v2 Dropbox API endpoint is a "content-download" style endpoint, meaning the "response body contains file content, so the result will appear as JSON in the Dropbox-API-Result response header". So, the illegible value you're receiving is the actual bytes of the thumbnail data itself. You're currently attempting to display it as text, but you'll instead need to save and display it as an image to see the thumbnail. Refer to your platform's documentation for information on how to display an image.
For reference, the Dropbox API v2 Explorer is built with knowledge of the different endpoint formats, so in this case it displays the metadata from the Dropbox-API-Result response header, and just offers the file data, in this case the thumbnail data, as a download via a "Download" button.
I'm intern and work on a project where I develop DRF API that need to interact with mobile app written by my colleague with Ionic framework.
We are creating new user. My view method is following:
class NewUser(generics.CreateAPIView):
model = User
permission_classes = [permissions.AllowAny]
serializer_class = NewUserSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
token, created = Token.objects.get_or_create(user=serializer.instance)
return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers)
When someone wants to create new user via POST request if user name has't been taken yet, then API return 201 status code and token in JSON, if user name already taken it returns 400 status and error message in JSON. MY colleague request me to change status message to 200 when he tries to create username with name that already exist. He says that he can't consume the ERROR response.
His code looks like:
$http.post(url,{
username:$scope.tel,
password:$scope.passwd
}).success(function(data){
alert(data);
$ionicLoading.hide();
console.log(data);
})
Question:
1) Should I tweak my API to send 200 status instead of more logical 400 for 'user already register' error?
I tried to change my code, But i couldn't find the method to override in CreateAPIView/ModelSerializer of DRF. I ended up rewriting my view class to method:
#api_view(['POST'])
def newUser(request):
"""
Saves a new user on the database
"""
if request.method == 'POST':
serializer = NewUserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
token, created = Token.objects.get_or_create(user=serializer.instance)
return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_200_OK)
Question:
2) If I want to change behaviorof API and responce, which method should I override
3) I'm new to Django and still don't qiute know where we should use generic views VS. #.... methods
200 vs 400 in this case is mostly preference. 400 means "Bad Request". This is generally more correct for a incorrectly formatted request, rather than one that doesn't meet some condition.
200 is just as appropriate it conveys the correct information:
Your request was valid, but I didn't create a new record.
As to how to do the override. The shortest path is to override the CreateAPIView.create and change the response code used. You should also avoid repeating the default behavior of CreateAPIView by calling super.
class CreateUserView(generics.CreateAPIView):
model = User
permission_classes = [permissions.AllowAny]
serializer_class = NewUserSerializer
def create(self, request, *args, **kwargs):
response = super(CreateUserView, self).create(request, *args, **kwargs)
token, created = Token.objects.get_or_create(user=serializer.instance)
response.status = status.HTTP_200_OK
response.data = {'token': token.key}
return response
Personally, I would have also crafted my NewUserSerializer to have a token field and handle the token so I didn't have to do that work in the View. It doesn't belong in a View.
Save and deletion hooks:
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
perform_create(self, serializer) - Called by CreateModelMixin when
saving a new object instance. perform_update(self, serializer) -
Called by UpdateModelMixin when saving an existing object instance.
perform_destroy(self, instance) - Called by DestroyModelMixin when
deleting an object instance.
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
https://www.django-rest-framework.org/api-guide/generic-views/#methods
class CourseOrder(generics.CreateAPIView):
serializer_class = serializers.OrderCoursesSerializer
permission_classes = [permissions.AllowAny]
# hook before creating
def perform_create(self, serializer):
# print(serializer['name'].value)
# save post data
serializer.save()
try:
subject, from_email, to = 'New order', 'zelenchyks#gmail.com', 'zelenchyks#gmail.com'
text_content = 'New order'
html_content = '''
<p>client name: %s </p>
<p>client phone: %s </p>
'''
% (serializer['name'].value, serializer['mobile'].value)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
except Warning:
print('Huston we have a problems with smtp')
I have the following GQL database model:
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
And this is the POST request used to store content to the database
def post(self):
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
a = Post(subject = subject, content = content)
a.put()
self.redirect("/")
else:
error = "subject and content can neither be empty"
self.Render_NewPost(subject, content, error)
If I POST content to the database it works alright since i don't get the error. However I don't get the contents to show on the page it is suppose to show.
I'm interested in knowing the command line instruction I can use to check the database to be sure if the contents been posted are actually in the database or not so I can know where to figure out the problem of the content not showing on my Homepage as I hoped.
Thanks
Wait 30 seconds and refresh the page /. You may be running into the issue of "eventual consistency", where the data will "eventually" be put into the physical datastore you've queried, but may not be there yet.
I am using Restangular in one of my works
The server guys have give me the following calls which i need to integrate on the AngularJS client
PUT api/partners/password – RequestPayload[{password,confirmpassword}]
partner id is being sent in the header
GET api/partners/password/forgot/ - Request Payload [{emailaddress}]
partner id is being sent in the header
The javascript code that I have written to call these services is as follow
Restangular.all('Partners').one('Password').put(params); - sends params as query string
Restangular.all('Partners').one('Password').one('Forgot').get(params); - sends object in the url
I have tried other ways but it simply doesn't make the correct call.
Help me out guys!
So, for point #1. it puts the object at hand, not another object. So you have 2 options:
Option 1
var passReq = Restangular.all('Partners').one('Password');
passReq.confirmPassword = ....
passReq.put(); // confirmPassword and the params of the object will be sent
Option 2 is
var passReq = Restangular.all('Partners').one('Password').customPUT(obj);
For Point #2, you cannot send a request body (payload) in the GET unfortunately.