I am facing a very weird Issue, In my Flask App when index route (https://sitename.com/) is called everything is fine, but as i navigate to a route like https://sitename.com/about it shows 404 Error, even when About route is created in main.py . This App works all perfect in localhost:5000 but when I deployed it too a VPS It is showing that Error of showing 404 on every route
My main.py
from os import environ
from flask import Flask, redirect, render_template, request, url_for
import requests
import json
import datetime
def getUserData(route):
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
with open("users.txt", "a") as f:
f.write(f"Page Visited: {route}\n")
f.write(f"User Agent: {request.headers.get('User-Agent')}\n")
f.write(f"Remote Addr: {ip}\n")
f.write(f"DateTime: {datetime.datetime.now()}\n")
f.write(f"\n\n\n")
app = Flask(__name__)
app.debug = True
# Website
#app.route('/')
def index():
getUserData("Index Page")
return render_template('index.html')
#app.route('/gallery')
def gallery():
getUserData("Gallery")
return render_template('pages/gallery.html')
#app.route('/faqs')
def faqs():
getUserData("FAQs")
return render_template('pages/faqs.html')
#app.route('/about')
def about():
getUserData("About")
return render_template('pages/about.html')
#app.route('/contact')
def contact():
getUserData("Contact")
return render_template('pages/contact.html')
# 404 Handling
#app.errorhandler(404)
def not_found(e):
getUserData("404 Page")
return render_template("pages/404.html")
if __name__ == '__main__':
app.run()
Related
I have a very basic flask application that I have deployed to Heroku. I am trying to define a variable that I can change when a specific function is executed. For example, if I have a variable logged_in=True, I want to be able to change it to logged_in=False when the route #app.route('/logout') is executed. Here is the code:
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
#app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
#app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
#app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
#app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
#app.route("/log_out", methods=["POST"])
def log_out():
app.config['logged_in']=False
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)
When I launch the app locally, the value of logged_in is set to False when logout is executed and does not change if login is triggered again. However, when I deploy the app to Heroku, the value of logged_in goes back True when login is triggered again (it's weird, the value changes sometimes, but not always).
How can I set the value of logged_in so that it does not change until I update it with a function? I tried to use session.config['logged_in']instead of app.config['logged_in'], but I had the same issue. Ideally, I want the value to be unique for each session.
Thank you
If you want to store one value to each session. No sql like redis is recommendation.
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
import redis
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379')
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
#app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
#app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
#app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
#app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
#app.route("/log_out", methods=["POST"])
def log_out():
session['key'] = 'False'
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)
i'm new to Flask. And i'm trying to redirect the user to a "success" page where he can download the csv file that my program had create for him.
so my server.py look like this:
from flask import Flask, request, abort, redirect
from flask_cors import cross_origin
import process
app = Flask(__name__)
#app.route('/ind', methods=['POST'])
#cross_origin(origin='localhost', headers=['Content- Type', 'Authorization'])
def ind():
if not request.json:
abort(400)
my_json = request.json
reponse = process.process(my_json)
if reponse:
return redirect("http://localhost:8080/success", code=302)
else:
return redirect("http://localhost:8080/fail", code=302)
#app.route('/position', methods=['POST'])
#cross_origin(origin='localhost', headers=['Content- Type', 'Authorization'])
def position():
if not request.json:
abort(400)
my_json = request.json
reponse = process.process(my_json)
if reponse:
return redirect("http://localhost:8080/success", code=302)
else:
return redirect("http://localhost:8080/fail", code=302)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5050, debug=True)
my process.py where the JSON that i received is transformed and transcripts to a csv file, look like this:
def process(my_json):
[blablabla...]
return True
"reponse" is always True but no redirection, what am i doing wrong ?
Assuming you have handlers for routes /success and /fail, you can use url_for.
from flask import url_for
#app.route('/position', methods=['POST'])
def posistion():
# ...
if response:
return redirect(url_for('/success'), code=302)
return redirect(url_for('/fail'), code=302)
Do not hard-code urls to other routes of your flask application. This can lead to your case, when your server is running on port 5050 and your urls are targeting port 8080.
I am trying to take a modular approach to designing my Flask App.
So each module as multiple routes. See below
Templates folder
Contents of my home_routes.py
from flask import Blueprint, request, session, abort
from flask import render_template
def home_blueprints(app):
home_routes = Blueprint("home_routes", __name__, template_folder='../../templates', static_folder='../../static')
#home_routes.route('/home/Links')
def links():
return render_template('links.html')
#home_routes.route('/home/Confirmation')
def confirmation():
return render_template('Confirmation.html')
#home_routes.route('/')
def main():
return render_template('main.html')
#home_routes.route('/home/Contactus', methods=['GET', 'POST'])
def contact():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
abort(403)
return render_template('GoogleForm.html')
app.register_blueprint(home_routes)
Contents of believe_routes.py
from flask import Blueprint
from flask import render_template
def believe_blueprints(app):
believe_routes = Blueprint("believe_routes", __name__, template_folder='../../templates', static_folder='../../static')
#believe_routes.route('/home/Believe/Truth_About_God')
def truth_about_God():
return render_template('The_Truth_Concerning_God.html')
#believe_routes.route('/home/Believe/Truth_We_Believe')
def the_truth_we_beleive():
return render_template('The_Truth_We_Believe.html')
#believe_routes.route('/home/Believe/Truth_About_Christ')
def truth_about_christ():
return render_template('The_Truth_About_Christ.html')
#believe_routes.route('/home/Believe/Truth_About_Church')
def truth_about_church():
return render_template('The_Truth_About_Church.html')
#believe_routes.route('/home/Believe/Truth_About_Salvation')
def truth_about_salvation():
return render_template('The_Truth_About_Salvation.html')
#believe_routes.route('/Believe')
def truth_we_believe():
return render_template('Truth_We_Believe.html')
app.register_blueprint(believe_routes)
Contents of init.py
from home_routes import home_blueprints
from believe_routes import believe_blueprints
def configure_blueprints(app):
home_blueprints(app)
believe_blueprints(app)
Only the home_routes work. The URLs in the believe_routes do not work. I get a 404
INFO 2017-05-26 18:01:44,325 module.py:813] default: "GET /home/Believe/Truth_About_Christ HTTP/1.1" 404 233
I am calling configure_blueprints(app) from create_app which is then called from main.py.
Any thoughts please.
the 404 is not for the template reason, maybe you can try this code to view whether blueprint is registed to flask instance, and you can put your output back for more details...
#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
from home_routes import home_blueprints
from believe_routes import believe_blueprints
app = Flask('demo')
def configure_blueprints(app):
home_blueprints(app)
believe_blueprints(app)
configure_blueprints(app)
print(app.url_map)
i hope this would help you ..
I have the following code in __init__.py
#app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
#app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
#app.errorhandler(403)
def page_forbidden(e):
return render_template('403.html'), 500
It used to catch all 500 errors and show my nice 500.html template. However I moved all my views into separate blueprint files and now the 500 errorhandler does not work. It is only that handler though. 404 works just fine.
If the server throws a 500 error, it will display the default Chrome INTERNAL SERVER ERROR message and not my template. Did I do something wrong when I created all my blueprints that would create this issue?
Here is the entire __init__.py file
import datetime
import mysql.connector
import os
from flask import Flask, render_template, session, request, Blueprint
from flask.ext.moment import Moment
from flask.ext.login import LoginManager
from db_classes import User
from info import info_blueprint
from claims import claims_blueprint
from users import users_blueprint
from members import members_blueprint
from drug import drug_blueprint
from auth import auth_blueprint
from formulary import formulary_blueprint
from config import MYSQL_USR, MYSQL_HOST, MYSQL_PASS, MYSQL_DB, MYSQL_PORT, second_to_live
from decorators import role_required
app = Flask(__name__, template_folder="static/templates")
app.config.from_object('config')
moment = Moment(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
#login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
####################
# Blueprints
####################
app.register_blueprint(info_blueprint)
app.register_blueprint(claims_blueprint)
app.register_blueprint(users_blueprint)
app.register_blueprint(members_blueprint)
app.register_blueprint(drug_blueprint)
app.register_blueprint(formulary_blueprint)
app.register_blueprint(auth_blueprint)
#####################
# Error Routes
#####################
#app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
#app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
#app.errorhandler(403)
def page_forbidden(e):
return render_template('403.html'), 500
#####################
# Context Processors
#####################
#app.before_request
def make_session_permanent():
session.permanent = True
app.permanent_session_lifetime = datetime.timedelta(seconds=second_to_live)
#app.context_processor
def inject_time():
return dict(current_time=datetime.datetime.utcnow())
if __name__ == "__main__":
app.run(host= '0.0.0.0', debug=True)
Something I didn't realize... from the Flask docs
Please note that if you add an error handler for “500 Internal Server
Error”, Flask will not trigger it if it’s running in Debug mode.
I have json data in demo_data.json that I'd like to bring into a Flask app. I'm receiving a 404 on the file which I've placed in the static directory, my code is below, thanks for any thoughts in advance:
from flask import Flask, render_template
from flask import url_for
app = Flask(__name__, static_url_path='/static/')
#app.route('/')
def home():
return render_template('home.html')
#app.route('/welcome')
def welcome():
return render_template('welcome.html')
if __name__ == '__main__':
app.run()
return send_from_directory('/static', 'demo_data.json')
You would need to define the view to send the data.
Something similar to :
from flask import Flask, render_template
from flask import url_for
app = Flask(__name__, static_url_path='/static/')
#app.route('/')
def home():
return render_template('home.html')
#app.route('/welcome')
def welcome():
return render_template('welcome.html')
#app.route('data/<filename>')
def get_json(filename):
return send_from_dir
if __name__ == '__main__':
app.run()
So, you are trying to send a file? Or show a file in an url?
I assumed the later. Notice the use of url_for.
This creates a link that will show your static file.
http://127.0.0.1:5000/send and http://127.0.0.1:5000/static/demo_data.json
from flask import Flask, render_template
from flask import url_for
app = Flask(__name__, static_url_path='/static')
#app.route('/')
def home():
return render_template('home.html')
#app.route('/send')
def send():
return "<a href=%s>file</a>" % url_for('static', filename='demo_data.json')
if __name__ == '__main__':
app.run()
But you also might want to check out https://github.com/cranmer/flask-d3-hello-world
It looks like you have a trailing slash on your static_url_path. Removing the extra character resolved the issue. Also note the removed last line. The return call wasn't necessary and the function call after the return was a syntax error.
from flask import Flask, render_template
from flask import url_for
app = Flask(__name__, static_url_path='/static')
#app.route('/')
def home():
return render_template('home.html')
#app.route('/welcome')
def welcome():
return render_template('welcome.html')
if __name__ == '__main__':
app.run()