I'm making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).
I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this? Surely there is a way to do it with Python?
See the documentation on how to access the Request object and then get from this same Request object, the attribute remote_addr.
Code example
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
For more information see the Werkzeug documentation.
Proxies can make this a little tricky, make sure to check out ProxyFix (Flask docs) if you are using one. Take a look at request.environ in your particular environment. With nginx I will sometimes do something like this:
from flask import request
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
When proxies, such as nginx, forward addresses, they typically include the original IP somewhere in the request headers.
Update See the flask-security implementation. Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.
Actually, what you will find is that when simply getting the following will get you the server's address:
request.remote_addr
If you want the clients IP address, then use the following:
request.environ['REMOTE_ADDR']
The below code always gives the public IP of the client (and not a private IP behind a proxy).
from flask import request
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
print(request.environ['REMOTE_ADDR'])
else:
print(request.environ['HTTP_X_FORWARDED_FOR']) # if behind a proxy
I have Nginx and With below Nginx Config:
server {
listen 80;
server_name xxxxxx;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://x.x.x.x:8000;
}
}
#tirtha-r solution worked for me
#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/', methods=['GET'])
def get_tasks():
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
else:
return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0', port=8000)
My Request and Response:
curl -X GET http://test.api
{
"ip": "Client Ip......"
}
The user's IP address can be retrieved using the following snippet:
from flask import request
print(request.remote_addr)
httpbin.org uses this method:
return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))
If you use Nginx behind other balancer, for instance AWS Application Balancer, HTTP_X_FORWARDED_FOR returns list of addresses. It can be fixed like that:
if 'X-Forwarded-For' in request.headers:
proxy_data = request.headers['X-Forwarded-For']
ip_list = proxy_data.split(',')
user_ip = ip_list[0] # first address in list is User IP
else:
user_ip = request.remote_addr # For local development
Here is the simplest solution, and how to use in production.
from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
# Set environment from any X-Forwarded-For headers if proxy is configured properly
app.wsgi_app = ProxyFix(app.wsgi_app, x_host=1)
#app.before_request
def before_process():
ip_address = request.remote_addr
Add include proxy_params to /etc/nginx/sites-available/$project.
location / {
proxy_pass http://unix:$project_dir/gunicorn.sock;
include proxy_params;
}
include proxy_params forwards the following headers which are parsed by ProxyFix.
$ sudo cat /etc/nginx/proxy_params
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
If You are using Gunicorn and Nginx environment then the following code template works for you.
addr_ip4 = request.remote_addr
This should do the job.
It provides the client IP address (remote host).
Note that this code is running on the server side.
from mod_python import apache
req.get_remote_host(apache.REMOTE_NOLOOKUP)
I did not get any of the above work with Google Cloud App Engine. This worked, however
ip = request.headers['X-Appengine-User-Ip']
The proposed request.remote_addr did only return local host ip every time.
Related
I work on a Django project + django-rest-framework. On localhost, PATCH requests work perfectly fine. However, on server, PATCH requests do not work. I get a 400 Bad request error. I use nginx to configure the web server.
Here is my configuration:
server {
listen 80;
server_name x.y.z.com;
root /var/www/path-to/project;
location / {
error_page 404 = 404;
proxy_pass http://127.0.0.1:5555/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_intercept_errors on;
}
}
I get this error when I try PATCH requests on server :
How can I make so that django accept PATCH requests? The log does not show anything. As if it does not even receives the request. I run the django server like this:
python manage.py runserver 5555
Friend, I faced this problem, I made all the possible settings in nginx, but the problem was in my js fetch that tried with the patch method in lowercase, 'patch', changing to 'PATCH' worked normally.
I am using Flask and when developing locally, all this works fine. However, when deployed using nginx with a proxy pass through gunicorn, the url_for seems to be adding a trailing / to the url which is causing errors when pulling the json data off the url. Here's the relevant code:
#app.route('/save', methods=['POST'])
def save():
name = request.form['name'];
email = request.form['email']
data = json.dumps({"name": name, "email": email})
return redirect(url_for('.record', data=data))
#app.route("/record")
def record():
// error here because of trailing /
data = json.loads(request.args['data'])
//... more code
I'm pretty new to using Flask and super new to gunicorn so if I'm missing any required info to get help, just let me know. Here's the proxy_pass config in nginx:
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
And then I'm just running gunicorn as a service with:
gunicorn --bind 0.0.0.0:8000 app:app
Example breaking URL
https://<ipaddress>/record?data=%7B%22name%22%3A+%22fdaf%22%2C+%22email%22%3A+%22fsd%40sfd.com%22%7D/
I'm writing a website with Flask. I use Flask-Secuirty to do authentication. I use nginx + gunicorn to deploy it.
The configuration of nginx as follow:
server{
listen 80;
server_name project.example.com;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
}
}
And I use gunicorn -w worker_number -k gevent run:app -p app.pid -b 127.0.0.1:5000 to start gunicorn.
If the worker_number is 1, everything is ok.
If the worker_number is greater than 1 like 3, I can't login in with Flask-Security.
The output of server said the post request of login is 200. But the server redirect me to login page again.
After some search, I can't find direct reason of this. And I guess this might cause by SERVER_NAME config of Flask or the misuse of Flask-SQLAlchemy.
Is there anyone has met this situation before? Please give me some advices.
I met a similar problem with flask_login, when the worker_number is greater than 1, I could not login in.
My app.secret_key was set to os.urandom(24), so every worker will have another secret key.
Set app.secret_key to a string solved my problem.
Just use a fixed secret key.
Generate with following command.
$ openssl rand -base64 <desired_length>
If you don't want to hardcode the key inside source code which you shouldn't for security purposes.
Set up an environment variable and get it.
import os
# -- snip --
app.config["SECRET_KEY"] = os.environ.get("FLASK_APP_SECRET_KEY")
Use something like Flask-Session and use Redis as a session store. I'm not sure how Flask-Security works, but I assume it relies on Flask sessions, in which case it would solve the problem of a user session switching between application servers.
http://stackoverflow.com/questions/3110919/how-do-i-get-the-client-ip-of-a-tornado-request
Above link tells us how we could derive the Client IP for a Request Handler. What about while using a Websocket Handler?
Thanks.
The class WebSocketHandler extends RequestHandler
class WebSocketHandler(tornado.web.RequestHandler):
So, you can get the ip in this way:
class SocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
logging.info('Client IP:' + self.request.remote_ip)
if you used nginx as proxy server, the situation will be a little more complex, there are two solutions:
option 1: using self.request.remote_ip
if you insist using this method, you need to configure both nginx and your tornado app.
step 1: in nginx server block add either of fllowing lines:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
or
proxy_set_header X-Real-Ip $remote_addr;
step 2: when creating tornado httpserver, add xheader option
server = httpserver.HTTPServer(application, xheaders=True)
then you can use self.request.remote_ip to get your remote ip address now
option 2: get X-Real-Ip from HttpRequest headers
following code will give you remote real ip directly:
self.request.headers.get('X-Real-Ip', '')
I've got a flask app daemonized via supervisor. I want to proxy_pass a subfolder on the localhost to the flask app. The flask app runs correctly when run directly, however it gives 404 errors when called through the proxy. Here is the config file for nginx:
upstream apiserver {
server 127.0.0.1:5000;
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://apiserver;
proxy_next_upstream error timeout http_502;
proxy_buffering off;
}
For instance, when I go to http://127.0.0.1:5000/me, I get a valid response from the app. However when I go to http://127.0.0.1/api/me I get a 404 from the flask app (not nginx). Also, the flask SERVER_NAME variable is set to 127.0.0.1:5000, if that's important.
I'd really appreciate any suggestions; I'm pretty stumped! If there's anything else I need to add, let me know!
I suggest not setting SERVER_NAME.
If SERVER_NAME is set, it will 404 any requests that don't match the value.
Since Flask is handling the request, you could just add a little bit of information to the 404 error to help you understand what's passing through to the application and give you some real feedback about what effect your nginx configuration changes cause.
from flask import request
#app.errorhandler(404)
def page_not_found(error):
return 'This route does not exist {}'.format(request.url), 404
So when you get a 404 page, it will helpfully tell you exactly what Flask was handling, which should help you to very quickly narrow down your problem.
I ran into the same issue. Flask should really provide more verbose errors here since the naked 404 isn't very helpful.
In my case, SERVER_NAME was set to my domain name (e.g. example.com).
nginx was forwarding requests without the server name, and as #Zoidberg notes, this caused Flask to trigger a 404.
The solution was to configure nginx to use the same server name as Flask.
In your nginx configuration file (e.g. sites_available or nginx.conf, depending on where you're defining your server):
server {
listen 80;
server_name example.com; # this should match Flask SERVER_NAME
...etc...