I'm working on how to add value from flask into static/css file
Here's my code from static/style.css:
.color1 {
background-color: {{pickcolor}};
width: 30px;
height: 30px;
}
.color2 {
background-color: {{pickcolor}};
width: 30px;
height: 30px;
}
so the problem i got is underline error property value expectedcss(css-propertyvalueexpected)
BUT when I use internal css in html file
<style>
.color1 {
background-color: {{pickcolor}};
width: 30px;
height: 30px;
}
.color2 {
background-color: {{pickcolor}};
width: 30px;
height: 30px;
}
</style>
There is no underline problem with my {{pickcolor}}
Your style.css file is probably not templated. I do not know about your exact project config but static files are usually not templated in general.
If you want to template your CSS file, first move it to the templates folder (usually templates), you will then have to create a view for it and use the URL of that view instead of a link to a static file. e.g.
from flask import make_response, render_template
#app.route('/style.css')
def style():
pickcolor = ... # whatever
# we explicitly create the response because we need to edit its headers
response = make_response(render_template('style.css', pickcolor=pickcolor))
# required to make the browser know it is CSS
response['Content-type'] = 'text/css'
return response
Then, in your HTML template
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ url_for('style') }}">
</head>
<!-- ... -->
</html>
Related
I am trying to build a web-app which extracts and inputs information about different city buildings using Python, Flask and HTML. At the moment I want to create a button which after clicking it will give me a list of all the buildings available on the database. The database is populated and stored in PostgreSQL. The problem is that the button is created and displayed but the list is not. I used the second answer on this link as a reference.
My Python code looks like as follows :
app = flask.Flask(__name__)
#app.route('/')
def home():
return flask.render_template('interface.html')
#app.route('/GetBuildingsLists', methods = ['GET','POST'])
def GetBuildingsLists():
print('Connecting to the PostgreSQL database...')
db = pg.connect(
host="****",
database="****",
user ="****",
password="*****")
db_cursor = db.cursor()
print('PostgreSQL database version:')
db_cursor.execute('SELECT version()')
q = ("SELECT building_id FROM table1")
db_cursor.execute(q)
buildings = db_cursor.fetchall()
unique_buildings = list(dict.fromkeys(buildings))
db_cursor.close()
#print(unique_buildings)
return flask.render_template('interfaceLists.html', unique_buildings = unique_buildings)
if __name__ == '__main__':
app.run()
Meanwhile, on a template folder I have interfaceLists.html as below :
<html>
<head>
<title>Results</title>
<style>
.links-unordered {
display: inline-block;
position: relative;
}
.links-unordered {
margin-top: 20px;
min-height: 30px;
}
.links-unordered .toggle-button {
text-decoration: none;
padding: 12px 16px 12px 16px;
transition: 0.2s;
border: 1px solid black;
}
.links-unordered .toggle-button:hover,
.links-unordered .toggle-button:active,
.links-unordered .toggle-button:focus,
.links-unordered .toggle-button:visited {
text-decoration: none;
color: black;
}
.links-unordered .toggle-button:hover {
border-width: 2px;
}
.links-unordered ul {
position: absolute;
top: 10px;
margin-top: 25px;
padding-inline-start: 20px;
}
.links-unordered ul li {
line-height: 25px;
padding-left: 15px;
}
.links-unordered a {
text-decoration: none;
color: black;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="demo_script_src.js"></script>
<div class="links-unordered">
<a class="toggle-button" href="#">Buildings</a>
{% for building in unique_buildings %}
<ul style="display:none;">
<li>building[0]</li>
</ul>
{% endfor %}
</div>
</body>
</html>
I take the results from the PostgreSQL using a query in the python code and store them in the list called unique_buildings. I have tried to display afterwards the results as an unordered list but the list is not displayed.
The .js file mention in the HTML file performs the animation while using the button and it looks like this :
$(document).ready(function() {
$(".toggle-button").click(function() {
$(this).parent().find("ul").slideToggle(function() {
// Animation complete.
});
});
})
Can someone please help me by telling what might be wrong with my script and why what I want is not working? Thank you!!
I have a flask app that executes scripts using exec(script_name, globals()) and is running in Google Cloud Run using a docker. All my scripts are in Google Cloud storage. So I use gcsfs module to read the scripts from GCS and execute.
For eg:
exec(gcs_file_system.open(<script_from_cloud>).read(), globals())
But the problem I am facing is that, whenever there is a new package to be imported, I need to first install that package through my flask app using exec() function. As far, I have tried using
1. exec("os.system('pip install package_name')", globals())
2. exec("subprocess.check_call([sys.executable, '-m', 'pip', 'install', package_name])", globals())
3. import pip
pip.main(['install', package_name])
4. import pip
exec("pip.main(['install', package_name])", globals())
5. os.system('pip install package_name')
6. subprocess.check_call([sys.executable, '-m', 'pip', 'install', package_name])
All these were tried executing in a script script.py which i call using
exec(gcs_file_system.open('bucket_name..../script.py').read())
Everytime i try any of these, I either get an upstream disconnect error or the script simply fails. I really need some help or suggestion on how to install a package through a flask app that is running in the cloud (Google Cloud Run).
Installing a package can be done by defining another route function just for installing a package.
This was done by providing the below statement in a separate route function rather than specifying to install the package in another exec(script) function inside a route function.
exec("os.system('pip install " + str(packages) + "')", globals())
Server.py
#app.route('/add_package', methods=['GET', 'POST'])
def add_package():
return render_template('add_package.html')
#app.route('/add_package_success', methods=['GET', 'POST'])
def add_package_success():
code_content = request.form.get("code_editor", "").split("\n")
for empties in range(code_content.count("")):
code_content.remove("")
code_content = [packages.strip().replace("\n", "") for packages in code_content]
for packages in code_content:
exec("os.system('pip install " + str(packages) + "')", globals())
return render_template('add_package_success.html')
add_package.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Packages</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/codemirror.css') }}">
<script type="text/javascript"
src="{{ url_for('static', filename='codemirror.js') }}"></script>
<script type="text/javascript"
src="{{ url_for('static', filename='python.js') }}"></script>
<style>
.center {
width: 15%;
border: 2.5px solid red;
}
.header{
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: bold;
position: relative;
left: 10%;
}
.body_text{
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.info_div{
height: 180px;
width: 50%;
position: absolute;
left: 50px;
display: none;
z-index:100;
}
.info{
height: 15px;
width: 15px;
background-color: yellow;
position: relative;
left: 30px;
border: solid red;
text-align: center;
font-weight bold;
font-family: Arial, Helvetica, sans-serif;
}
.info:hover{
cursor: help;
}
.info:hover + .info_div{
display: block;
}
.submit_btn_2 {
color: white;
border: solid;
position: relative;
background-color: #003280;
width: 170px;
height: 30px;
}
.submit_btn_2:hover {
background-color: #575558;
cursor: pointer;
}
</style>
</head>
<body>
<form action="/add_package_success" method="post">
<div class="center">
<p class='header'>Add Packages</p><input class='info' value='?' readonly<br/><br/>
</div><br/>
<div>
<a class="body_text" style="border: 2px #020d36 solid;color: #3a18a5;text-align: left;">Enter the Packages name (one in each line): </a><br/><br/>
<textarea name="code_editor" id="code_editor"></textarea><br/><br/>
<button type="submit">Add</button><br/><br/>
<button formaction="/" style="left: 0px; top: 10px; width: 100px; height: 30px;" class = "submit_btn_2" type="submit"> Home </button>
</div>
</form>
</body>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code_editor"), {
mode: {name: "python",
version: 3,
singleLineStringErrors: false},
lineNumbers: true,
indentUnit: 4,
matchBrackets: true
});
</script>
</html>
add_package_success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Code Edited</title>
</head>
<body onload="load_function()">
</body>
<script>
function load_function(){
if(alert("Package Installed.\n\nPress OK to go HOME.")){
window.location.href = "{{ url_for('index') }}";
}
window.location.href = "{{ url_for('index') }}";
}
</script>
</html>
index.html
<form method='post' action='/'>
<button class = "submit_btn_2" formaction="/add_package" id='add_package' style="position: absolute; top: 210px; left:1230px; height: 30px;" name="add_package">Install Packages</button>
</form>
I'm having trouble linking my static "css" file. When I run the code I only get my basic html and not the css. When I use the html element all of my css code work fine. Here is my code:
h1 {
padding: 60px;
text-align: center;
background: #1abc9c;
color: white;
font-size: 30px;
}
.header {
padding: 60px;
text-align: center;
background: #1abc9c;
color: white;
font-size: 30px;
}
.sidebar {
height: 200px;
width: 150px;
position: sticky;
top: 0px;
float: right;
margin-top: 100px;
padding-top: 40px;
background-color: lightblue;
}
.sidebar div {
padding: 8px;
font-size: 24px;
display: block;
}
.body-text {
margin-right: 150px;
font-size: 18px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Header</h1>
<div class="sidebar">
<div>Menu Item 1</div>
<div>Menu Item 2</div>
<div>Menu Item 3</div>
</div>
<div class="body-text">
<!-- body content -->
</div>
</body>
</html>
Here is my python code also in case that is causing a problem:
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
app.config['ENV'] = 'development'
app.config['DEBUG'] = True
app.config['TESTING'] = True
app.static_folder = 'static'
#app.route('/')
def index():
return render_template('base.html')
#app.route('/<name>')
def user(name):
return f"Hello {name}!"
#app.route('/admin')
def admin():
return redirect(url_for('index', name='Admin'))
if __name__ == '__main__':
app.run()
Thanks for any help. Sorry if the code is messy, I'm a rookie :).
In addition to the answer given above, this might also occur sometimes if your browser has already cached the CSS file. You can force your browser to refresh the contents using Ctrl+f5 on your keyboard each time you add new code in your style.css file.
This may be an issue with the structure of your application. Consider this structure:
project_folder
| --- app/
| --- templates/
| --- index.html
| --- static/
| --- style.css
The templates sub-folder should be at the same location as the static sub-folder. Your link should work just with this structure.
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
For a personal website I would like to randomly select a background picture (out of 4) for my starting page using flask. When try to create a HTML template (with inline CSS for formatting), the resulting HTML does not display the picture chosen at random.
So far I have tried to use url_for(), as I thought the problem might be that jinja cannot find the files, but this does not resolve my problem.
I also looked at the whitespace and delimiters, which seem to be correct in my mind.
The code from my app.py:
flask import Flask, render_template
import random
app = Flask(__name__)
#app.route('/')
def index():
intt = random.randint(1, 4)
random_number = ("../Images/artwork/{}.jpeg".format(intt))
return render_template('index.html', random_number=random_number)
The code in my HTML file:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#font-face {
font-family: "Pretoria Gross";
src: url("../Fonts/Pretoria.ttf");
}
ge {
color: Yellow;
font-family: Pretoria Gross;
font-size:70px;
text-align: center;
display:inline-block;
position:relative;
width:100%;
background: url('../Images/artwork/{{random_number}}.jpeg') no-repeat top center;
background-position: center top;
background-size: 25% auto;
}
</style>
<a href="about.html">
<ge>Website<br/>Title<br/>here</ge>
</a>
The resulting HTML does not render the CSS. Where do I go wrong?
Many Thanks
random_number is already storing the desired path. Change url in the css:
background: url('{{random_number}}') no-repeat top center;
Or, you can simply pass intt to the template, and keep the original css templating:
return render_template('index.html', random_number=intt)
I am working through Learn Python The Hard Way, and am currently working through exercise 51. In it, the student is asked to try building out some basic web applications using the web.py framework. The first study drill is to improve the quality of the HTML layouts so that the applications are built on well-formatted pages. I am looking to make a template layout that applies to all pages in the application, and leverages a CSS stylesheet to provide the formatting. I would like for the CSS formatting to be external, rather than within the HTML file. For some reason, no matter how I format the path to 'main_layout.css' I cannot get the formatting changes to take effect. I have tried the path with a leading '/' and without the leading '/'. I have tried moving the CSS file into another folder (the root folder, and the templates folder). I tried emptying my browser cache in case that was causing in issue. I tried accessing the 'static' directory and the 'main_layout.css' file itself directly through my browser, which I was able to do in both cases--the files is in there, but I can't get it to accept the formatting markup from 'main_layout.css'. I googled this issue, checked the google group for web.py, and searched stackoverflow--in all cases, the answers were related to the path to the css file, which I believe I have fully explored and attempted to fix to no avail.I have tried all suggestions I could find on the web, and I am stumped. My code is as follows:
/bin
app.py
/ex51
/static
main_layout.css
/templates
hello_form.html
index.html
layout.html
/tests
app.py is written as follows:
import web
urls = (
'/hello', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base="layout")
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="Nobody", greet="Hello")
greeting = "%s, %s" % (form.greet, form.name)
return render.index(greeting = greeting)
if __name__ == "__main__":
app.run()
index.html written as follows:
$def with (greeting)
$if greeting:
I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>
$else:
<em>Hello</em>, world!
hello_form.html written as follows:
<h1>Fill out this form</h1>
<form action="/hello" method="POST">
A Greeting: <input type="text" name="greet">
<br/>
Your Name: <input type="text" name="name">
<br/>
<input type="submit">
</form>
main_layout.css written as follows:
html, body {
height: 100%;
}
.container {
width:800px;
}
.container #body_container {
margin: 10px auto;
padding-bottom: 50px;
min-height: 100%;
text-align: center;
overflow: auto;
}
.container #footer_container {
margin-top: -50px;
height: 50px;
}
and layout.html:
$def with (content)
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/main_layout.css" />
<title>This is My Page</title>
</head>
<body>
<div class="container" id="body_container">
$:content
</div>
<div class="container" id="footer_container">
Hello World
</div>
</body>
</html>
Thanks in advance for your help.
Edit: One additional bit of information--I am running this script from the PowerShell of my Windows 7 PC, and accessing it at http://localhost:8080/hello through Google Chrome.
You are commenting out the CSS file using a octothorp (#) which is incorrect for a CSS document (but correct for Python, which is where the confusion is). Use /* to comment out your code in a CSS document. Like this:
.container /*body_container*/ {
margin: 10px auto;
padding-bottom: 50px;
min-height: 100%;
text-align: center;
overflow: auto;
}