How to display HTML using Python Alone in localhost - python

I am trying to display my html files using python alone. Such as I would python code.py and I would be able to access my html at localhost:8080
html files are static files that access each other. For example, index.html directs to contact.html and all of them access css folder.
How do I open my html files so it displays it on the webpage?
below is what I have so far.
html_file = []
with open("index.html", "r") as f:
for line in f.readlines():
html_file.append(line)
Is there way to do python code.py and when I access localhost:8000 that would show me the code? and I can access each page.
here is an example html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>

There's way to do so using the python web frameworks like Flask or Django. In a typical flask scenario your code would look like this:-
1) Install flask:-
pip install flask
2) Write your code.py like this:-
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('hello.html')
3) Next create a templates folder inside which put your html file which I have named it to be hello.html
templates > hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
4) Your directory structure would look like this:-
/code.py
/templates
/hello.html
5) Run python code.py and you can see your page on localhost:5000.

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

PyScript: connecting to a Postgres database?

I'm testing PyScript for the purposes of submitting queries to a Postgres database, creating Pandas dataframes, and rendering some numerical results and visualizations in the browser.
I'm attempting to connect to a Postgres database hosted on Heroku.
My code is as follows:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/#holoviz/panel#0.13.1/dist/panel.min.js"></script>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>PyScript Demo</title>
<py-env>
- pandas
- panel
- psycopg2
</py-env>
</head>
<body>
<div id='output' class="text-3xl text-center"></div>
<button id="retrieve-data" class="mt-4 p-2 text-white bg-blue-600 rounded" pys-onClick="retrieve_data">Get Data</button>
<py-script src="./main.py"></py-script>
</body>
</html>
main.py
import panel as pn
import psycopg2 as pg
pn.extension()
connection = pg.connect(host="ec2-12-345-678-910.compute-1.amazonaws.com",
port = 5432,
database="test_db",
user="test_user",
password="my_password_here")
var_1 = 'a test string...'
pyscript.write('output', var_1)
def retrieve_data(*args):
pyscript.write('output', 'Foo')
In the web browser, I see the standard messages:
Loading runtime...
Runtime created...
Initializing components...
However, the page fails to load.
Is it possible to connect to Postgres using PyScript?

Problems with Jinja not executing python code within a block

I have a basic web app - a blog - I am trying to create using Flask.
I am trying to use {{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css') }} in my index.html to create a dynamic url. However, I am continually getting a GET request error because Jinja is not recognizing it as python code, and Flask is trying to create a url using the verbatim call.
Here is an example error:
"GET /%7B‌%20%7Burl_for(%22static%22,%20filename=%22vendor/bootstrap/css/bootstrap.min.css%22)%20%7D%7D HTTP/1.1" 404
The problem is not with the url_for() call or with the structure of my directory/inclusion of correct static and template folders because using
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
in my main.py file prints the correct path.
Additionally, Jinja is properly installed and working as evidenced by the fact that {% include "header.html" %} and {% include "footer.html" %} both work because the attempts to create the urls are all in those files.
Here is my main.py
from flask import Flask,render_template, url_for
import jinja2
app = Flask(__name__)
#app.route('/')
def root():
return render_template('index.html')
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
if __name__=='__main__':
app.run(debug=True)
Here is the relevant part of index.html
{% include "header.html"%}
<!-- Page Header -->
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
...
</header>
<!-- Main Content -->
<div class="container">
...
</div>
{% include "footer.html"%}
Here is the footer.html :
<!-- Footer -->
<footer>
...
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{‌{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{‌{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Custom scripts for this template -->
<script src="{‌{ url_for('static', filename='js/clean-blog.min.js') }}"></script>
</body>
</html>
Here is the header.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Clean Blog - Start Bootstrap Theme</title>
<!-- Bootstrap core CSS -->
<link href="{‌{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="{‌{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css')}} " rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="{‌{ url_for('static', filename='css/clean-blog.min.css')}} " rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
...
</nav>
One last note, before created the dynamic urls and doing a static reference, all the CSS/JS files rendered correctly.
Edit
The following code correctly renders the url on the page.
<h1>{{url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css', _external=True)}}</h1>
It's only when I wrap it as a string that it no longer picks it up as code.
In the content you've pasted in your question, there is a Unicode zero-width non-joiner character in between the two { markers in front of your Jinja expression. That is, if I copy this line from footer.html:
<script src="{‌{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
And produce a hexdump from it, I see:
00000000: 2020 3c73 6372 6970 7420 7372 633d 227b <script src="{
00000010: e280 8c7b 2075 726c 5f66 6f72 2827 7374 ...{ url_for('st
00000020: 6174 6963 272c 2066 696c 656e 616d 653d atic', filename=
00000030: 2776 656e 646f 722f 6a71 7565 7279 2f6a 'vendor/jquery/j
00000040: 7175 6572 792e 6d69 6e2e 6a73 2729 207d query.min.js') }
00000050: 7d22 3e3c 2f73 6372 6970 743e 0a }"></script>.
Look at offset x10, where we see e2 80 8c; that's the UTF-8 encoding of U+200c:
>>> "\u200c".encode()
b'\xe2\x80\x8c'
If I remove those extraneous characters from your source, everything works correctly:
$ curl -s localhost:5000 | grep static
<link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/vendor/fontawesome-free/css/all.min.css " rel="stylesheet" type="text/css">
<link href="/static/css/clean-blog.min.css " rel="stylesheet">
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
This is a test /static/foo/bar
<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/clean-blog.min.js"></script>

'html template not found' error (VS Code)

I have the following files on VS code and when I try to run them on my browser, it fails to identify that there is any reg.html template at all. What is the issue?
python file
from flask import Flask,
render_template, flash
app = Flask(__name__)
app.config["SECRET_KEY"] = "asdfghjkl"
#app.route("/")
def form():
return render_template("reg.html", title = "Form")
if __name__ == "__main__":
app.run(debug = True)
html file (reg.html)
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login/Signup - ((title)) </title>
<!-- Bootstrap CSS-->
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/bootstrap.min.css)' ))">
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/site.css') ))">
</head>
<body>
<div class = "container">
<div class = "row">
<div class = "col-md-5">
<h1 class = "text-center">Registration form</h1>
</div>
<div class = "col-md-2"></div>
<div class = "col-md-2"></div>
</div>
</div>
<!-- Javascript -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.js.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src = "((url for ('static', filename = 'js/bootstrap.min.js')))">`</script>`
</body>
</html>
To solve this question, create a folder named templates, which is where Flask looks for templates by default, then put the reg.html in this folder:
start the program and you will observe the results:
Detailed information about flask, you can refer to Flask Tutorial.

Check for variable declared in child view in parent template

I am migrating several pages over to use our site's new template. These are legacy pages, though, so they need a couple extra global js files.
I was hoping to set a legacy flag in the child page views, and then have an if check in the master template, but this didn't seem to work.
Is there a better way to do this?
The ideal approach would mean I could simply declare the global legacy scripts in one place. I don't want to have to include them on every legacy child page, which is what we're doing now.
Parent template:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=.5"/>
<title>Title</title>
<link rel="stylesheet" href="/static/css/global.css"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<%block name="page_css" />
</head>
<body>
<!-- Body -->
<div class="bc-page-wrapper">
${self.body()}
</div>
<script type="text/javascript" src="/static/globals.js"></script>
% if legacy == 1:
<script type="text/javascript" src="/static/js/legacy.js"></script>
% endif
</body>
</html>
Legacy Page Inheriting Template:
<%
legacy = true
%>
<%inherit file="/global/ko_admin_template.html" />
<div class="legacy-container">
content here
</div>

Categories