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)
Related
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.
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
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
Flask keeps returning a weird 404 default template and ignores my custom made template. I have no idea why.
Here is my init
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
#Fixes flask db upgrade to allow deleting columns
with app.app_context():
if db.engine.url.drivername == 'sqlite':
migrate.init_app(app, db, render_as_batch=True)
else:
migrate.init_app(app, db)
login.init_app(app)
babel.init_app(app)
bootstrap.init_app(app)
moment.init_app(app)
app.logger.setLevel(logging.INFO)
app.logger.info('Bob startup')
app.redis = Redis.from_url(app.config['REDIS_URL'])
app.task_queue = rq.Queue('offutt-tasks', connection=app.redis)
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp)
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
from app import models
Here is my init in my errors folder:
from flask import Blueprint
bp = Blueprint('errors', __name__)
from app.errors import handlers
Finally here is my handlers page with the routes.
from flask import render_template, request
from app import db
from app.errors import bp
#from app.api.errors import error_response as api_error_response
def wants_json_response():
return request.accept_mimetypes['application/json'] >= \
request.accept_mimetypes['text/html']
#bp.errorhandler(404)
def not_found_error(error):
#if wants_json_response():
# return api_error_response(404)
return render_template('errors/404.html'), 404
#bp.errorhandler(500)
def internal_error(error):
db.session.rollback()
#if wants_json_response():
# return api_error_response(500)
return render_template('errors/500.html'), 500
my 404.html renders fine when i write a route to go directly to it, but the errorhandler does not seem to be working at all. All it renders is a page saying "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
Any ideas?
You need to use app_errorhandler() to use it for all requests, even outside of the blueprint doc. E.g.
#bp.app_errorhandler(404)
def not_found_error(error):
....
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..