Flask routes order matters? - python

I'm just started to play with Flask, so in all likelihood this is a seriously noobish question. This app is running on Google App Engine SDK 1.7.4. Flask 0.9, Werkzeug 0.9 and Jinja2 2.6.
The following code works as expected:
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route('/')
def hello():
return "Main page"
#app.route('/hello/', methods=['GET', 'POST'])
#app.route('/hello/<name>', methods=['GET', 'POST'])
def hello(name=None):
return render_template('hello.html', name=name)
if __name__ == "__main__":
app.run()
However, if I reverse the route handlers, going to the /hello/ renders as if I went to /
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route('/hello/', methods=['GET', 'POST'])
#app.route('/hello/<name>', methods=['GET', 'POST'])
def hello(name=None):
return render_template('hello.html', name=name)
#app.route('/')
def hello():
return "Main page"
if __name__ == "__main__":
app.run()
Worse yet, going to /hello/, for example /hello/John, results in error 500.
Is this normal behavior and the order of routes matters? If so, please also point me to relevant docs and, if possible, provide an explanation of why this order is so important.

You're creating two functions with the same name (hello). Rename the second one:
#app.route('/')
def index():
return "Main page"

Related

flask cannot open folder

I am trying to use the flask to open a local folder on the browser, like directly typing file:///D:/ to the address bar. but it failed. when I directly run the home.html on the browser it can work successfully. Is there anything wrong? How can I tell Flask works correctly?
Thanks
app.py
from flask import Flask, render_template, render_template_string
from flask import Flask
app = Flask(__name__)
#app.route("/", methods=['POST', 'GET'])
#app.route('/helloworld')
def helloworld():
return 'Hello, world!', 200
#app.route("/home")
def home():
return render_template('home.html')
home.html
CLICK
Try this way
#app.route("/home")
def home():
import os
arr = os.listdir("F:/")
return render_template('home.html', arr=arr)
and then on template(home.html) list your files accordingly.

Why flask app run but browser is not loading the page?

I was developing a web application and it was woking fine, then I closed the project and re-opened it after a few hours, the project ran without error, but when I go to localhost:5000 it doesn't even load. I tried the same project in another laptop and it works perfectly.
I also tried a simple project in the problematic one like this. The program run, but the browser won't load the page, also here if I use my second laptop it works perfectly. What I should do to fix? Literally like 2 hours ago was working fine
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()
My application code is:
from flask import Flask, render_template
from flask_login import current_user, LoginManager
from DaisPCTO.db import get_user_by_id
from flask_bootstrap import Bootstrap
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = "qwnfdopqwebnpqepfm"
Bootstrap(app)
login_manager = LoginManager()
login_manager.login_view = "auth_blueprint.login"
login_manager.init_app(app)
#app.route("/")
def home():
print("hello")
return render_template("page.html", user=current_user, roleProf = True if current_user.is_authenticated and current_user.hasRole("Professor") else False)
#login_manager.user_loader
def load_user(UserID):
return get_user_by_id(UserID)
from DaisPCTO.auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from DaisPCTO.courses import courses as courses_blueprint
app.register_blueprint(courses_blueprint, url_prefix="/courses")
return app
i'm not putting all the blueprint, this is only the init.py file
In you application you don't run your app you just create a function
if __name__ == '__main__':
app = create_app()
app.run()
If you add this to your code you should be abble to see it in http://localhost:5000

jinja2.exceptions.TemplateNotFound error using flask and python

WHY IT DOES NOT SHOW WHAT I'VE WRITTEN IN HOME.HTML AND IT RESULTS TO THAT ERROR?
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def home_page():
return render_template('home.html')
app.debug = True
if __name__ == "__main__":
app.run()
You do have to specify the port in the app.run() call like app.run(port=8080, debug=True). Also check whether home.html is existing in the templates folder.

Why cant I route to localhost /login?

Im new to python and trying to setup a practice webapp.
from flask import Blueprint
views = Blueprint('views', __name__)
#views.route('/')
def home():
return "<h1>Test</h1>"
When i run this the result comes out fine result
127.0.0.1:8080/login (anything i put after "/" page doesnt load.)
Ex: when i run this
from flask import Blueprint
auth = Blueprint('auth', __name__)
#auth.route('/login')
def login():
return "<h1>Login</h1>"
i get 404 error
please advise.
from flask import Blueprint, Flask
views = Blueprint('views', __name__)
#views.route('/')
def home():
return "<h1>Test</h1>"
auth = Blueprint('auth', __name__)
#auth.route('/login')
def login():
return "<h1>Login</h1>"
app = Flask(__name__)
app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/')
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True)
I think this is what you're trying to do. You neglected to "register" your blueprints to the app. Default port is 5000 I believe

Where do I put my templates folder in a Flask app?

I'm trying to use render_template in my Flask app:
# -*- coding: utf-8 -*-
from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__)
#app.route("/")
def hello_world():
return "Hello World", 200
#app.route('/welcome')
def welcome():
return render_template("welcome.html")
#app.route("/login", methods=["GET", "POST"])
def login():
error = None
if request.method == "POST":
if request.form["username"] != "admin" or request.form["password"] != "admin":
error = "Invalid credentials. Please try again!"
else:
return redirect(url_for("home"))
return render_template("login.html", error=error)
app.run(debug=True)
I think that my app can't see welcome.html (and the templates folder) because I always get a "Internal Server Error" and no HTML page.
In a single folder, I have app.py the static folder and the templates folder (with the HTML file).
What's wrong here?
Does your python script have all the necessary bits of a minimal Flask application?
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/welcome')
def welcome():
return render_template("/welcome.html")
if name== "__main__":
app.run()
You probably don't need a / in the name of the template.
(i.e. 'welcome.html', not '/welcome.html').
See the documentation for render_template.
It works with or without the slash.
Can you share the folder structure, and the script that you are executing (such as a init.py)
try looking at this (it's my repo for my webpage), to see if you might have missed something..

Categories