I am loading an 'index.html' page where the URL might be http://127.0.0.1:5000/?ip_address=192.168.2.36.
The variable ip_address can change when I get to index.html.
I have a form with a submit button that should send the value of ip_address to the controller. My goal is to, be default, set the input field box with the variable ip_address and leave it greyed out, so the user only hits the button.
Is there a way I can get that variable from the URL?
Thanks.
CodePudding user response:
@app.route("/")
def home():
return "<h1> Hello World</h1>"
url_for("home" _external=True)
the url_for with the option "_external" set to True will crate the url with the IP address.
CodePudding user response:
I'm not sure if I understood your question correctly.
The following example displays the client's IP address in a text field and sends it to the server. A possibly used proxy or load balancer is taken into account. However, the display of the correct address is not guaranteed.
If an IP is already specified in the URL, this will be used to fill in the text field.
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
ip_address = request.args.get('ip_address',
request.headers.get('X-Forwarded-For', request.remote_addr).split(', ')[0])
return render_template('index.html', **locals())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<form method="get">
<input type="text" name="ip_address" value="{{ip_address}}" />
<input type="submit" />
</form>
</body>
</html>