Using FontAwecome icon in Flask table - python

I have a pandas dataframe that I'm displaying as HTML in my Flask app and would like to add a Font Awesome icon as a column in that table and repeat it based on a count for each group. For example, in this scenario:
Group
Count
Icon
A
1
B
2
I want the icon to be repeated once for Group A and twice for Group B. I'm able display icons in my navbar after downloading the flask-fontawesome package. The unicode/<i> tag (not sure which one is needed) are:

<i class="fa fa-trophy" aria-hidden="true"></i>

same way as you would include a font-awesome icon in HTML. Within a <span> with appropriate class
repeat <span> as many times as required
consider need to undo escaping of < and >
this is running in Jupyter, but same would be true for flask
import io
import pandas as pd
df = pd.DataFrame({'Group': ['A', 'B'], 'Count': [1, 2]})
df = df.assign(Icon=df["Count"].apply(lambda n: n*'<span class="fab fa-docker"></span>'))
from IPython.core.display import display, HTML
display(HTML(df.to_html().replace("<","<").replace(">",">")))
integrated into flask
same code used to generate font awesome icons based on Count
undone escaping of < and >
included link to needed CDN for font awesome
simple approach of using f-string to generate a html document
import pandas as pd
from flask import Flask, render_template, Response, jsonify
app = Flask(__name__)
#app.route('/')
#app.route('/home')
def home():
df = pd.DataFrame({'Group': ['A', 'B'], 'Count': [1, 2]})
df = df.assign(Icon=df["Count"].apply(lambda n: n*'<span class="fab fa-docker"></span>'))
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>SO example</title>
</head>
<body>
{df.to_html().replace("<","<").replace(">",">")}
</body>
</html>"""
if __name__ == '__main__':
app.run(debug=True, port=3000)

Related

how can i show css animation in my html using flask?

im a begginer here , struggling with basic stuff
I have my flask:
from flask import Flask , render_template , send_file , send_from_directory
import os
app = Flask(__name__)
#PRIMERA FUNCION
#app.route('/')
def index():
return render_template('prueba.html')
and i have my html :
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - The Arrow</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div class="arrow-1"></div>
<!-- partial -->
</body>
</html>
when I open the html file on browser it shows the css ,
but when I run flask css doesnt show and I cant figure out why!!!
I have try this
#app.route('/css/<path:filename>')
def css_file(filename):
file_path = os.path.join('css', filename)
return send_file(file_path)
and i also thought it was a problem of my folder layout but I already tried re arrange folders
Flask has different ways to do this, but the convention is to put static assets (like CSS) in the static directory (which should be at the root of your project) and link them in with Jinja and the url_for() function. so in your case it would look like this:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - The Arrow</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
More explained in the Flask docs

how can I deploy Dash components on html script?

I'm newbie in python Dash.
And I'm currently developing a website combine with Python Flask and HTML.
I already made some functions that shows some graph like data visualization by routing them as a independent HTML scripts.
but it was too static to deliver the insights I want to show. and I figured out Dash, and I'd like to route and deploy Dash components(like figure) on my own html scripts by integrating exist project.
As far as I known, I need to declare app.layout = html.Div([<contents>]) in advance before running server.
but by doing so, I couldn't load dash ouputs.
this is the result I want to get.
goal to achive
this is the source of app.py
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import numpy as np
import pandas as pd
from flask import Flask, send_file, render_template, make_response, request, redirect, url_for, session, flash
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
df = pd.read_csv('https://gist.githubusercontent.com/chriddyp/5d1ea79569ed194d432e56108a04d188/raw/a9f9e8076b837d541398e999dcbac2b2826a81f8/gdp-life-exp-2007.csv')
fig = px.scatter(df, x="gdp per capita", y="life expectancy",
size="population", color="continent", hover_name="country",
log_x=True, size_max=60)
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure=fig
)
])
#server.route("/main")
def main():
fig = app.layout
return render_template('main.html',figure = fig)
and this is my html script, main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
Administrator
</title>
</head>
<body>
<h1>Hi this is the results!</h1>
<div>
<h2>Dash outputs</h2>
{{figure}}
<div>
</body>
</html>
any helps? Thank you so much in advance and happy new year!
To embed a Dash app as an iframe, run the dash app in a separate python process and then use the iframe markup to embed it by URL: <iframe src="the-url-of-your-dash-app" style="border: none;"/>
Above quote source.
I ran this for your code by using the following for main.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
Administrator
</title>
</head>
<body>
<h1>Hi this is the results!</h1>
<div>
<h2>Dash outputs</h2>
<iframe src="./" style="width: 400px; height: 400px;"/>
<div>
</body>
</html>
and modifying main():
#server.route("/main")
def main():
fig = app.layout
return render_template('main.html')

How can I run a Python script on one HTML page, and print the results on another?

I have a Flask app where I want to click a button on the home page, which will
On click, run Python script and route to my results.html. (which i have done)
Auto-fill certain fields on that page with results from a python script. (what i need help with)
The python script (parser.py) may take a 30-40 minutes to run, as its job is to start a test that takes about that long, then process and grab/parse the results. After that, some other fields will be filled in by the user, then the form on results.html is submitted to a database.
I hope i'm closer to my answer than I think, but where/how do I introduce my python into this and pass it into the form on results.html?
parser.py
import csv
import pandas as pd
import numpy as np
# Test data
body = pd.read_csv('path-to-test-data.csv', skiprows=11)
# Build dataframe of test info
frame = body['Frame Size']
loss = body['Loss Rate (Percent)']
speed = body['Tx Rate (L1) (Bit/s)']
grade = body['Result State']
lst = pd.concat([frame,loss,speed,grade], axis = 1)
selected_df = pd.DataFrame(data=lst)
selected_df.set_index('Frame Size')
# Select all 64b frame results
print(selected_df[np.isclose(selected_df['Frame Size'].values[:, None], [64],).any(axis=1)])
# Select all tests that fail
print(selected_df.loc[selected_df['Result State'] == 'FAIL'])
app.py:
import os
from flask import Flask, escape, request, redirect, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html')
#app.route('/results/')
def about():
return render_template('results.html')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OLT TESTER</title>
</head>
<body>
<div class="index">
Press This Button to Begin Testing
<button onclick=""></button>
</div>
</body>
</html>
results.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Results</title>
</head>
<body>
<div class="results">
Initialize Test
<form action="#.php" method="post">
Job Order: <input type="text" name="jobOrder"><br>
Serial Number: <input type="text" name="serialNo"><br>
Frame Size: <input type="text" name="jobOrder"><br> <!--Fill this field with Python output -->
Result State: <input type="text" name="serialNo"><br> <!--Fill this field with Python output -->
<input type="submit">
</form>
</div>
</body>
</html>

Why can't I console log data from my flask application? I am using jinja

I am trying load data into my flask page, and console log it, however I keep getting the below error
VM165:1 Uncaught ReferenceError: data is not defined
at <anonymous>:1:13
These are the code snippets from my .py and .html
import os
from flask import Flask, render_template, jsonify, request, redirect
import json
app = Flask(__name__)
#app.route("/")
def home():
json_file = open("/Users/-------/Documents/GitHub/Geospatial-Opportunities-for-Supermarkets/supermarket_locations/longos_locations.json", "r", encoding ="utf-8")
data = json.load(json_file)
json_file.close
return render_template("index.html", data = data)
<!DOCTYPE html>
<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">
<title>Supermarkets in Toronto</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.0-rc.3/dist/leaflet.css" />
<link rel="stylesheet" type="text/css" href="static/css/style.css">
<script> var data = '{{data}}'; </script>
</head>
Looks like I had 2 index.html files and I was using the wrong one

Bokeh Problem Rendering Plot in Flask App

My flask driven app works as expected with the high level Bar plot from Bokeh.
I now want to change the plot to a horizontal bar plot and found this SO answer.
My code minus the formatting for brevity:
from flask import Flask, render_template
from bokeh.embed import components
from bokeh.util.string import encode_utf8
from bokeh.plotting import figure
import pandas as pd
app = Flask(__name__)
#app.route('/')
def test():
kws = ["one", "two", "cat", "dog"]
count = [23, 45, 11, 87]
df = pd.DataFrame({"kw": kws,
"count": count
})
df.sort("count", inplace=True)
df.set_index("kw", inplace=True)
series = df['count']
p = figure(width=1000, height=1000, y_range=series.index.tolist())
j = 1
for k, v in series.iteritems():
w = v / 2 * 2
p.rect(x=v/2,
y=j,
width=w,
height=0.4,
color=(76, 114, 176),
width_units="screen",
height_units="screen"
)
j += 1
#### get components ####
script, div = components(p)
page = render_template('test.html', div=div, script=script)
return encode_utf8(page)
if __name__ == "__main__":
app.run(debug=True,
threaded=False
)
Located in templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.9.0.min.css" rel="stylesheet" type="text/css">
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.9.0.min.js"></script>
</head>
<body>
{{ div | safe }}
{{ script | safe }}
</body>
</html>
This answer works in testing with show(p). However the actual application takes the p object and gets the components div and script and embeds those in html.
When I run the app with debug=True I do not get an error just a hanging page.
EDIT: "Hang" is not accurate. I get a blank page.
Following Bigreddot's advice, I checked my version of Bokeh and adjusted the BokehJS version to match.
conda list bokeh yielded:
bokeh 0.10.0 py27_0
I then changed my html and the minimal example works as expected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.css" rel="stylesheet" type="text/css">
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.js"></script>
</head>
<body>
{{ div | safe }}
{{ script | safe }}
</body>
</html>
In case anyone comes across this from now on please note that bokeh.util.string import encode_utf8 has been removed since bokeh==2.0.0
In my case, with a flask app (using flask==1.1.2 and bokeh==2.0.2), I was simply able to delete this line from the code and in the html render template, just return html rather than return encode_utf8(html).

Categories