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()
Related
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()
I'm just starting to learn Flask but I can't even get through this beginner step. I have tried to make a dynamic URL route as below but when I go to http://127.0.0.1:5000/home for example, it says "NOT FOUND". Any help appreciated!
from flask import Flask
app = Flask(__name__)
#app.route("/") #this is the default domain
def home():
return "<h1>Hello this main page</h1>"
#app.route("/<name>")
def user(name):
return f"hi {name}"
if __name__ == "__main__":
app.run()
You forgot to set the route /home.
Try this :)
#app.route("/home")
def home():
return "<h1>Hello this main page</h1>"
I'm using the Flask-socketio library for a python project and it seems it's not possible to use render_template in a socket.io callback. I could of course send the redirection url with emit and redirect my page in javascript like here but the problem is that I have to pass a variable in the render template. So I have a button on my index page that redirects to the process page and sends the process message with socket.io.
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route("/")
def index():
return render_template('index.html')
#app.route("/process")
def format():
return render_template('process.html')
#socketio.on('process')
def do_process():
if process() == 0:
return render_template('index.html')
else:
return render_template('index.html', description=MSG_ERROR)
if __name__ == "__main__":
socketio.run(app)
This question already has an answer here:
register_blueprint doesn't add route to Flask app
(1 answer)
Closed 5 years ago.
This is really strange but am facing this problem. Everything was working and i was almost done with the app but out of a sudden it stopped. I have isolated the code and i realized that when i register a blueprint and use it on a route, it fails to return saying no URL found. Here is the isolated code:
from flask import Flask, render_template, Blueprint
app = Flask(__name__)
home = Blueprint('home', __name__, static_folder='static', template_folder='template')
app.register_blueprint(home)
#home.route('/') #<---This one does not work
# #app.route('/') <--- This one works
def index():
return "This is the index route."
# return render_template('layer.html')
if __name__ == '__main__':
app.run()
Move the app.register_blueprint(home) after route defined.
from flask import Flask, Blueprint
app = Flask(__name__)
home = Blueprint('home', __name__, static_folder='static', template_folder='template')
#home.route('/')
def index():
return "This is the index route."
app.register_blueprint(home)
if __name__ == '__main__':
app.run()
I am trying to add a function in the Jinja environment from a blueprint (a function that I will use into a template).
Main.py
app = Flask(__name__)
app.register_blueprint(heysyni)
MyBluePrint.py
heysyni = Blueprint('heysyni', __name__)
#heysyni.route('/heysyni'):
return render_template('heysyni.html', heysini=res_heysini)
Now in MyBluePrint.py, I would like to add something like :
def role_function():
return 'admin'
app.jinja_env.globals.update(role_function=role_function)
I will then be able to use this function in my template. I cannot figure out how I can access the application since
app = current_app._get_current_object()
returns the error:
working outside of request context
How can I implement such a pattern ?
The message error was actually pretty clear :
working outside of request context
In my blueprint, I was trying to get my application outside the 'request' function :
heysyni = Blueprint('heysyni', __name__)
app = current_app._get_current_object()
print(app)
#heysyni.route('/heysyni/')
def aheysyni():
return 'hello'
I simply had to move the current_app statement into the function. Finally it works that way :
Main.py
from flask import Flask
from Ablueprint import heysyni
app = Flask(__name__)
app.register_blueprint(heysyni)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Ablueprint.py
from flask import Blueprint, current_app
heysyni = Blueprint('heysyni', __name__)
#heysyni.route('/heysyni/')
def aheysyni():
# Got my app here
app = current_app._get_current_object()
return 'hello'