Home > Net >  it throws a 404 when without url prefix (FLASK)
it throws a 404 when without url prefix (FLASK)

Time:12-01

You see Im having a problem where in flask, I made a web app. and I added the URL prefix as views and you see without /views attached to localhost it throws a 404, I wanna change it so it will redirect automatically to /views when you go to the regular URL such as http://127.0.0.1:8000/

I tried adding @app.route in app.py but it just caused even more problems

CodePudding user response:

You could redirect automatically from http://127.0.0.1:8000/ to http://127.0.0.1:8000/views using the code below.

from flask import Flask, jsonify, redirect

app = Flask(__name__)

#Page 1
@app.route('/', methods=['GET'])
def welcome():
  return redirect("http://127.0.0.1:8000/views", code=302)

#Page 2
@app.route('/views', methods=['GET'])
def hello():
  return jsonify({"data": "Hello"})

if __name__ == '__main__':
 app.run(host="0.0.0.0", port="8000")

Output

 #127.0.0.1 - - [01/Dec/2022 15:23:23] "GET / HTTP/1.1" 302 - (Redirecting to views page)
 #127.0.0.1 - - [01/Dec/2022 15:23:23] "GET /views HTTP/1.1" 200 -
  • Related