'Python Flask: limit requests sent to API
I'm new to Flask and I'm creating a website with the following functionality: I want to retrieve the user location and store it in a database in order to build some analytics about the website audience (and eventually, also include some degree of personalisation according to the user location).
In order to do so I'm using an external API (https://ipinfo.io) and my goal would be to send a GET request to this API, with the user IP address every time somebody logs in my website.
My current approach is this:
def get_my_ip():
# Get user id
ip_address = request.remote_addr
# Retrieve user location data
location_details = get_ip_location_details(ip_address="80.57.40.203", access_token=ACCESS_TOKEN)
# Store data in the database
webview = WebsiteView(**location_details)
db.session.add(webview)
db.session.commit()
And I'm passing this function to all my routes along with their function for rendering the templates.
# Home route
@app.route("/")
def home():
get_my_ip()
return render_template('home.html')
This actually works but sometimes the website sends multiple requests to the external API when somebody logs in or refresh the page (even though the user interaction with the website is the same and all the requests are successful)
I would like to store this information only once every time somebody logs in the website and in order to do so the only idea I got is putting some constraints in the database to not keep track of the same user in multiple records, but what I would also like to do is sending the least amount of requests to the Ipinfo API.
Is this something possible to tell the website to wait for the response of request before sending new ones?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
