I have this code:
def signup(fname, email, password):
user={
"name": fname,
"email":email,
"password":password
}
@app.route('/', methods =["GET", "POST"])
def login():
if request.method == "POST":
name = request.form.get("fname")
email = request.form.get("email")
password = request.form.get('password')
signup(name, email, password)
return redirect(url_for('user_blueprint.main', usr = name))
return render_template('form.html')
Blueprint:
@user.route('/<usr>')
def main(usr):
return f'Hello {usr}'
When I get to the page the url changes to ip/user/username, and if I change the 'username' of the url my html (which returns the name) also changes, can anyone tell me how to make my page no change? I dont mind if my url doesn't have to contain the username, but when i dont put it, flask gives me the error 'missing arguments'.
CodePudding user response:
As you're missing some part of the code, I'll assume some stuff, and then you can write a comment if I need to change stuff.
@user
that you use in the second part of the code is user_blueprint
and I assume you've registered it with the user
prefix in the main application. So let me explain how you get URL <IP>/user/<username>
.
When you call url_for(user_blueprint.main, usr = name)
flasks looks for the blueprint and how it is registered, so it gets the prefix user
from your configuration, then it replaces parameter usr
in the only route you've registered, that is how you get /user/<username>
.
So if you want to have unique URL then you need to remove usr
from URL and try to pass name
some other way (e.g. session). Here is example of code (just needed parts):
from flask import session
@app.route('/', methods =["GET", "POST"])
def login():
if request.method == "POST":
...
session['usr'] = name
return redirect(url_for('user_blueprint.main'))
return render_template('form.html')
...
@user.route('/')
def main():
return f'Hello {session['usr']}'
If you chose to use session
here is a useful link that you need to check before starting using session.