I'm new to Flask and
I'm trying to create a Stumbleupon like website but I'm having problems while loading the content into an iFrame. I just cant figure it out how to iterate through each url and load them into the iFrame while clicking in the <a> tag.
Here is what I've done:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
return render_template('index.html', urls=urls)
if __name__ == "__main__":
app.run(debug=True)
templates/layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="/static/css/foundation.css"/>
</head>
<body>
<nav class="top-bar">
<h3 align="center">Stumble</h3>
</nav>
{% block content %}
{% endblock content %}
</body>
</html>
templates/index.html
{% extends 'layout.html' %}
{% block content %}
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="????????" frameborder="0"></iframe>
{% endblock content %}
After adding import random at the top of your app.py file you could structure your code like this:
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
iframe = random.choice(urls)
return render_template('index.html', iframe=iframe)
Then access the value in your template:
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="{{ iframe }}" frameborder="0"></iframe>
And simply set the Stumble button to refresh the page.
<h3 align="center">Stumble</h3>
This will be pretty basic, but it will have the behaviour you're describing.
An improvement will be to use the session object to make sure that two subsequent requests do not display the same page inside the iframe.
Related
1. Background:
I am new to Flask, JavaScript or web development. I am currently trying to build an interface for a project of mine, which does extract the linear area of a curve. So far so good, my python code works: It reads data from an .csv or .xlsx file and returns the area, it's slope and plots for each sample. Now I am desperately trying to put them in some kind of user interface, so you can decide which ones to plot. I recognized image-picker (github.com/rvera/image-picker) as a suitable tool for the job, so I decided to implement it into my project. For this I started to build a simple test-page with the image-picker.
2. Problem
Unfortunately, I wasn't able to achieve this. Instead of seeing a list of the image names followed by the pictures, I can only get the list. I will add screenshots of the outcomes.
3. My Code
The project structure
Both, image-picker.css and image-picker.js are taken from the image-picker github
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{{ url_for('static', filename = 'css/main.css') }}">
{% block head %} {% endblock %}
</head>
<body>
{% block body %} {% endblock %}
</body>
</html>
img_picker.html
{% extends 'base.html' %}
{% block head %}<title>Image Picker</title> {% endblock %}
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='image-picker.css') }}">
<script src="{{ url_for('static', filename='image-picker.js') }}" type="text/javascript"></script>
{% block body %}
<select multiple="multiple" class="image-picker show-html">
<option data-img-src='http://placekitten.com/220/200' value='1'>Cute Kitten 1</option>
<option data-img-src='http://placekitten.com/180/200' value='2'>Cute Kitten 2</option>
<option data-img-src='http://placekitten.com/130/200' value='3'>Cute Kitten 3</option>
<option data-img-src='http://placekitten.com/270/200' value='4'>Cute Kitten 4</option>
</select>
<script> $('.image-picker').imagepicker();
</script>
{% endblock %}
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('img_picker.html')
if __name__ == '__main__':
app.run()
main.css
body{
margin: 0;
font-family: sans-serif;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
How it looks
How it should look
(The website I took the example from: https://rvera.github.io/image-picker/)
If you need any more information, I will be glad to provide it. There has been another question regarding this problem before, but it wasn't solved.
Thanks for any help,
Carroll
This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 1 year ago.
I have been trying for the last 45 minutes to figure out how to get my favicon on my flask page.
Here is my current code:
from flask import Flask, render_template, send_from_directory, url_for
import os
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route("/store")
def store():
return render_template("store.html")
#app.route("/games")
def games():
return render_template("games.html")
#app.route("/americanstudios")
def americanstudios():
return render_template("as.html")
#app.route("/pear")
def pear():
return render_template("pear.html")
#app.route("/favicon.ico")
def fav():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', minetype='image/vnd.microsof.icon')
if __name__ == "__main__":
app.run(debug=True)
With the base html being this:
<!DOCTYPE html>
<html>
<title>{% block title %}{% endblock %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font- awesome.min.css">
<head>
<link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}">
</head>
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Raleway", Arial, Helvetica, sans-serif}
</style>
<body class="w3-light-grey">
<!-- Navigation Bar -->
<div class="w3-bar w3-white w3-large">
</i>newtech
Store
Games
American Studios
PEAR Electronics
Log In
</body>
<div class="w3-main" style="margin-left:250px">
<div class="w3-row w3-padding-64">
<div class="w3-twothird w3-container">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</html>
And this is index.html
{% extends "base.html" %}
{% block title %}newtech inc.{% endblock %}
{% block content %}
<h1 class="w3-text-teal">Home</h1>
<p>Welcome to newtech inc, where we have the coolest new items for all purposes. Whether it's a new movie to watch, or a fun game, or maybe something else, we're here for you.</p>
{% endblock %}
The only line in head in base.html should load my favicon from the static folder as the favicon for the page. But for some reason, the favicon stays as the default favicon for the index page and all other pages.
My favicon is a 64 X 64 .ico file
And it is located in my static folder
And yes the static folder is in the same directory as main.py
But even with all of this the favicon still does not show up.
And yes I am running the correct main.py
Also tried this
Yet no luck. Can anyone help me?
to look for network error, you would need to look at the network tab of the dev tools. it shows that your get for favicon.ico is failing with 404. fix? add static folder to your app (refer 1 in code), and the add get for favicon and return the file - refer 2 in code.
from flask import Flask,render_template,send_from_directory
app = Flask(__name__, static_folder='static') # 1 ( either add here or add through some os join)
import os
#app.route("/")
def home():
return render_template("index.html")
#app.route("/static/favicon.ico") # 2 add get for favicon
def fav():
print(os.path.join(app.root_path, 'static'))
return send_from_directory(app.static_folder, 'favicon.ico') # for sure return the file
if __name__=="__main__":
app.run(debug=True)
the folder structure will be like :
Did you check out the Flask documentation already? They recommend a slightly different reference than what you have there:
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/?highlight=favicon
Can't seem to get my style sheet to link, can someone please tell me why?
I'm trying to set up an sample instance with a database, ran on Flask.
I thought it was my folder location, but I've double checked it is on the right place and can't figure out why, spent hours trying to fix it.
My HTML:
{% extends "layout.html" %}
{% block title %}
CS50_Web_Project1
{% endblock %}
{% block body %}
<h1>Login to CS50_Web_Project1</h1>
<form action="{{ url_for('register') }}" method="POST">
<button>Register</button>
</form>
{% endblock %}
My layout.html:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<!-- #olaf: own link to own style sheet-->
<link rel="stylesheet" href="css/style.css" type="text/css" >
<!-- #olaf: copied from https://bootsnipp.com/snippets/GaEOX-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
My CSS in css/style.css location:
/* style.css */
.note
{
text-align: center;
height: 80px;
background: -webkit-linear-gradient(left, #0072ff, #8811c5);
color: #fff;
font-weight: bold;
line-height: 80px;
}
.form-content
{
padding: 5%;
border: 1px solid #ced4da;
margin-bottom: 2%;
}
.form-control{
border-radius:1.5rem;
}
.btnSubmit
{
border:none;
border-radius:1.5rem;
padding: 1%;
width: 20%;
cursor: pointer;
background: #0062cc;
color: #fff;
}
My application.py:
import os
from flask import Flask, session, render_template, jsonify, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
#from the internet...# app.config['DATABASE_URL'] = "path_to_db"
# Check for environment variable
if not "DATABASE_URL":
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Set up database
engine = create_engine("DATABASE_URL")
db = scoped_session(sessionmaker(bind=engine))
#olaf: create a login page that has a form, containing "login" & "register" button
#app.route("/")
def index():
return render_template("index.html")
#olaf: Login button
#app.route("/register", methods=["POST"])
def register():
"""Register for the site"""
return render_template("registerSuccess.html")
To provide CSS file in your Flask template you need to use a specific method for that in your HTML template {{ url_for(STATIC_DIR_NAME, filename=PATH_TO_FILE_IN_STATIC_DIR)}}.
In your layout.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<!-- #olaf: own link to own style sheet-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" type="text/css" >
<!-- #olaf: copied from https://bootsnipp.com/snippets/GaEOX-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
Also, if you follow the official documentation tips on the layout should do it.
But if you have a custom project setup then you might need to provide to your app where a static folder is.
For example in your application.py
import os
from flask import Flask, session, render_template, jsonify, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(THIS_DIR, 'specific_path_to_static', 'static')
app = Flask(__name__, static_url_path=STATIC_DIR)
#from the internet...# app.config['DATABASE_URL'] = "path_to_db"
# Check for environment variable
if not "DATABASE_URL":
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Set up database
engine = create_engine("DATABASE_URL")
db = scoped_session(sessionmaker(bind=engine))
#olaf: create a login page that has a form, containing "login" & "register" button
#app.route("/")
def index():
return render_template("index.html")
#olaf: Login button
#app.route("/register", methods=["POST"])
def register():
"""Register for the site"""
return render_template("registerSuccess.html")
Then the flask template should find the style.css file provided in layout.html file.
The first solution i can propose is that you download the bootstrap files and have them on your local working directory, then make a folder to contain static files and try the following code
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
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.
I am building a simple website and I am trying to get an image onto the page using Flask. All i get is the broken image symbol on the page tho.
Here is the server code...
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def homePage():
return render_template("HomePage.html")
if __name__ == "__main__":
app.run(debug=True)
And here is HomePage.html...
<!DOCTYPE html>
<style>
</style>
<html>
<head>
</head>
<body>
<img href="{{ url_for('static', filename='testing.png') }}" />
</body>
</html>
<script>
</script>
My file structure is as followed...
-Web
-static
-testing.png
-templates
-HomePage.html
server.py
Now, if i actually inspect through chrome, I can see the img tag gets converted to
<img href="/static/testing.png">
and if I right click this in chrome and open it in a new tab the image appears, But is still doesn't show on my web page.
For img tag use src attribute rather than href attribute.
In HomePage.html change the following line:
<img href="{{ url_for('static', filename='testing.png') }}" />
to
<img src="{{ url_for('static', filename='testing.png') }}" />
Reference:
MDN's documentation on img tag attributes