OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

My Flask application continues to generate all of its Ip Addresses with the city and country as 'Unknown', 'Unknown'

  • Thread starter Thread starter BackOut
  • Start date Start date
B

BackOut

Guest
I am currently making a Flask application as a side project which generates random IP addresses with the city and country included. My problem is, the city and country keeps returning 'Unknown', 'Unknown'. Can anyone help me prevent this from happening? All help will be greatly appreciated.

My code:

Code:
from flask import Flask, jsonify, render_template_string
from requests import get, RequestException
from random import randint

app = Flask(__name__)

class GenerateIp:
    ips = []

    def __init__(self) -> None:
        self.ip = self.GenerateNewIp()
        self.city, self.country = self.GetGeolocation(self.ip)
        
        GenerateIp.ips.append(self.ip)

    def GenerateNewIp(self) -> str:
        while True:
            ip_parts = []
            
            for _ in range(4):
                rand_num = randint(0, 2)
                
                ip_parts.append(str(randint(0, 255))) if rand_num == 0 else \
                ip_parts.append(str(randint(0, 99))) if rand_num == 1 else ip_parts.append(str(randint(0, 9)))
            
            new_ip = '.'.join(ip_parts)
            
            if new_ip not in GenerateIp.ips:
                return new_ip

    def GetGeolocation(self, ip: str) -> tuple[str, str]:
        while True:
            try:
                response = get(f'http://ipinfo.io/{ip}/json')
                data = response.json()
                city, country = data.get('city', 'Unknown'), data.get('country', 'Unknown')
                break
            
            except:
                ip = self.GenerateNewIp
        
        return city, country

@app.route('/')
def index():
    return render_template_string('''
        <!doctype html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            
            <title>IP Generator</title>
        </head>
        <body>
            <h1>Randomly Generated IP Addresses</h1>
            
            <button onclick="generateIps()">Generate IPs</button>
            <ul id="ip-list"></ul>
            
            <script>
                function generateIps() {
                    fetch('/generate_ips')
                        .then(response => response.json())
                        .then(data => {
                            const ipList = document.getElementById('ip-list');
                            ipList.innerHTML = '';
                            data.forEach(ip => {
                                const li = document.createElement('li');
                                li.textContent = `${ip.ip} - ${ip.city}, ${ip.country}`;
                                ipList.appendChild(li);
                            });
                        });
                }
            </script>
        </body>
        </html>
    ''')

@app.route('/generate_ips')
def generate_ips():
    ip_addresses = []
    
    for _ in range(randint(5, 10)):
        new_ip = GenerateIp()
        ip_addresses.append({'ip': new_ip.ip, 'city': new_ip.city, 'country': new_ip.country})
    
    return jsonify(ip_addresses)

if __name__ == '__main__':
    app.run(debug=True, port=5000)


What I want:

Randomly Generated IP Addresses​

  • 2.29.9.14 - [City], [Country]
  • 24.6.4.2 - [City], [Country]
  • 136.12.67.8 - [City], [Country]
  • 5.20.168.91 - [City], [Country]
  • 4.79.212.46 - [City], [Country]
  • 2.78.98.44 - [City], [Country]


What I got:

Randomly Generated IP Addresses​

  • 2.29.9.14 - 'Unknown', 'Unknown'
  • 2.78.98.44 - 'Unknown', 'Unknown'
  • 4.79.212.46 - 'Unknown', 'Unknown'
  • 5.20.168.91 - 'Unknown', 'Unknown'
  • 136.12.67.8 - 'Unknown', 'Unknown'
  • 24.6.4.2 - 'Unknown', 'Unknown'
<p>I am currently making a Flask application as a side project which generates random IP addresses with the city and country included. My problem is, the city and country keeps returning 'Unknown', 'Unknown'. Can anyone help me prevent this from happening? <em>All help will be greatly appreciated.</em></p>
<p>My code:</p>
<pre><code>from flask import Flask, jsonify, render_template_string
from requests import get, RequestException
from random import randint

app = Flask(__name__)

class GenerateIp:
ips = []

def __init__(self) -> None:
self.ip = self.GenerateNewIp()
self.city, self.country = self.GetGeolocation(self.ip)

GenerateIp.ips.append(self.ip)

def GenerateNewIp(self) -> str:
while True:
ip_parts = []

for _ in range(4):
rand_num = randint(0, 2)

ip_parts.append(str(randint(0, 255))) if rand_num == 0 else \
ip_parts.append(str(randint(0, 99))) if rand_num == 1 else ip_parts.append(str(randint(0, 9)))

new_ip = '.'.join(ip_parts)

if new_ip not in GenerateIp.ips:
return new_ip

def GetGeolocation(self, ip: str) -> tuple[str, str]:
while True:
try:
response = get(f'http://ipinfo.io/{ip}/json')
data = response.json()
city, country = data.get('city', 'Unknown'), data.get('country', 'Unknown')
break

except:
ip = self.GenerateNewIp

return city, country

@app.route('/')
def index():
return render_template_string('''
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">

<title>IP Generator</title>
</head>
<body>
<h1>Randomly Generated IP Addresses</h1>

<button onclick="generateIps()">Generate IPs</button>
<ul id="ip-list"></ul>

<script>
function generateIps() {
fetch('/generate_ips')
.then(response => response.json())
.then(data => {
const ipList = document.getElementById('ip-list');
ipList.innerHTML = '';
data.forEach(ip => {
const li = document.createElement('li');
li.textContent = `${ip.ip} - ${ip.city}, ${ip.country}`;
ipList.appendChild(li);
});
});
}
</script>
</body>
</html>
''')

@app.route('/generate_ips')
def generate_ips():
ip_addresses = []

for _ in range(randint(5, 10)):
new_ip = GenerateIp()
ip_addresses.append({'ip': new_ip.ip, 'city': new_ip.city, 'country': new_ip.country})

return jsonify(ip_addresses)

if __name__ == '__main__':
app.run(debug=True, port=5000)
</code></pre>
<hr />
<p>What I want:</p>
<h2>Randomly Generated IP Addresses</h2>
<ul>
<li>2.29.9.14 - [City], [Country]</li>
<li>24.6.4.2 - [City], [Country]</li>
<li>136.12.67.8 - [City], [Country]</li>
<li>5.20.168.91 - [City], [Country]</li>
<li>4.79.212.46 - [City], [Country]</li>
<li>2.78.98.44 - [City], [Country]</li>
</ul>
<hr />
<p>What I got:</p>
<h2>Randomly Generated IP Addresses</h2>
<ul>
<li>2.29.9.14 - 'Unknown', 'Unknown'</li>
<li>2.78.98.44 - 'Unknown', 'Unknown'</li>
<li>4.79.212.46 - 'Unknown', 'Unknown'</li>
<li>5.20.168.91 - 'Unknown', 'Unknown'</li>
<li>136.12.67.8 - 'Unknown', 'Unknown'</li>
<li>24.6.4.2 - 'Unknown', 'Unknown'</li>
</ul>
 

Latest posts

Top