I want to use the Facebook Graph API to search for exact page matches to "My String".
I tried https://graph.facebook.com/search?q=%22My%20String%22&type=page - but it returns pages that match either "String" or "My".
How do I construct a search query that returns only exact matches to the quoted string?
Currently, you can't. It's triaged on the wishlist.
So, you'll have to wrap the request, in Python :
import requests
query = 'My String'
r = requests.get('https://graph.facebook.com/search?q=%s&type=page' % query)
result = r.json
result['data'] = [ item for item in result['data']
if query.lower() in item['name'].lower() ]
print [ item['name'] for item in result['data'] ]
Now you only have exact matches.
try using Unicode, U+0200 is the space bar, so concatenate "My", U+0200, and "String". No clue if that works.
Related
i have recently started building a bot in discord.py and got stuck in this situation here
#client.command()
async def replace(ctx, *, arg):
msg = f"{arg}" .format(ctx.message).replace('happe', '<:happe:869470107066302484>')
await ctx.send(msg)
this is a command which replaces the word "happe" with the emoji so this looks like :
Command : {prefix}replace i am very happe
Result : i am very "emoji for happe"
but i want to make it so we can replace multiple words with different emoji and not just a single one like
Command : {prefix}replace i am not happe, i am sad
Result : i am not "emoji for happe", i am "emoji for sad"
is there a way to edit multiple words in just one sentence like using a json file of making a list of emojis and its id?
also this command doesnt seems to work in cogs and says command is invalid
is there a way to edit multiple words in just one sentence like using a json file ot making a list of emojis and its id?
Yes, you can do just that. Make a list of word-emoji pairs and iterate over all of them to replace every word.
async def replace(ctx, *, arg):
l = [("happe", "<:happe:869470107066302484>"), ("sad", "..."), ...]
msg = arg # Making a copy here to avoid editing the original arg in case you want to use it at some point
for word, emoji in l:
msg = msg.replace(word, emoji)
await ctx.send(msg)
also this command doesnt seems to work in cogs and says command is invalid
In cogs the decorator is #commands.command(), not #client.command(). Don't forget the from discord.ext import commands import to get access to it.
Lastly, I'm a bit confused what f"{arg}" .format(ctx.message) is supposed to be doing? You can remove the .format and the f-string entirely. args is already a string so putting it in an f-string with nothing else has no effect, and .format(ctx.message) doesn't do anything either. The result of that entire thing is the same as just arg.
>>> arg = "this is the arg"
>>> f"{arg}".format("this has no effect")
'this is the arg'
Whenever I try to to get my query string parameter everything works but only + sign gets stripped.
Here is url file:
urlpatterns = [
re_path(r'^forecast/(?P<city>[\w|\W]+)/$', weather_service_api_views.getCurrentWeather)]
Here is view File:
#api_view(['GET'])
def getCurrentWeather(request, city):
at = request.GET["at"]
print(at)
return JsonResponse({"status": "ok"}, status=200)
So if I hit the server with this URL:
http://192.168.0.5:8282/forecast/Bangladesh/?at=2018-10-14T14:34:40+0100
the output of at is like this:
2018-10-14T14:34:40 0100
Always + sign gets stripped. No other characters get stripped. I have used characters like !, = , - etc.
Since + is a special character, you will have to encode your value. Where to encode? it depends how are you generating the values for at. Based on your URL's and endpoints it looks like you are working on a weather app and at value is generated by Javascript. You can encode your values with encodeURIComponent
let at = encodeURIComponent(<your_existing_logic>)
eg:
let at = encodeURIComponent('2018-10-14T14:34:40+0100')
it will return a result
'2018-10-14T14%3A34%3A40%2B0100'
then in your backend you can get that value with:
at = request.GET.get('at')
it will give you the desired value, 2018-10-14T14:34:40+0100 in this case.
If you are creating your at param in your backend, then there are multiple ways to achieve that. You can look into this solution:
How to percent-encode URL parameters in Python?
I have a HTML button that is supposed to sort the search results by alphabetical order.
Button HTML code:
A-Z
views.py:
def query_search(request):
articles = cross_currents.objects.all()
search_term = ''
if 'keyword' in request.GET:
search_term = request.GET['keyword']
articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity')
if request.GET.get('a-z') == 'True':
articles = articles.order_by('Title')
Currently, the URL contains the keywords searched by the user. For example, if the user searches for "cheese," the URL will be search/?keyword=cheese. When I click the sorting button, the URL becomes search/?a-z=True and loses the keyword, which means that the sorting mechanism isn't sorting the search results based on the keyword. I think I need the URL to contain both the keyword and ?a-z=True for the sorting mechanism to work on the search results. How can I make that happen?
I think this is not specific to Django only, you can use javascript to do that:
Add a function that will get the current url and do the sorting function and call that function via onclick.
Then add the necessary param.
A-Z
Then in your js part, you can check the url contains a keyword param, if not, just add the sort param.
function sort(foo) {
let url = window.location.href;
// check if current url includes a "keyword" param else add the sort as param
if(url.includes("?") && url.includes("keyword")) window.location.href = url + "&" + foo;
else window.location.href = url + "?" + foo;
}
This is just an idea and might not work since I never tried to run this.
I'm getting an unexpected result using icontains in my get_or_create call.
Take the following example:
>>>team_name = "Bears"
>>>Team.objects.get(name__icontains=team_name) # returns DoesNotExist as expected
>>>team, created = Team.objects.get_or_create(name__icontains=team_name)
>>>print(created) # Prints True as expected
>>>print(team.name) # Prints an empty string!
Why does this create a team with a blank name rather than "Bears"? The reason I'm using get_or_create here is that if a subsequent user posts something like "BearS" I want to get the correct team, not create a duplicate team with incorrect capitalization.
I think here you should split the get() and create() functionalities instead of using get_or_create(), because the __icontains lookup works for get() only.
Try doing something like this:
>>> team_name = 'Bears'
>>> teams = Team.objects.filter(name__icontains=team_name)
# This will filter the teams with this name
>>> team = teams.first() if teams.exists() else Team.objects.create(name=team_name)
# Now your team is the first element of your previous query (it returns a QuerySet with single element) if it exists
# Otherwise, you create a new Team.
Another option besides wencakisa's answer is to include the defaults parameter in get_or_create, because Django strips lookups containing the __ separator. See answers to this question.
The code would be:
Team.objects.get_or_create(
name__icontains=team_name,
defaults = {
"name": team_name
}
)
The right way to do it is using Django's function get_or_create(). But instead of "icontains", you should use "iexact" (), unless you want an exact match, in wich case you should use just "exact":
Team.objects.get_or_create(
name__iexact=team_name,
defaults = {
"name": team_name
}
)
Outside "defaults" you should put your search terms. If the objects doesn't exist, you should write your creation terms inside 'defaults'
I have a Warehouse Model which is getting index as follows
class WarehouseIndex(SearchIndex, Indexable):
"""
SearchIndex Class that stored indexes for Model Warehouse
"""
text = CharField(document=True, use_template=True)
search_auto = NgramField()
....
def get_model(self):
return WareHouse
In my shell I am running the following sqs query.
>>> sqs = SearchQuerySet().models(WareHouse)
>>> sqs.filter(customers=3).filter(search_auto='pondicherry')
This returns result consisting of results that do not have exact term pondicherry it also provides me some results that match terms like ich, che, ndi, etc.
I have even tried using __exact and Exact but all return the same result?
EDIT: Index mapping, Index Setting
How can I avoid this and provide result only of term pondicherry?
It seems to be related to this open issue
This is because your search_auto ngram field has the same index and search analyzer and hence your search term pondicherry also gets ngramed at search time. The only way to fix this is to set a different search_analyzer for your search_auto field, standard would be a good fit.
You can change your search_auto field mapping with this:
curl -XPUT localhost:9200/haystack/_mapping/modelresult -d '{
"properties": {
"search_auto": {
"type": "string",
"analyzer": "ngram_analyzer",
"search_analyzer": "standard"
}
}
}'
As #Val has stated in the above answer, the error was because search_analyzer and indexed_analyzer are same which caused the issue,
As we all know haystack is very inflexible in setting up the basic elasticsearch configuration, I installed elasticstack and in my setting.py changed the backend to it's elasticsearch_backend as suggest and additionally added the following 2 configurations
# elasticslack setting
ELASTICSEARCH_DEFAULT_ANALYZER = 'snowball'
ELASTICSEARCH_DEFAULT_NGRAM_SEARCH_ANALYZER = 'standard'
this seemed to solve my problem.