How do I get the same format for a javascript array and django set on the backend? - javascript

I have code that, when a user is logged in, selects recipes that apply to him based on the ingredients (items) he has previously identified identified as possessions.
This code gets the id's of the items the user already has:
if request.user.is_authenticated():
user_items = [possession.item for possession in request.user.possession_set.all()]
user_items_ids = [item.id for item in user_items]
uids = set(user_items_ids)
The following code, which already existed, is where I run into problems...
recipes = [(recipe, len(set([item.id for item in recipe.items.all()]) & uids), recipe.votes) for recipe in recipes]
I created another part of the site that allows people who have not yet signed up to just pick a few ingredients. I do this with some jQuery on the front end, then send the results to the backend:
var ingredient_set = [];
$('.temp_ingredient').each(function(index){
ingredient_set[index] = $(this).attr('id').substr(4);
});
$.get('/recipes/discover', { 'ingredients': ingredient_set },
function(){
alert("Success");
});
The problem is when I receive them on the Django side, with this code:
uids = request.GET['ingredients']
I get the following error:
unsupported operand type(s) for &: 'set' and 'unicode'
Basically, I know they aren't in the same format, but I don't know how to get them to be compatible.

You are sending a JavaScript array in the query string of your GET request. Therefore you should use request.GET.getlist. Just using request.GET[key] gives you the last value for that key.
>> request.GET['foo[]']
u'5'
>> request.GET.getlist('foo[]')
[u'1', u'2', u'4', u'5']
Note that the values are unicode, but you probably need them as integers, so be sure to convert them.
uids = request.GET.getlist('foo[]')
uids = set([int(x) for x in uids])
I'm not sure why my key is actually foo[] and not just foo, but as you get no KeyError, request.GET.getlist('ingredients') should work.

Related

How to get views and comment count when using Youtube data api -v3 playlistItems

I'm trying to get some data using Youtube data api -v3 playlistItems. I'm able to get all the data that comes with playlistItems perfectly. However, I need more data than what playlistItems offers. For example, I would like to get the view counts, comment count, and all the statistics
I know I could use /youtube/v3/videos to get the statistics but I have been trying this and it is not working for me. Please help. Thanks.
export function buildVideosRequest(amount = 12, loadDescription = false, nextPageToken) {
let fields = 'nextPageToken,prevPageToken,items(contentDetails/videoId,id,snippet(channelId,channelTitle,publishedAt,thumbnails/medium,title)),pageInfo(totalResults)';
if (loadDescription) {
fields += ',items/snippet/description';
}
return buildApiRequest('GET',
'/youtube/v3/playlistItems',
{
part: 'snippet,contentDetails',
maxResults: amount,
playlistId: 'PLvahqwMqN4M0zIUkkXUW1JOgBARhbIz2e',
pageToken: nextPageToken,
fields,
}, null);
}
Upon invoking the PlaylistItems.list endpoint, you obtain a result set of which each item is a playlistItems resource JSON object.
That JSON object doesn't contain the info you're interested in (view count, comment count, etc). This kind of info -- as you alluded yourself -- is obtainable through the Videos.list API endpoint.
That is that you have to collect all video IDs that you're interested in into an array, then invoke repeatedly the Videos.list endpoint, passing to it an id parameter assigned properly.
Note that this endpoint's id property allows you to reduce the number of endpoint calls, since the id may be specified as a comma-separated list of video IDs (at most 50). Hence, if you have for example an array of 114 video ID's, then you may issue only 3 calls to Videos.list.

Stored procedure azure Cosmos DB returns empty collection

I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.
Stored Procedure
// SAMPLE STORED PROCEDURE
function sample(prefix) {
var collection = getContext().getCollection();
console.log(JSON.stringify(collection));
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var body = { prefix: prefix, feed: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
The console shows only this.
the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.
I had a similar issue. I think the Azure portal doesn't execute stored procedures properly when the partition key is not a string.
In my case I had a partitionKey that is a number. When I executed the stored procedure via the portal I always got an empty resultSet, even though I had documents in my database. When I changed the structure a little, and made my partitionKey a string, the stored procedure worked fine.
Did you create the ToDoList Database with the Items Collection? Yo can do this from the Quick start blade in the Azure portal.
And then create an SP to run against that collection. There is no partition key required, so no additional params are required (leave blank).
The Collection is created without any documents. You may choose to add documents via the Query Explorer blade or via the sample ToDoList App that is available via the Quick start blade.
You are debugging in a wrong way.
It is perfectly fine to see "{\"spatial\":{}}" in your console log, even if the collection has items. Why? well because that is a property of that object.
So regarding what you said:
the results shows no doc found because of not getting collection
is false. I have the same console log text, but I have items in my collection.
I have 2 scenarios for why your stored procedure return no items:
I had the same issue trying on azure portal UI(in browser) and for my surprise I had to insert an item without the KEY in order that my stored procedure to see it.
On code you specify the partition as a string ie. new PartitionKey("/UserId") instead of your object ie. new PartitionKey(stock.UserId)

How to clear the search parameter that caused the error?

Let's say I have a page that renders search results depending on the parameters in the URL like so:
https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3
Which results in the page showing only brand1, brand2, and brand3 listings. I also have a filter section on the side like so:
[o] Brand 1
[ ] Brand 2
[o] Brand 3
[o] Brand 4
By ticking the items, the URL will get updated with the corresponding parameters. Basically, what happens is that I am fetching data from an API by passing the URL parameters as arguments, which then the server side endpoint takes in to return to me the matching data.
Now the problem is that, if a user types into the URL an invalid parameter e.g.
https://www.someurl.com/categories/somecategory?brands=somegibberish
The server will return an error (which I then display on the page).
However, when I tick one or more of the filters, since what it does is merely append into the URL more parameters, the server will always return an error as the errant parameter is still being sent over:
https://www.someurl.com/categories/somecategory?brands=somegibberish,brand1,brand2
To solve this, currently, when someone clicks a filter and error is not null, I just clear the parameters like so:
componentDidUpdate(prevProps)
if (prevProps.location.search !== location.search) {
if (
someobject.error &&
!someobject.list.length
) {
this.props.history.replace("categories", null);
this.props.resetError();
}
}
}
Which results in the path becoming:
https://www.someurl.com/categories/
But the UX of that isn't smooth because when I click a filter (even if there was an error), I expect it to do a filter and not to clear everything. Means if I have this path previously (has an error param):
https://www.someurl.com/categories/somecategory?brands=somegibberish,brand1
..and I click on brand2 in my filters, the path should become:
https://www.someurl.com/categories/somecategory?brands=brand1,brand2
But am quite stumped as to how to know which of the parameters has to be removed. Any ideas on how to achieve it? Should the server return to me the 'id' that it cannot recognize then I do a filter? Currently, all the server returns to me is an error message.
I agree with SrThompson's comment to not support typing of brands in the app since anything outside of your list results in an error anyway.
Expose an interface with the possible brands for the user to make a selection from.
With that said, here's how you can go about filtering the brands in the request URL.
Convert the URLstring to a URL object and retrieve the value for "brands" query parameter from its search params.
const url = new URL(
"https://www.someurl.com/categories/somecategory?brands=somegibberish,brand1,brand2")
const brands = url.searchParams.get("brands")
Filter brands that are not included in the filter list
const BRAND_FILTER = ['brand1', 'brand2']
const allowedBrands = brands.split(',')
.filter(brand => BRAND_FILTER.includes(brand))
.join(',')
Update the brand query parameter value
url.searchParams.set("brands", allowedBrands)
Then get the URL to be used for the request.
const requestURL = url.toString();

Parse - limit result of a Query in Cloud Code

Hello is this code in the comment possible with Parse Cloud Code?
Parse.Cloud.beforeFind('Note', function(req) {
var query = req.query;
var user = req.user;
// if a given 'Note' visibility is set to 'Unlisted'
// return only the Notes with 'user' field that the calling _User
});
The documentation only shows how to filter fields that are returned but not exactly remove items from the query result in the Cloud Code.
This can be done through ACL, I know, but the caveat is that if the request is a retrieve function and not query the Note should still return.
Assuming you've saved the user as an object relationship (not a string id). Just add the qualification you need, such as:
query.equalTo("your_user_pointer_col_on_Note", user)

Undefined attributes in Parse

I'm using Parse to handle my backend and I'm encountering issues grabbing data from my Parse objects. I've seen many questions similar to this, but none with a straightforward answer.
My User objects have a field called groupsArray which is an array that contains Group objects. Each Group object then contains a field called groupName, which is simply the name of that particular group object.
Here is my trouble. I'm grabbing the current user via
var user = Parse.User.current();
then I grab the groupsArray and the groupNames via
var groupsArray = user.get("groupsArray");
var groupName = groupsArray[i].get("groupName");
Initially this works after I add a group, however, my problem comes after I refresh my browser. After refreshing my browser, all my groupName fields are undefined. When I try and grab their id, it works, but all the personal fields that I created for that object is undefined. When I go to my applications dashboard on parse.com, I see all the objects with their groupNames. Anyone know what's going on?
More detailed code:
Inside groups.js, which calls modelGroups.js:
$('#tester').on('click', function() {
populateSidebar();
});
Inside modelGroups.js:
function populateSidebar(){
var groupsArray = Parse.User.current().get("groupsArray");
for (var i=0; i<groupsArray.length; i++) {
var groupName = groupsArray[i].get("groupName");
console.log(groupName); // ALL of these are undefined after a browser refresh
}
}
And yes, even after refreshing the browser, Parse.User.current() is fetching the correct user, user.id, and username
It seems that the group data needs to be fetched from database again after refresh to me. Never happened on iOS since I enabled local datastore for me.

Categories