How to add custom font in python-flask? - python

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>

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.

Flask, url_for() not linking static file

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

How to add images in CSS file? I am using python flask for website development

Everything was working fine before Python Flask. Now I tried to connect my HTML page with Python Flask. CSS is working fine but when I define images inside the CSS file the image is no longer loaded into the web site. Instead it is showing error 404.
python app.py code
from flask import Flask, render_template, url_for
app = Flask(__name__ , static_url_path='/static')
#app.route('/')
def index():
return render_template('/intro.html')
if __name__ == '__main__':
app.run(debug=True)
HTML code :-
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title>NewliFit</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://unpkg.com/aos#next/dist/aos.css" />
<link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename = 'css/owl.theme.default.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/firstone.css') }}">
</head>
<body>
<div class="main">
<div class="cover-image">
<div class="menu">
<div class="leftmenu">
CSS file
#charset "utf-8";
/* CSS Document */
*{
margin: 0px ;
padding: 0px ;
}
/* ------------cover image -------------*/
.cover-image {
background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});
background-size: 100% 100%;
width: 100%;
height: 110vh;
}
Please help.
You are using url_for in a CSS file, which does not work. You need to specify the url of the background image either in the HTML file, or specify a proper URL in your CSS.
So either add this to your CSS:
background-image: url('/static/images/cover4.jpg')}});
Or change your cover-image div in your HTML file to this:
<div class="cover-image" style="background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});">
Unless you plan on changing your static folder (or your cover image) regularly, I would advise going the first route, to make sure you separate style and semantics.

how can i solve html5_webcam problem on the website?

there is a problem about html5 webcam
this is the error i have
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
at photo.js:17
photo.js :17
video.src=vendorUrl.createObjectURL(stream);
please check my code
thank you so much!
takeing_photo.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Document</title>
<link href="{% static 'css/photo.css' %}" rel="stylesheet">
</head>
<body>
<div class="booth">
<video id="video" width="400" height="300"></video>
Take photo
<canvas id="canvas" width="400" height="300"></canvas>
<img id="photo" src="http://placekitten.com/g/400/300" alt="photo of you">
</div>
<script src="{% static 'js/photo.js' %}"></script>
</body>
</html>
photo.js
(function(){
var video = document.getElementById('video'),
photo = document.getElementById('photo'),
context = canvas.getContext('2d'),
phto = document.getElementById('photo');
vendorUrl = window.URL || window.webkitURL;
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video:true,
audio:false
}, function(stream){
video.src=vendorUrl.createObjectURL(stream);
video.play();
}, function(error){
});
document.getElementById('capture').addEventListener('click', function(){
context.drawImage(video, 0, 0, 400, 300);
photo.setAttribute('src', canvas.toDataURL('image/png'))
});
})();
photo.css
.booth{
width:400px;
background-color: #ccc;
border:10px solid #ddd;
margin:0 auto;
}
.booth-capture-button {
display:block;
margin:10px 0;
padding:10px 20px;
background-color: cornflowerblue;
color: #fff;
text-align: center;
text-decoration: none;
}
#canvas {
display :none;
}
i just want to make webcam properly
and i m wondering there is a way to save the pics into the folder when i put the button "take of you"
please give me advice. thank you so much.
This error is caused because the function createObjectURL is deprecated. You need to update your code to set srcObject to the video object directly.
video.srcObject=stream;

Cannot load HTML file with QWebEngineView.setHtml()

The solution of my problem is probably very simple but yet out of my understanding. I am trying to load an HTML file into a QWebEngineView with PyQt5. The way I am doing it is:
self.webView = QtWebEngineWidgets.QWebEngineView(self.splitter)
html = r"C:\DATI\git\webgis\map.html"
self.webView.setHtml(html)
The only thing I get is a string representing the path and name of my HTML file:
C:\DATI\git\webgis\map.html
My map.html looks like this:
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.5.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.5.0/build/ol.js"></script>
<script src=".js/qwebchannel.js"></script>
<style>
body { padding: 0; margin: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="./js/map.js"></script>
</body>
</html>
Strangely (to me at least), if I do self.webView.setHtml("<html><head></head><body><h1>ciao</h1></body></html>"), this will render the HTML properly.
What am I missing?
The setHtml method does exactly what its name suggests: it loads html content from a string. What you are trying to do is load a url, so for that, you need to use the load method:
url = QtCore.QUrl.fromLocalFile(r"C:\DATI\git\webgis\map.html")
self.webView.load(url)

Categories