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

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..

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.

http://localhost:5000/user/signup 404 not found

So I'm trying to set up a simple registration application where users sign up and login however the code doesn't seem to be finding the user/signup as 404 Not Found page appears.
Here is the routes.py file
from app import app
from user.models import User
#app.route('/user/signup', methods = ['POST'])
def signup():
return User().signup()
And here is the app.py file
from flask import Flask, render_template
app = Flask(__name__)
# Routes
from user import routes
#app.route('/')
def home():
return render_template('home.html')
#app.route('/dashboard/')
def dashboard():
return render_template('dashboard.html')
if __name__ == "__main__":
app.run(debug = True)
This is what I'm trying to pass to user/signup which is models.py
from flask import Flask, jsonify
class User:
def signup(self):
user = {
"_id": "",
"name": "",
"email": "",
"password": ""
}
return jsonify(user), 200
Home.html and Dashboard.html are both loaded however when trying to go to http://localhost:5000/user/signup i receive a not found 404 page and this is displayed in my VS Code:
127.0.0.1 - - [09/Dec/2020 16:07:06] "GET / HTTP/1.1" 200 -
You can use Blueprints for this purpose. Blueprints help in logically organising your flask app into several parts.
The following implementation should work.
routes.py
from flask import Blueprint
from user.models import User
_user = Blueprint('user', __name__)
#_user.route('/user/signup', methods = ['POST'])
def signup():
return User().signup()
app.py
from flask import Flask, render_template
app = Flask(__name__)
# Routes
from user import routes
app.register_blueprint(routes._user)

Flask blueprint for upload of files not getting route

Hey I am building a simple prototype in Flask and I am somehow missing something. The route to the upload is missing otherwise it's the pretty standard tutorial and I have pretty much everything working besides it's not adding the route. I have no clue why the route isn't there the debug simply gives a 404.
My routes in init.py looks like this
#app.route('/hello')
def hello():
return 'Hello, World!'
#app.route('/')
def index():
return render_template('home.html')
from . import uploader
app.register_blueprint(uploader.bp)
from . import db
db.init_app(app)
from . import auth
app.register_blueprint(auth.bp)
return app
And my uploader.py looks like this
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
from werkzeug.utils import secure_filename
from flaskr.db import get_db
bp = Blueprint('uploader', __name__, url_prefix='/upload')
#bp.route('/upload', methods=('GET', 'POST'))
def upload():
if form.validate_on_submit():
f = form.photo.data
filename = secure_filename(f.filename)
f.save(os.path.join(
app.instance_path, 'photos', filename
))
return redirect(url_for('index'))
return render_template('upload.html', form=form)
I am probably not declaring something the right way but I don't know what.
The issue wasn't in my code but on my system. I fixed this by recloning the repo I already had which was working. I have no clue what broke it.

Flask TemplateNotFound

I am new to flask and try to run a very simple python file which calls an HTML document, but whenever I search on http://127.0.0.1:5000/, it raises the TemplateNotFound error. I searched stack overflow on similar questions, but even with implementing the solutions, I get the same error. Nothing worked so far
base.html contains:
<body>
<h1>Hello there</h1>
</body>
</html>
flask_test_2.py contains:
from flask import Flask, render_template
app = Flask(__name__, template_folder='templates')
#app.route('/')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run()
as advised in some of the solutions, I checked the file structure:
/flask_test_2.py
/templates
/base.html
It should work. Since is doesn't, you may take out the
template_folder='templates' portion of you app` assignment and have it this way:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run()
it will use the templates directory by default.
The issue you are experiencing may be path related. You may also declare the app variable this way:
app = Flask(__name__, template_folder='usr\...\templates')

How to serve static file in Flask

I have a google verification file that I need to have in my root directory. How do I serve it and set up the route correctly in my app.py file? I thought just having it in the static directory would do the trick.
In my app.py file:
import requests; requests = requests.session()
from flask import (
Flask,
g,
session,
request,
render_template,
abort,
json,
jsonify,
make_response
)
from jinja2 import TemplateNotFound
app = Flask(__name__)
...
#app.route('/ping')
def ping():
return "OK"
"""
Catch-All Route
first looks for templates in /templates/pages
then looks in /templates
finally renders 404.html with 404 status
"""
#app.route('/', defaults={'path': 'index'})
#app.route('/<path:path>')
def show_page(path):
if session.get('tracking_url'):
session['session_url'] = False
templates = [t.format(path=path) for t in 'pages/{path}.html', '{path}.html']
g.path = path
try:
return render_template(templates, **site_variables(path))
except TemplateNotFound:
return render_template('404.html', **site_variables(path)), 404
application = app
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
I've tried adding this but it didn't work:
#app.route('/myfile.html')
def myfile():
return send_from_directory('/static', 'myfile.html')
For a one-off file that Google looks for in the root, I'd just add a specific route:
from flask import send_from_directory
#app.route('/foobar_baz')
def google_check():
return send_from_directory(app.static_folder, 'foobar_baz')
You are free to add in test in show_page(path) to try and serve path with send_from_directory() before you test for a template, of course; the second filename argument can take relative paths.

Categories