0

I'm creating a news application. Using flask on the backend. The server has news from many countries. I want to show the user news from their country if it has news.

I've tried getting the IP address of the user with flask.request.remote_addr but it always gives 127.0.0.1 (localhost). I want to know the actual address.


from flask import Flask, render_template, jsonify, request
from x import IPINFO_API_KEY, DEFAULT_COUNTRY

def get_user_country(ip_address):
    ipinfo_handler = getHandler(IPINFO_API_KEY)
    details = ipinfo_handler.getDetails(ip_address)
    return details.country

@app.route('/api/user_country')
def get_user_country():
    # Get the client's IP address
    ip_address = request.remote_addr
    print( f'ipaddress: { ip_address }')
    # If the client is accessing the site locally, return the default country
    if ip_address in ('127.0.0.1', '::1', 'localhost'):
        return jsonify({'country': DEFAULT_COUNTRY})
    
    # Use a third-party API to get the user's country based on their IP address
    response = requests.get(f'https://ipinfo.io/{ip_address}/country?token={IPINFO_API_KEY}')
    if response.status_code == 200:
        country_code = response.text.strip()
        return jsonify({'country': country_code})
    else:
        return jsonify({'error': f'Unable to retrieve country information for IP address {ip_address}'})

M Z
  • 4,571
  • 2
  • 13
  • 27
Hex Heager
  • 107
  • 7

1 Answers1

0

A solution is provided here: Flask request.remote_addr is wrong on webfaction and not showing real user IP

if not request.headers.getlist("X-Forwarded-For"):
   ip = request.remote_addr
else:
   ip = request.headers.getlist("X-Forwarded-For")[0]

The reasoning and warning is explained here: https://esd.io/blog/flask-apps-heroku-real-ip-spoofing.html

Hex Heager
  • 107
  • 7