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__)
Related
I have an issue deploying the quick start python web app from the openai website.
It works fine on my local, but when I push to my host (A2hosting), after configuring the web app in cpanel, not only is the css not recognized (with a MIME type (“text/html”) mismatch), when I POST request, it loads the root directory, where there is nothing.
The app and all files are located here: /home/domain/flaskai.
And when creating the app via cpanel, it also created a folder in public html here: /home/domain/public_html/flaskai.
So in effect, the app loads ok (but without css) in domain/flaskapp, and when I submit the form it loads: domain/.
Here is my passenger_wsgi.py:
import os
import sys
import importlib.util
sys.path.append(os.getcwd())
spec = importlib.util.spec_from_file_location("app", "app.py")
app = importlib.util.module_from_spec(spec)
spec.loader.exec_module(app)
application = app.app
Here is my app.py:
import os
import openai
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__, static_folder='static', static_url_path='/static')
openai.api_key = os.getenv("OPENAI_API_KEY")
#app.route("/", methods=("GET", "POST"))
def index():
if request.method == "POST":
animal = request.form["animal"]
response = openai.Completion.create(
model="text-davinci-003",
prompt=generate_prompt(animal),
temperature=0.6,
)
return redirect(url_for("index", result=response.choices[0].text))
result = request.args.get("result")
return render_template("index.html", result=result)
def generate_prompt(animal):
return """Suggest three names for an animal that is a superhero.
Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: {}
Names:""".format(
animal.capitalize()
)
if __name__ == "__main__":
app.run()
Here is the index.html in the template folder:
<!DOCTYPE html>
<head>
<title>OpenAI Quickstart</title>
<link
rel="shortcut icon"
href="{{ url_for('static', filename='dog.png') }}"
/>
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}" />
</head>
<body>
<img src="{{ url_for('static', filename='dog.png') }}" class="icon" />
<h3>Name my pet</h3>
<form action="{{ url_for('index') }}" method="post">
<input type="text" name="animal" placeholder="Enter an animal" required />
<input type="submit" value="Generate names" />
</form>
{% if result %}
<div class="result">{{ result }}</div>
{% endif %}
</body>
and here is the .htaccess in /home/domain/public_html/flaskai:
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home/domain/flaskai"
PassengerBaseURI "/flaskai"
PassengerPython "/home/domain/virtualenv/flaskai/3.7/bin/python"
AddType text/css .css
It works fine on my local, so What went wrong.
I have been at it for two days now and going nuts. Thanks in advance.
I found the issue.
I needed to import dotenv in the app.py file
from dotenv import load_dotenv
load_dotenv()
I'm trying to show a background image using python flask and html. But I get the error "Failed to load resource: the server responded with a status of 404 (NOT FOUND)" My structre I think is good but heres the code.
home.py file
from flask import render_template, Blueprint, request, send_file
home_page = Blueprint('home', __name__)
#home_page.route('/', methods=['POST', 'GET'])
def home():
return render_template('index.html')
return send_file ("home_bg.jpg")
index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>poo</title>
<style>
</style>
</head>
<body style="background-image: url(/static/home_bg.jpg);">
<script>
</script>
</body>
</html>
I think it has something to do with returning the picture to the client in the home.py file.
Change the URL to this style
background-image: url({{ url_for('static',filename='img/home.jpg') }})
To learn more about this here is the documentation:
http://flask.pocoo.org/docs/1.0/tutorial/static/
You must change the home view function and remove the last line, because firstly this line will NEVER be executed, and secondly it is simply not necessary, the flask distributes static files itself, you should not do it manually
The line from the template where you upload the image should be changed to the following:
background-image: url( {{ url_for('static', filename='home_bg.jpg') }} )
Also see:
About Static Files
About url_for function
And about url building in flask using url_for
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')
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) }}
...
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