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.
Related
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
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)
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.
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..
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"