Search code examples
pythonflaskroutesdynamic-routing

Flask dynamic route is taking values which I have not specified


Question

I have created a dynamic route as /update/<randomString> in my Flask app.py file, where randomString is a randomly generated string with the length of 50. However if I search for /update/1 I am able to view the same dynamic route /update/<randomString> without any error! Can anyone explain why is it so?

See what I've tried so far:

@app.route('/')
def index():
 randomString = ''.join(secrets.choice(string.ascii_uppercase+string.digits+string.ascii_lowercase) for k in range (50))
 session['randomString'] = str(randomString)
 return render_template('index.html')

@app.route('/update/<randomString>')
def update(randomString):
 if 'randomString' in session:
  randomString = session['randomString']
  return render_template('update.html')
 else:
  return 'error...'

Link of the dynamic page at update.html page, where random string is passed with the help of session(defined at index.html page).

<a href="update/{{randomString}}">Dynamic page</a>

Edit: I am also able to view dynamic route when I click on the link defined above and my URL section shows that long randomString. Problem is: I can access the same route when I search for http://127.0.0.1:5000/update/1

Screenshot one

enter image description here

Screenshot two

enter image description here


Solution

  • While storing the random string, the key you use is randomString. So you are storing the random string in a dict like

    session['randomString'] = '1234567890'
    

    Then when you access the session in the /update route you are just checking if session has a key named randomString. You should also check if session['randomString'] == '1234567890' and render the page only if the random string in session is the same as you created in the / path. You can replace the if with

    if 'randomString' in session and session['randomString'] == randomString :