Flask, url_for() not linking static file - python

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') }}">

Related

Passing variable from flask to html adds "

I'm trying to pass a variable from flask to my html code. I'm adding it as a url for a button, so a user can follow it. My problem is that the buttons don't work an when inspecting the website I see that the variables have had " added to them. Removing this makes the buttons work.
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Testing buttons">
<meta name="keywords" content="Test">
<style>
h1 {
font-family: Arial, sans-serif;
color: #2f2d2d;
text-align: Center;
}
p {
font-family: Arial, sans-serif;
font-size: 14px;
text-align: Center;
color: #2f2d2d;
}
</style>
</head>
<body>
<h1>Results</h1>
<p>Click the buttons below to go to your results: </p>
<button onclick={{ value1 }}>
Yandex.com
</body>
</html>
Value1 in my python code:
input1 = (str(""""window.location.href='""")
+ str(img_search_url) + str('''';"'''))
return render_template('results.html', value1=input1)
For testing purposes let img_search_url = https://yandex.com/images/search?cbir_id=1865182%2F7z8tGw017Oxvkl-ZRGX7jA6207&rpt=imageview&lr=123432
Thanks
You need to use the |safe filter as mentioned on other SO answers.
<button onclick={{ value1|safe }}>
This ensures that the auto unescaping is turned off. If you do it on untrusted data, it can easily lead to XSS vulnerabilities though.

Some CSS is not working after adding "extends/base.html"

I am building a toggle button and i am using some CSS but when i try to run code then one CSS command is not working. When i remove {% extends 'base.html' %} then it works perfectly but after adding it doesn't load a function.
toggle.html
{% extends 'mains/base.html' %}
{% load static %}
{% block content %}
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<style>
#media screen and (max-width: 700px) {
body {
padding: 170px 0 0 0;
width: 100%
}
}
a {
color: inherit;
}
.menu-item,
.menu-open-button {
background: #EEEEEE;
border-radius: 100%;
width: 80px;
height: 80px;
margin-left: -35px;
margin-top: 230px;
position: absolute;
color: #FFFFFF;
text-align: center;
line-height: 3em;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
-webkit-transition: -webkit-transform ease-out 200ms;
transition: -webkit-transform ease-out 200ms;
transition: transform ease-out 200ms;
transition: transform ease-out 200ms, -webkit-transform ease-out 200ms;
}
</style>
base.html
{% load static %}
Other links.......
.......
......
{% block content %}
{% endblock %}
line-height: 100px; is not working after adding extends base.html, which is necessary.
I have searched everywhere, and I have also tried by deleting every element on base.html, then I notice that after deleting every single link it is working.
Any help would be much appreciated. Thank you in advance.
There is an CSS that override your CSS, make sure that link to your CSS is the last in base.htnl.
In your ‘base.html’ add a block called ‘head’ between ‘’ and ‘< /head> and your style tag to it.
CSS can be only applied in HEAD not in body like JS
I added this in base.html :-
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
AND It Worked

Is there any way to install python packages through flask app?

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>

Flask static css file

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>

How to add custom font in python-flask?

I have tried using #fontface css style, but the font doesn't get rendered.
Is there another way of doing this using python/flask??
<!DOCTYPE html>
<html>
<style type="text/css">
#font-face {
font-family: trial;
src: url_for('CENTRALESANSCND-BOLD.otf') ;
font-weight:bold; }
</style>
<body>
<p style="font-family:trial; font-weight: bold"> Hello </p>
</body>
</html>
The above is my HTML template.
Unfortunately, when I render it using Flask, it doesn't reflect the font.
The following is my .py code:
from flask import Flask, render_template
app=Flask(__name__)
app.secret_key='1234'
#app.route('/', methods=['post', 'get'])
def output():
c=2+3
print c
return render_template('f.html', c=c)
if __name__=='__main__':
app.run(port=9876)
Thanks a lot for all your help.. A combination of all the suggestions finally worked.
Posting the solution here:
CSS file:
#font-face{
font-family: trial;
src: url('CENTRALESANSCND-BOLD.otf');
font-weight: bold;}
body {font-family: georgia; color:green}
h1 {font-family:trial; color: pink}
HTML file:
<!DOCTYPE html>
<html>
<link type="text/css" rel="stylesheet" href="{{url_for('static', filename='mystyle.css')}}"/>
<body>
<p > Hello... </p>
<h1> welcome </h1>
</body>
</html>
url_for takes a function name, and you need to wrap it in double curly brackets... try:
<style type="text/css">
#font-face {
font-family: trial;
src: {{ url_for('static', filename='CENTRALESANSCND-BOLD.otf') }};
font-weight:bold; }
</style>
<style>
#font-face {
font-family: FontName;
src: url("{{ url_for('static', filename='FontFile.otf') }}");
}
</style>

Categories