404 error for CSS file in Flask Application - python

I am unable to find exact path of .css file in my flask app. Following is relevant code
layout.html
<!DOCTYPE html>
<html>
<head>
<title>An App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div id="container">
<div id="heading"><h3>App</h3></div>
{% block content %}{% endblock %}
</div>
</body>
</html>
+app
+static
style.css
+templates
__init__.py
forms.py
models.py
views.py
db_repository
.gitignore
app.db
config.py
db_create.py
The one with + sign are folders
Update:
I tried this in __init__.py, same result
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
app.config.from_object('config')
app._static_folder = os.path.abspath("static/style.css")
print os.path.abspath(app._static_folder)
db = SQLAlchemy(app)
from app import views, models
The link http://127.0.0.1:5000/static/style.css gives 404 error

Static should be on the same level as templates, not under app. Have you tried that?

I you want to change the route to the static asset's folder you could do:
app = Flask(__name__, static_folder='app/static')
check this here

Related

Flask path to css

How can i repair errors with my path? I would like my html in a flask to load my stylesheet into the project, but it throws a lot of jinja2 errors. I'm starting with flask framework.
from flask import Flask, redirect, url_for, render_template
import os.path
TEMPLATE_DIR = os.path.abspath('PROJECTS DEV\Extractor_APP\templates')
STATIC_DIR = os.path.abspath('PROJECTS DEV\Extractor_APP\static\styles')
app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)
#app.route("/")
def home():
return render_template("homepage.html")
#app.route("/<name>")
def name(name):
return render_template("namepage.html")
if __name__ == '__main__':
app.run(debug=True)
<html>
<head>
<title>Flask learning</title>
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/homepage.css') }}">
<title>Home page</title>
</head>
<body>
<h1>Home page!</h1>
{% for text in content%}
<p>{{text}}</p>
{% endfor %}
</body>
</html>```
In the root folder of your project, create a static folder for static files like css and js files. See example below:
To generate URLs for static files, use the special 'static' endpoint
name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
https://flask.palletsprojects.com/en/2.1.x/quickstart/#static-files
There is also no need to specify static and template folders. Just use: app = Flask(__name__)

Python Flask - url_for{} not accessing static folder [duplicate]

This question already has an answer here:
Flask Python not loading main.css
(1 answer)
Closed 1 year ago.
Have a directory structure as follows:
Flask_project
-env
-src
--app2.py
-static
--css
---main.css
-templates
--base.html
--index.html
-app.py
If I load the page using app.py in the main folder, the main.css file is loaded fine using: python app.py. This works from the following file:
from flask import Flask, render_template, url_for # import
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
However, if I load app2.py using python3 src\app2.py which is in the \src folder as follows, and redirects the template_folder:
from flask import Flask, render_template, url_for # import
app = Flask(__name__, template_folder='../templates')
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
I am unable to load the css\main.css folder, I get the following error:
"GET /css/main.css HTTP/1.1" 404 -
I don't see why placing the app_whatever.py file in a sub directory (in this case \src) makes it unable to locate the main.css file?
For reference the base.html is as follows:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{url_for('static', filename='css/main.css') }}">
{% block head %}{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
And index.html is:
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{% block body %}
<h1> Template </h1>
{% endblock %}
As mentioned in your second question, you need to define the location of your static-folder:
app = Flask(__name__, template_folder='../templates', static_folder='../static')

Internal Server Error when trying to run flask

I am trying to create a website with a web form in it using flask, but I keep getting an Internal Server error, despite getting no error when I run it in the console
Here is my code:
__init.py
from flask import Flask, render_template
from forms import TestForm
app = Flask(__name__)
app.config.from_pyfile('config.py')
#app.route('/')
def homepage():
return render_template("main.html", form=TestForm())
if __name__ == "__main__":
app.run(debug=True)
forms.py
from flask_wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class TestForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
config.py
WTF_CSRF_ENABLED = True
SECRET_KEY = '<super-secret>'
main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/" method="post" name="login">
{{ render_field(form.test_form(size=80) }}<br>
<p><input type="submit" value="Sign In"></p>
</form>
</html>
When I run flask run I get this
$ flask run
* Serving Flask app "FlaskApp"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
When I try to access http://127.0.0.1:5000/ in both chrome and firefox I get an error, but I feel like that's a whole separate question.
If all of your codes are here then I can tell you the problem might be about rendering form, try this one (pip install flask-bootstrap):
# __init.py
...
bootstrap = Bootstrap(app)
main.html
{% import 'bootstrap/wtf.html' as wtf %}
...
{{ wtf.quick_form(form) }}
...

flask isnt reading or interpreting css file

I'm basically trying to follow this tutorial ( http://net.tutsplus.com/tutorials/python-tutorials/an-introduction-to-pythons-flask-framework/)
Now when the css part comes in, and i copy the code it simply wont come out styled even afterr main.css is added it still shows up unstyled like if it wasn't importing the css file here's the HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flask</title>
<strong><link rel="stylesheet" type"text/css" href="{{ url_for('static', filename='css/main.css') }}"></strong>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Flask App</h1>
</div>
</header>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
layout.html ^
Home.html v
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Flask app<h2>
<h3>This is the home page for the Flask app<h3>
</div>
{% endblock %}
routes.py v
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
This is probably due to the directory structure of your app. By default, flask looks for the static directory in the same level as the file that the app object is created in. This is the example structure for a small application from the flask docs.
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
You can also change the location of the static files by setting the "static_folder" attribute on the app object. Check the docs here for setting the static_folder

duplicated url_prefix in Flask using blueprint

Sorry I've searched inside the stackoverflow and googled, but no useful information found.
I have an flask application,
python version 2.6
flask version 0.9
its application hierarchy is like
application/
__init__.py
app.py
hello/
__init__.py
view.py
templates/
hello.html
both files init.py are empty
app.py
-----------------------
from flask import Flask
from flup.server.fcgi import WSGIServer
from hello.view import hello
app = Flask(__name__)
app.debug = True
app.register_blueprint(hello, url_prefix='/hello')
if __name__ == '__main__':
WSGIServer(app, bindAddress='/tmp/app.sock').run()
view.py
-----------------------
import os
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
hello = Blueprint('hello', __name__, template_folder='templates')
#hello.route('/')
def get_index():
try:
return render_template('hello.html')
except TemplateNotFound:
abort(404)
hello.html
-----------------------
<!DOCTYPE html>
<html>
<head>
{% block head %}
<meta charset="utf-8">
{% endblock %}
</head>
<body>
<div>
{% block body %}
<h1>Click Me</h1>
{% endblock %}
</div>
</body>
</html>
It works fine when I enter localhost:8080/hello, but turns out error if I click the link in html. I found its url value is href="/hello/hello/" (Should it be /hello/ right?).
I know hello.get_index is mapped to /hello/, but have no idea that the first one hello/ comes from. Any hint is appreciated.
Have you tried removing the url_prefix parameter when you regisger the blueprint? For example, what if you change the following from :
app.register_blueprint(hello, url_prefix='/hello')
to
app.register_blueprint(hello)

Categories