1

I'm trying to implement the get_my_ip() method from flask. I'm getting an unresolved reference despite importing the relevant packages. I found solutions for similar issues that say that I have folder named 'app', which causes the problem, but I couldn't find such folder.

The code:

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

The function is called as follows:

with open('file.txt, 'a') as f:
    f.write(f'ip: {get_my_ip()}')

Thanks.

random
  • 146
  • 2
  • 10
  • 2
    You haven't actually defined `app`. It's not a folder, it's a `Flask` object that you need to create – roganjosh Jul 26 '20 at 11:55
  • You mean calling the function? I added a function call now. – random Jul 26 '20 at 12:00
  • Oof, I'm not sure what that edit is about but it definitely isn't what I was suggesting. So you want the app route to write to a file? – roganjosh Jul 26 '20 at 12:05
  • 1
    Actually, I'm utterly confused now. You're trying to piggyback on Flask to grab an IP but you don't want to run an actual application? I guess it's an ingenious concept, but I can't think of any way to make that work. – roganjosh Jul 26 '20 at 12:09
  • I'm writing a server and I need to get users' ip. From what I found, the only way to do that is with flask. That's the only reason I'm trying to use flask. – random Jul 26 '20 at 12:17
  • This looks like it is trying to debug a weird server setup, if that is true you might look into [ServerFault.SE](https://serverfault.com/tour) which focuses on IT systems within business environments (like servers) – LinkBerest Jul 26 '20 at 12:44
  • 1
    It seems you got that code from this answer: https://stackoverflow.com/a/3760309/2745495. That answer does not show how a Flask `app` instance is supposed to be created first (since that wasn't the point of that Q&A). See Flask's [Minimal Application](https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application) tutorial to understand what `app` is and how to create it. – Gino Mempin Jul 26 '20 at 14:09

1 Answers1

0

To answer the question title

You haven't actually defined app. You can't use the decorator to add routes to an application that you haven't even defined.

from flask import Flask, request, jsonify

app = Flask(__name__) # See here

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

I strongly suggest The Flask Megatutorial because this is a fundamental misunderstanding.


To answer what you're trying to do - this is horribly misguided. You're trying to snag on to some functionality from Flask without actually running an application. Flask is not a server. You could have any number of levels of actual servers before things got to the level of your code. For example, Apache or Nginx, then gunicorn. All of those could capture the IP.

roganjosh
  • 12,594
  • 4
  • 29
  • 46