-1

So essentially I'd like to be able to type in the URL e.g. http://example.com/"something", and if there is nothing render the index.html. For some reason that isn't working. On the other side i'd like to be able to pass that parameter, e.g. http://example.com/host123 and use that in the result function below. Ideally in the end I am able to simply type in the URL example.com/host123 and take me directly to that page.

@app.route('/<host>',methods= ['POST', 'GET'])
     15 def index(host):    
     16         if host is None:
     17                 return render_template("index.html")
     18         else:
     19                 return result(host)
     20         print("test")   
     21 @app.route('/<host>',methods= ['POST', 'GET'])
     22 def result(host):
#some code....

1 Answers1

2

From you question it seems you are trying to (#1) render the index.html template if host is not defined, else render a different template. From your code, however, it seems that you may actually want to (#2) redirect to another endpoint if host is defined.

If you are trying #1, you are pretty close. Don't make the result function a route, render and return the template you want from that function, then return it from the view. Something like this:

@app.route('/',methods= ['POST', 'GET'])
@app.route('/<host>',methods= ['POST', 'GET'])
def index(host=None):    

    if host is None:
        return render_template('index.html')
    else:
        return result(host)

def result(host):
    ...
    return render_template('other_template.html')

I also showed how to explicitly route the "host is nothing" case with a second decorator (docs here).

If you are trying to implement #2, then look at the Flask.redirect function and redirect to the desired endpoint/url. Keep in mind that your code currently shows two view functions responding to the same variable url path. You should use unique urls so that your app can resolve them correctly (you can find more about this here. Try something like this:

@app.route('/',methods= ['POST', 'GET'])
@app.route('/<host>',methods= ['POST', 'GET'])
def index(host):    

    if host is None:
        return render_template('index.html')
    else:
        return redirect(url_for('result', host=host))

@app.route('/result/<host>',methods= ['POST', 'GET'])       
def result(host):
    ...
    return render_template('other_template.html')

Code snippets not tested, but should get you started. Good luck.

gary
  • 685
  • 6
  • 14