So i've decided to mess around with Tornado (http://www.tornadoweb.org/), and I've gotten pretty far, however for some reason whenever I call the .generate() function on a view a blank page is generated in the browser (self.write() works however)
My ReqHandler:
class Index(tornado.web.RequestHandler):
def get(self):
loader = template.Loader(funcs.static_prefix("/templates/"))
#self.write("Hello, world") #This works!
loader.load("test.html").generate(this="hello") #This doesn't :(
My template(test.html):
<html>
{{ this }}
</html>
My logs:
13:43:18 web.1 | started with pid 21876
13:43:20 web.1 | WARNING:root:404 GET /favicon.ico (::1) 0.48ms
As you can see, if there is an error it is failing silently
Can anybody help?
generate doesn't write the rendered template to output. simply write it like this:
self.render("test.html", this="hello")
and make sure to set the template path in your app's config options.
Related
I am trying to show some preview in Flask from user-uploaded images static/uploads and found that URLs generated by url_for('static', filename=image_file_path) do not work as I'd like.
I am getting out a path like: /static/uploads/0321.jpg
and after putting it in HTML img src={{ image_url_list[0] }} I see no preview (with URL: http://127.0.0.1:5000/static/uploads/0321.jpg if I copy the empty image address)
It is 404 error:GET /static/uploads/03020011.jpg HTTP/1.1" 404 -
The file is in its place and I can access it inside the App if remove the first slash static/uploads/0321.jpg
Actually, I'd like to get the working URLs not only for preview but have them externally visible for other sites (but not freely explorable by other users just typing static/uploads in browser).
So, please, advise me what am I doing wrong?
This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 4 years ago.
I'm pretty new to python, even less experienced with flask, and I cannot figure out this issue. I have the following simple web page with jQuery functionality that works great when I double click the file and open it in a browser:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#updateBtn").on("click", function() {
text = "<h2>The div has been updated!</h2>";
$("#jQuery_div").html(text);
});
});
</script>
<div>
<h1>This is a non-jQuery div</h1>
</div>
<div id="jQuery_div">
<h2>This div should update with jQuery</h2>
</div>
<button id="updateBtn">update</button>
</body>
</html>
However, when flask delivers the web page on localhost:5000, the jQuery functionality is no longer present. My python is as follows:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def render():
return render_template("jquery_test.html")
if __name__ == "__main__":
app.run(port=5000, debug=True)
My app's file tree is:
/AJAX_practice
ajax_practice.py
/templates
jquery-3.3.1.js
jquery_test.html
I was trying to follow this tutorial when I couldn't get the "echo" button to work. In my efforts to debug, I have slowly chipped away and drastically simplified the program to the above code to see why I cannot get my jQuery to work through flask. I am still at a loss. I am running the flask app by pressing F5 in IDLE, with no errors in Python 2.7.13 Shell, and the Terminal (from which I started IDLE with $ sudo idle) showing:
my ip - - [date and time] "GET / HTTP/1.1" 200 -
my ip - - [date and time] "GET /jquery-3.3.1.js HTTP/1.1" 404 -
From this, my best guess is that flask cannot find the jquery.3.3.1.js file, though I have tried putting it everywhere in the file tree with no luck. I cannot use the script src to https for jQuery dependencies, as my server will eventually be on a non-internet connected LAN. Am I on the right track? If so, how does flask find and/or navigate jQuery dependencies? Can anyone point me towards some documentation that might help my fundamental understanding of this issue?
Any help on this matter would be greatly appreciated.
You are trying to serve JavaScript file from templates folder. Add a static folder and use that to serve static content.
in your case create a directory structure like "static/js/jquery.min.js"
and then add script reference like this
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
See this :
http://exploreflask.com/en/latest/static.html
If you don't want to keep it in "static" folder and use another local directory you can use send_from_directory as shown in this example :
https://stackoverflow.com/a/20648053/2118215
This has always worked for me with Flask in the past:
<script src="{{ url_for('static', filename='jquery-3.3.1.js') }}"></script>
'static' is the name of the folder it's in (and the 'static' folder is in the root of my project). You can edit this to suit your preferred structure and naming, so change 'static' to 'templates' if that's where you'd rather keep your jquery file, although I would recommend keeping it in a separate folder from your HTML templates, purely in the interests of keeping your project well organised.
I believe the path to jquery should be /templates/jquery-3.3.1.js
On me flask server when i serve jquery it has the full path from the home directory: /static/js/jquery.min.js
My background-image works only for this template that has #app.route('/').
<header class="intro-header" style="background-image: url('static/img/home.jpg')">
This works perfectly fine when:
#app.route('/')
def home():
return render_template('post.html')
Everything works. I get this:
127.0.0.1 - - [19/Sep/2016 21:07:11] "GET /static/img/home.jpg HTTP/1.1" 304
But when I use same template with:
#app.route('/post/')
def post():
return render_template('post.html')
I get this:
127.0.0.1 - - [19/Sep/2016 21:15:23] "GET /post/static/img/home.jpg HTTP/1.1" 404 -
And background-image is blank.
This is a simple problem can solved by Flask documentation
Anyway, you should use something like this in your template:
background-image: url({{ url_for('static', filename='img/home.jpg') }})
but if you don't want to use Flask methods use :
url('/static/img/home.jpg')
or use another web server instead of flask default web server for your files like Apache and access via http://yoursite/static/img/home.jpg
Partial URLs are interpreted relative to the source of the style sheet, not relative to the document - w3 CSS
This means that you need to change your url() a bit, to include the leading /.
"background-image: url('/static/img/home.jpg')"
4 years, 7 months too late, but anyways just in case someone needs help..
I found flask recognized my .jpg image was located in 'static', so adding 'static' like so "background-image: url('/static/img/home.jpg')", is adding an "extra" static.
What worked for me, using the skeleton approach,
background-image: url('home.jpg');
Simple and bare, like a skeleton.
I have a program which generates an image. Now I want to use Flask to make this picture accessible to other users, but I can’t display this image with the following code:
#!/usr/bin/python2
#coding: utf-8
from flask import *
app = Flask(__name__)
#app.run(host='0.0.0.0')
#app.route('/')
def index():
return render_template('hello.html')
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
My template hello.html is:
<!doctype html>
<title>Hello from Flask</title>
<h1>Hello World!</h1>
<img src="./weather-plot.png">
When I run this program and visit the page, I see this:
192.168.0.61 - - [10/Jul/2013 10:22:09] "GET / HTTP/1.1" 200 -
192.168.0.61 - - [10/Jul/2013 10:22:09] "GET /weather-plot.png HTTP/1.1" 200 -
And in my browser I see the title, but not the picture. What’s wrong?
By the way, is there a better method to display a picture without anything else? Maybe I don’t have to use a template?
Are you sure the image is indeed in the location ./, i.e. in the root of your project?
In any case, it is better to use Flask's url_for() method to determine URLs (see http://flask.pocoo.org/docs/api/#flask.url_for) This makes sure that when you move things around, the URLs don't break.
i want to go from one page to another in my website using a button.
my code for this is like the following:
self.response.out.write('''<form
action="/sign" method=post> <br><input type=submit value="go to lesson 2 ">
</form>
''') % self.redirect("/lesson1")
now i am in lesson one page and i want using this button to go to lesson1 page but i keep getting this error:
PyDev breakpoint
inconsistent dedent at line 53, column 2
Bad Indentation (7 spaces)
does any one know how to fix this?
thanks
Amal
Aside from bad indentation and an errant attempt at using %, self.redirect(...) is done for effect, not to get a string you can use to embed elsewhere. What you've got it more properly divided into a get handler (to emit the form) and a post handler to do the redirect.
An alternative is to do the redirect in the browser, using JavaScript.
I got the correct answer using html.
I have two pages inside my website in google app engine and they are:
lesson1.py
lesson2.py
to go from lesson one to lesson using a button i put this code inside lesson1.py:
self.response.out.write('''<form action="/lesson2" method="get">
<input type="submit" value="go to lesson2" />
</form> ''')
application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
application = webapp.WSGIApplication([('/lesson1', MainHandler)],debug = True)
then in lesson2.py where i want to go i put this code:
application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
application = webapp.WSGIApplication([('/lesson2', MainHandler)],debug = True)
an important issue is the app.yaml file mine looks like this:
application: Sign-language version: 1
runtime: python
api_version: 1
handlers:
- url: /lesson2
script: lesson2.py
- url: /.*
script: lesson1.py
Use Preferences->Pydev->Editor and uncheck replace tabs with spaces. Tabs can be 4 spaces despite popular opinion that it should be changed to 8 spaces.