AngularJS directives don't seem to work with Python Flask - python

Even though my issue might be a common one, I couldn't find a clear answer for it.
I'm a beginner with AngularJS and there is a very simple code that is not working, and actually all my directives doesn't work.
Here is my small project
/templates
-index.html
-header.html
-script.js
mainapp.py
In index.html there is
<!DOCTYPE html>
<html data-ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div data-ng-include="'header.html'"></div>
</body>
</html>
in header.html
<div> I'm supposed to see this </div>
And mainapp.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def mainpage():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Nothing in script.js
When I'm running mainapp.py I'm expecting to see "I'm supposed to see this" but I don't because the directives doesn't seem to be working. However if I'm trying the html code alone (on Plunker for example) it's working fine.
I assume there is configuration that I need to do but I have no idea what, any ideas? (and if someone could provide an explanation for why it's not working that would be great)
Note that using data- before my directives doesn't change the issue.
Thanks

The issue has to do with how Flask handles static files vs. templates. The header.html file is really a static file in your situation, not a Flask template.
Change your directory structure to:
├── mainapp.py
├── static
│   └── partials
│   └── header.html
└── templates
└── index.html
Then update the ng-include to:
<div data-ng-include="'header.html'"></div>
If this were me, I wouldn't even use a "templates" directory. Just serve up a your index.html file from the static directory so that when an end user hits the main / route, Angular takes over. Then, you can just interact with the server-side via making AJAX requests against the RESTful API.

Related

Integrating a web template with Flask [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Application not picking up .css file (flask/python) [duplicate]
(13 answers)
Closed 4 years ago.
I have downloaded a website template and I want to integrate it with flask. Basically, this template contains asset folder which contains the css and js files. I know that by using render_template('index.html'), I can call index.html on localhost. But when I do so, the webpage is not rendered properly. I think flask is not able to load the js, css, etc files in that folder (templates folder).
My template folder has index.html along with assets folder and othe folders. I am using the code shown below to actually run the index.html.
from flask import Flask, render_template
import os
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
So, index.html is loading but it is not loading the css files, etc. Because if that is not loaded, my webpage looks dull. Its simply some text on white screen. I think the problem is with loading the static files because I get an error saying that there is no folder assets on localhost.
Thanks in advance.
You need to reference the static files inside your template like this:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
And ensure you put the stylesheets in the static directory of your project. You can also configure which directory contains static assets with something like:
app = Flask(__name__, static_folder="static_dir")

Got 404 error while using Flask framework

I was trying to run my html code using flask framework. When I tried to run the python script, it showed 404 error in the browser
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
python script:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)
if __name__ == '__main__':
app.run(debug = True)
What is the reason of this error?
The code works fine.
Make sure that you keep the html file in templates folder. My folder structure is like this:
flask_app
├── hello.py
└── templates
└── hello.html
And also visiting the http://127.0.0.1:5000/ will cause the error as you did not define any view for root path.
While visiting the indexed path http://127.0.0.1:5000/hello/arsho I got the expected view:
Use jinja to print your name
<html>
<body>
<h1>Hello {{name}}</h1>
</body>
</html>
Go throught the flask quickstart

Flask web page cannot find image file

On a Raspberry Pi, I have written a simple Flask app that displays the server's current date and time on a web page. That part works great.
The page should also display an image. That part doesn't work. The image is stored in the photos folder under the app folder: Web_Test/photos.
I use a css file that is stored in a static folder, and that works great.
I use url_for to create the URL to the image:
<p><img src="{{url_for('photos', filename='image1.jpg')}}"></p>
Since photos is not a known endpoint for the url_for command, I used: app.add_url_rule('/photos/<path:filename>', view_func=app.send_static_file) to add the photos folder as an endpoint.
Every time I access the web page from a web browser, my command window, that I ran python (python3 photo.py) from, shows GET /photos/image1/jpg HTTP/1.1" 404.
There are no specific errors, but also no image.
I have read many of the posts on here about this issue, but nothing has helped.
This is my photo.py code:
from flask import Flask, render_template
import datetime
app = Flask(__name__)
app.add_url_rule('/photos/<path:filename>', endpoint='photos', view_func=app.send_static_file)
#app.route('/')
def photo():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'Latest Photo',
'time' : timeString
}
return render_template('photo1.html', **templateData)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
This is my photo1.html code:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href='/static/style.css' />
<title>{{title}}</title>
</head>
<body>
<h1>Latest Photo</h1>
<h2>Current date and time: {{time}}</h2>
<p> <img src="{{url_for('photos', filename='image1.jpg')}}"></p>
</body>
</html>
Any thoughts or suggestions would be greatly appreciated.
Thanks!
The way your program is currently written, the image will be visible if you reorganize the project layout like this:
project
├── app.py
├── static
│   └── image1.jpg
└── templates
   └── photo1.html
The fact that you want to use send_static_file to display photos suggests that photos are static resources. If that's the case, then it would be better to:
1) Move image1.jpg to static/photos/image1.jpg
2) Change the template like this:
<p> <img src="{{url_for('static', filename='photos/image1.jpg')}}"></p>
3) Drop the app.add_url_rule('/photos/<path:filename>', ...) in app.py
I just created a folder named "static" in the project folder and moved my images to it and my problem got solved.
app.py
static
|----image.jpg
templates
|----index.html
and changed index.html file like this:
<img src="/static/image.jpg">

Setting up static folder path in Flask

Seems like my static files aren't being served properly. This is what it looks like right now:
myApp
__init__.py
static
img
js
bootstrap.min.js
etc.
This is what my app config in my __init__.py looks like:
app = Flask(__name__, static_url_path="", static_folder="static")
This is the error:
127.0.0.1 - - [01/Dec/2014 13:12:01] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 -
As far as the url routing goes, no problems there, localhost/home routes to home, localhost/contact routes to contact, etc. But static files aren't being found :( Am I missing something?
NOTE: I'm hosting this on my Mac, purely local host
This is my __init__.py main method:
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Running as:
python __init.py__
It looks like you are hardcoding to static file URLs. You tell Flask to server them with no URL prefix -- the default would have been /static -- but the log shows the request going to /static/js/bootstrap.min.js. You probably have something like the following in a template file.
<script src="/static/js/bootstrap.min.js"></script>
Instead, you should use url_for to create the URL for you. Change the above to
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
This will result in
<script src="/js/bootstrap.min.js"></script>

Get correct static urls with cherrypy dispatching of flask apps

I'm trying to use cherrypy for application dispatching with Flask. The docs give an example with a development server, but when using the cherrypy example snippet and modifying the url prefix, the page is unable to find the static folder.
My directory structure is as follows:
cherry
├── app1
│   ├── __init__.py
│   └── app1.py
├── app2
│   ├── __init__.py
│   ├── app2.py
│   ├── static
│   │   └── js.js
│   └── templates
│   └── index.html
└── cherry_app.py
Some relevant files:
## cherry_app.py
from cherrypy import wsgiserver
from app1.app1 import app as app1
from app2.app2 import app as app2
d = wsgiserver.WSGIPathInfoDispatcher({'/first': app1,
'/second': app2,
})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 9999), d)
if __name__ == '__main__':
try:
print 'Start at 0.0.0.0:9999'
server.start()
except KeyboardInterrupt:
server.stop()
## app2.py
from flask import Flask, send_file
import flask
app = Flask(__name__)
#app.route("/")
def root():
return ("Hello World!\nThis is the second app. Url is %s"
% flask.url_for('root'))
#app.route("/index")
def index():
return send_file('templates/index.html')
if __name__ == "__main__":
app.run()
## index.html
<script src="/static/js.js"></script>
JS loaded?
## js.js
alert('Loaded!');
Going to http://0.0.0.0:9999/second/ correctly tells me that the Url is /second/, and the javascript is loaded when I go to http://0.0.0.0:9999/second/static/js.js. But the html gives the error GET http://0.0.0.0:9999/static/js.js 404 (Not Found). It appears it doesn't know to use the prefix /second when looking for /static even when I change the line:
app = Flask(__name__, static_url_path='/second/static')
How can I get the webpage to correctly load the static files? Preferrably without html templating (like jinja).
Did you try to use url_for to locate static files? Here is the static files section in Flask quickstart.
So in your situation, modify src value of script element in index.html:
<script src="{{ url_for("static", "js.js") }}"></script>
The second argument js.js should be the relative path of static file (say js.js) to the static folder. So if the directory structure of static looks like:
static/scripts/js.js
just replace js.js with scripts/js.js:
<script src="{{ url_for("static", "scripts/js.js") }}"></script>
Hope this will make sense.

Categories

Resources