0

I have the minimal flask app as:

from flask import Flask
app = Flask(__name__)

@app.route('/index')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__': 
    app.run() 

On running the app(locally) it open's on http://127.0.0.1:5000 and have to add /index explicitly to show 'Hello, World!'

But , Is there a way to directly open with /index added ?

I have seen other examples and I tried with another decorator as :

@app.route('/')
@app.route('/index')
def hello_world():
    return 'Hello, World!'

This open's the same /index with out explicitly adding it, but I need to have the trailing /index added in URL and show the Hello, World ....Hope this Q makes sense

Any help is appreciated , TIA

KcH
  • 3,302
  • 3
  • 21
  • 46
  • you need to do when hit http://127.0.0.1:5000 automatically its redirect to /index or its should call hello_world function same /index? – Avinash Dalvi Mar 10 '20 at 04:59
  • on run , it should directly open with http://127.0.0.1:5000/index instead of explicitly adding /index by us – KcH Mar 10 '20 at 05:01
  • 1
    https://stackoverflow.com/questions/13678397/python-flask-default-route-possible see this can help you. – Avinash Dalvi Mar 10 '20 at 05:04
  • @aviboy2006 Thanks mate for the reference , would look into that – KcH Mar 10 '20 at 05:16

1 Answers1

3

You need to redirect all requests to '/' to '/index'.

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('hello_world'), code=302)

@app.route('/index')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__': 
    app.run() 
Farzan Hajian
  • 1,799
  • 17
  • 27
  • Hey thanks mate , but may I know what does `code = 302` here represents ? – KcH Mar 10 '20 at 05:15
  • 1
    its HTTP redirection code. Its moving The HTTP response status code 302 Found is a common way of performing URL redirection – Avinash Dalvi Mar 10 '20 at 05:16
  • Do we usually use this way to land in to the home page on running the app? – KcH Mar 10 '20 at 05:21
  • 1
    Dear @Codenewbie, 302 is one of HTTP redirecting codes. I found a good explanation at https://www.contentkingapp.com/academy/redirects/ Check it out if to know about them but mostly 301 and 302 are used. – Farzan Hajian Mar 10 '20 at 05:28
  • Hey @FarzanHajian that's a good link thanks for sharing , also it mentioned two points 1) Use a 302 redirect for inactive campaigns. 2) Use a 301 redirect for content that’s permanently removed. As we just want to land home page as soon as we run does this `codes 301 & 302 ` have impact ? – KcH Mar 10 '20 at 05:41
  • Technically there is not difference between the two. They just express different intentions for the redirect command and mainly used by tools like web crawlers and so on. In this case, I think you'd better go with 301 – Farzan Hajian Mar 10 '20 at 05:55
  • @FarzanHajian sure mate !! – KcH Mar 10 '20 at 05:56