flask app searching logic for similar word - python

I am a flask beginner and recently I am doing my first project which is searching cocktails using flask and API.
So, here is the snippet of my flask code
#app.route('/search' ,methods=[ "POST"])
def search():
value = request.form['search']
cocktailAPI = requests.get(
f'https://www.thecocktaildb.com/api/json/v1/1/search.php?s={value}'
)
value = request.form['search']
print(value)
return f'ff'
My thought is like searching things on google, no matter what I am typing google can find the most relative information for me.
Is it possible to do that? for instance, if I type 'margarite' in which 'margarita' is correct, the flask will try to find the correct word in my API and give me a response.
Thank you!

What you're trying to achieve is called fuzzy search, and is a whole problem on its own.
This is not so hard though, considering that the list of existing cocktails is quite already known.
So here a way you could follow:
Build a list of existing cocktail names; you could for instance retrieve the whole list through Thecocktaildb API (though it requires a contribution), or create a list manually (as this is not likely to evolve much)
Once user enters a name, return the closest cocktail names from your list, using some distance metrics of your own (Wikipedia article provides some clues)
Request Thecocktaildb API for this cocktail.
Happy coding!

Related

How To Search For Specific Definition in Dictionary API

I am a super beginner and decided to try to create a project where I have to use an API so that I can advance my skills. I feel like I am in way over my head though I am sure this task would be simple for an advanced programmer.
I am using the Merriam Webster's Dictionary API to try to define some Spanish song lyrics. Through using the lyricsgenius module I was able to print the lyrics to a song, and now my issue is figuring out how to use the dictionary API to pull the definition for a specific word that I give it, and print it out. All I have done so far is this:
import requests
response = requests.get('https://dictionaryapi.com/api/v3/references/spanish/json/test?key=mykey').json()
print(response)
When I run this I get what seems to be to be a huge array of dictionaries filled with data that I do not understand, and I am very confused what I am supposed to do in order to get the result that I want. Am I supposed to alter the URL to let it know what specific information I want? How do I even go about figuring out what to do? The API Documentation site is also very difficult to understand as a beginner. Thank you for your help.

How to create a URL shortner (with python) without importing bittly or other stuff

So I recently became interested into knowing how to create a URL shortener without using bittly or other things, but I am not very good at using python to connect with other stuff. All I know is:
Checking to see if the URL is available ( Only to see if it has HTTP:// and unavailable characters, nothing to see if the domain is occupied or not. )
All of the other things... I need help with.
By the way, I COMPLETLY do not understand how to do that, so it would be great if you add comments to show me what is going on.
I suggest you take a look at Flask, it is a framework for building web applications (APIs, web apps, etc.).
DigitalOcean has a nice tutorial on this.
You can either use hashing algorithms for the custom shortened urls, or even let the user pick more readable names (like bit.ly/my-url). In this case you would be storing in a database the shortened url and the long url.

using EVE Python api for request and response

I am trying to use the EVE api with python 3. This is for the first time I am trying to use the API. So what I am trying to do and achieve is given below:
I have a list of name of people. for example:
Adam Gilchrist
Adam Barbar
Adam lobiof
Jaffer Wilson
Janet Wilson
Jane Cold
And many others. I am using the fuzzywuzzy python library. I have loaded these names into an array and using the library function for predicting the approx match of the string from the names using their email address names. For example:
adam.barbar#example.com is the exampe I have taken. Now, I have written the code for match the string adam.barbar with the name list that I have mentioned above.
I get the approx answers as expected.
Now where is the problem one might think. So here it is:
I want to fetch the response from the API as:
http://127.0.0.1/people/?email=adam.barbar#example.com
and get the response as the answer of fuzzywuzzy library as json to display on the screen.
I am not using any Database as such and all the names are available in the file format currently.
I have search and research about the usage of the EVE API, but could not find the usage as per my requirement. Where ever I searched for the solution I came across MongoDB or any other database. My requirement is database less.
So I want to know in the above mentioned condition, What need to be done if I want to use the Eve API
I am not using any Database as such and all the names are available in the file format currently.
As you are not using a database, you can use plain flask to solve your problem. It can easily return json for any request with the aptly named jsonify:
from flask import Flask, jsonify, make_response, request
def your_normal_code_here(email):
return something
app = Flask(__name__)
#app.route('/api/v1.0/people', methods=['GET'])
def people_api():
email = request.args.get('email')
if email is None:
make_response(jsonify({'error': 'Missing email parameter'}), 400)
return jsonify(your_normal_code_here(email))
For more robustness and completeness of your API, try using a lightweight framework like flask-restful.

Dynamically add URL rules to Flask app

I am writing an app in which users will be able to store information that they can specify a REST interface for. IE, store a list of products at /<username>/rest/products. Since the URLs are obviously not known before hand, I was trying to think of the best way to implement dynamic URL creation in Flask. The first way I thought of would be to write a catch-all rule, and route the URL from there. But then I am basically duplicating URL routing capabilities when Flask already has them built-in. So, I was wondering if it would be a bad idea to use .add_url_rule() (docs here, scroll down a bit) to attach them directly to the app. Is there a specific reason this shouldn't be done?
Every time you execute add_url_rule() the internal routing remaps the URL map. This is neither threadsafe nor fast. I right now don't understand why you need user specific URL rules to be honest. It kinda sounds like you actually want user specific applications mounted?
Maybe this is helpful: http://flask.pocoo.org/docs/patterns/appdispatch/
I have had similar requirement for my application where each endpoint /<SOMEID>/rest/other for given SOMEID should be bounded to a different function. One way to achieve this is keeping a lookup dictionary where values are the function that handle the specific SOMEID. For example take a look at this snippet:
func_look_up_dict = {...}
#app.route('<SOMEID>/rest/other', methods=['GET'])
def multiple_func_router_endpoint(SOMEID):
if SOMEID in func_look_up_dict.keys():
return jsonify({'result' = func_look_up_dict[SOMEID]()}), 200
else:
return jsonify({'result'='unknown', 'reason'='invalid id in url'}), 404
so for this care you don't really need to "dynamically" add url rules, but rather use a url rule with parameter and handle the various cases withing a single function. Another thing to consider is to really think about the use case of such URL endpoint. If <username> is a parameter that needs to be passed in, why not to use a url rule such as /rest/product/<username> or pass it in as an argument in the GET request?
Hope that helps.

Python: Store a num in Google App Engine

I am using Google App Engine Python.
I would like to store a simple variable number somewhere, so I can add, deduct and use this number.
examplenum=5
example+=1
Next time I use this examplenum, it wil become 6.
I know I can build a Model and add an IntegerProperty varible. But I guess that would be too much hassle because I only need one simple number not a model.
I have also read this question Simplest way to store a value in Google App Engine Python?, the memcache solution is not good for me. I want the number to stay forever not just temporary in the memcache.
Thanks a lot.
All the answers to the question you linked are relevent to you. If you want persistance you will have to create a model. Look at using get_or_insert to fetch/initialize an entity and give your entity a key_name so that you can keep fetching it easily whenever you need to store your values.
class MyAppData(db.Model):
my_number = db.IntegerProperty()
# fetch entity whenever you need to store your value
data = MyAppData.get_or_insert(key_name='mydata', my_number=1)
data.my_number += 1
data.put()
You code does look suspiciously like a counter, and you might want to look at the sharding countering article and the problems that it solves in case they are relevent.

Categories