Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

python - Flask redirect method redirecting to localhost

I am using apache2 and gunicorn to deploy my flask app, but whenever I use redirect method. it's redirecting to 127.0.0.1.

@module.route("/login", methods=["GET", "POST"])
def u():
    if request.method == "GET":
        return render_template("admin/login.html")
    
    username = request.form.get("username")
    password = request.form.get("password")

    for user in users:
        if username == user["username"] and password == user["password"]:
            session["user"] = user
            return redirect(url_for("admin.stories", num=1))
    
    return redirect(url_for("admin.u"))

as you can see when wrong username or password entered I am redirecting to itself, when the redirect happen, its going to https://127.0.0.1/admin/login

/etc/systemd/system/app.service

[Unit]
Description=Gunicorn instance to serve flask application
After=network.target

[Service]
User=anyms
Group=www-data
WorkingDirectory=/home/anyms/src/
Environment="PATH=/home/anyms/venv/bin"
ExecStart=/home/anyms/venv/bin/gunicorn --config gunicorn_config.py wsgi:app

[Install]
WantedBy=multi-user.target

/etc/apache2/sites-available/app.conf

<VirtualHost *:80>
    ServerAdmin anyms@ubuntu

    ErrorLog ${APACHE_LOG_DIR}/flask-error.log
        CustomLog ${APACHE_LOG_DIR}/flask-access.log combined

    <Location />
        ProxyPass unix:/home/anyms/src/app.sock|http://127.0.0.1/
        ProxyPassReverse unix:/home/anyms/src/app.sock|http://127.0.0.1/
    </Location>
</VirtualHost>
question from:https://stackoverflow.com/questions/65951531/flask-redirect-method-redirecting-to-localhost

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error seems to be on this line return redirect(url_for("admin.u")). You said you are redirecting to itself but I don't think that's what you're doing.

You are trying to use url_for for a blueprint_name.function_name scenario but from this line @module.route("/login", methods=["GET", "POST"]) it is clear that your current blueprint is module not admin as you wrote in url_for("admin.u").

I suggest you change this line return redirect(url_for("admin.u")) to:

return redirect(url_for("module.u"))

#OR EVEN MUCH SIMPLER

return redirect(url_for(".u"))

or as I'm guessing that there is a admin blueprint somewhere and that this line @module.route("/login", methods=["GET", "POST"]) was intended to be:

@admin.route("/login", methods=["GET", "POST"])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...