So I want to show a diagramm on my HTML page using Flask but when I run my website, then I don't see the image. I know there are a couple of similar questions here, but I'm just stuck with it.
Here is my Python Code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('test.html')
if __name__ == "__main__":
app.run(debug=True)
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Diagramm</h1>
<img src="{{url_for('static', filename='test.jpg')}}" alt="Here should be a picture"/>
</body>
</html>
And here is my file path:
/home/pi/flask
/static
/test.jpg
/templates
/test.html
website.py #This is the Programm
Related
my flask app is all black and i don't know what to do here is my
app = Flask(__name__)
#app.route("/")
def hello_world():
return render_template("index.html", magic_word="alakazam")
if __name__ == '__main__':
app.run(debug=True)
and my html code
<!DOCTYPE html>
<html>
<head>
<title>Python app</title>
</head>
<body>
<h1>blah blah blah {{ magic_word }} </h1>
</body>
</html>
you need to move your index.html file inside the templates directory. the directory structure should look like this:
/application.py
/templates
/index.html
here are the docs for rendering templates.
I am trying to redirect a user to a web page with a loading spinner using render_template and then redirect them to an external URL using flask in Python.
I have written the code below, it only waits 3 seconds and then redirects to youtube.com.
from flask import Flask, redirect, render_template
from time import sleep
app = Flask(__name__)
#app.route('/')
def redirect_to_url():
render_template('loading_spinner.html')
sleep(3)
return redirect("https://youtube.com")
if __name__ == "__main__":
app.run(debug=True)
Does anyone have any ideas on how to achieve this?
you can use a timeout in javascript. Here is the sample
loding_spinner.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello
</body>
<script>
function myFunction() {
location.replace("https://youtube.com")
}
setTimeout(function(){ myFunction(); }, 3000);
</script>
</html>
python Code
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def redirect_to_url():
return render_template('loading_spinner.html')
if __name__ == "__main__":
app.run(debug=True)
''' upload.html'''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2 style="color:DodgerBlue;">File Uploader</h2>
<form id = "upload-form" action = "{{ url_for('upload') }}" method="POST"
enctype="multipart/form-data">
<input type = "file" name = "file" accept = "files/*" multiple>
<input type = "submit" value = "submit">
</form>
</body>
</html>
''' app.py'''
import os
from flask import Flask, request, render_template, send_from_directory
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route("/")
def index():
return render_template("upload.html")
#app.route("/upload", methods=["POST"])
def upload():
target = os.path.join(APP_ROOT, 'Athena_XML_files/')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("complete.html")
#app.route('/run_script')
def run_script():
app.config.from_pyfile("main.py")
return render_template('result.html')
if __name__ == "__main__":
app.run(port=4555, debug=True)
'''complete.html'''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>XML files Uploaded</h1>
<ul><br><br>
<h2><strong>Please click to obtain the result</strong></h2><br><br>
<ul class="nav nav-stacked">
<li role="presentation"><a href="{{ url_for('run_script') }}">CLICK
HERE</a></li>
</ul>
</ul>
</body>
</html>
As the XML files are uploaded and the CLICK HERE button is clicked, main.py file should run in the background for which i have made a function in app.py file to run the main.py file.
Uploading works well, but on click of button the main.py file is not running in the background.
I'm not sure if your idea is a good one. I posted some small solutions, but you should read this article for a better practice.
1) If you want to run an external script from inside flask, you could use subprocess to run a script from the command line.
#app.route('/run-script')
def run_script():
result = subprocess.check_output("python main.py", shell=True)
return render_template('results.html', **locals())
2) If you want to run Python code in background without any return, you could create a thread.
from threading import Thread
#app.route('/run-in-background')
def run_in_background():
run_func()
return redirect(url_for('.index'))
def run_func():
data = { 'some': 'data', 'any': 'data' }
thr = Thread(target=run_async_func, args=[app, data])
thr.start()
return thr
def run_async_func(app, data):
with app.app_context():
# Your working code here!
example_module.do_somthing_with(data)
Not sure if it helps. Both solutions could make a lot mess.
You should read the flask docs.
The app.config.from_pyfile function evaluates configuration data from Python code. This is very different than your question.
This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 4 years ago.
I'm new to flask (but not new to Python) and I've been following Corey Schafer's YouTube tutorial on setting things up. I've done everything almost as Corey did in the videos. I'm working with Visual Studio Code on Mac instead of Sublime, which is the only difference.
When I get to the step of using the render_template function to execute basic html files, something is going wrong and I'm getting all kinds of errors. What am I missing?
My flask_blog.py program:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
return render_template('home.html')
#app.route("/about")
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
home.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Home Page</h1>
</body>
</html>
about.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>About Page</h1>
</body>
</html>
And here is what I'm getting when I try navigating to the home page:
Screenshot 1/2
Screenshot 2/2
Ensure that you are storing the html files in a subdirectory called templates:
parentfolder
templates
home.html
about.html
flask_blog.py \\this is the file that contains the route declarations
I have user interface (angularJS) in which i need to upload a file without refreshing the page.Currently we are using Flask as web application framework.
I changed the index.html to below format so that without using form tags i am trying to read the uploaded file and store it.
Using ngclick method how to read the file from app.py ?
The following is the code snippet(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<link href="http://bootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
</head>
<body>
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload file</button>
</div>
</body>
</html>
code snippet of app.py
from flask import Flask, render_template, json, request
app = Flask(__name__)
#app.route('/')
def main():
return render_template('index.html')
#app.route('/upload/')
def upload_file():
print('uploaded file ',request.FILES['file1'].read())
return render_template('signup.html')
I tried various options but i could not find feasible option.
Thanks
vijay