Python: How to embed my python script into a webpage - html

I have a full website with HTML and need to add an interactive piece that I could easily write with python (or even c/c++). What can I can use/do to accomplish this? The script will take user input do some calculations and display the output. I am completely lost on where to start, any help is appreciated!

If you want to embed Python in your HTML page the you will have to use a Python based web server which will have HTML form for data input and execute provided Python code as server side script and return you the desired result.
You could start by using Django.

If you want to build a web application with python back-end, then you need to do with a web framework, like Django or Flask. Flask is more easy to use and understandable for beginning level.
Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages.
Flask code:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)
home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Flask Tutorial</title>
</head>
<body>
<h1> My First Try Using Flask </h1>
<p> Flask is Fun </p>
</body>
</html>
For Run Your First App:
python3 app.py

One way would be to embed Python into a html file using <py-script> tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the the <py-script> tag -->
<py-script>
print("Hello World!")
input("Enter your name:")
</py-script>
</body>
</html>
Another way could be to embed Python script as a child process (eg: in Node.js):
const { spawn } = require('child_process');
var child = spawn("python", ["-c",`
print("Hi")
print(int(input("Enter a number:")))
`]);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
process.stdin.pipe(child.stdin);
child.on('exit', () => process.exit());

Related

Splitting large HTML file into smaller blocks and importing each file to a div?

I have an HTML file with around 4000 lines of code, it's a single-page website and it needs to stay that way.
The site is made up of 8 different 100vh div-s. Think about it like an 8-page full-size hero slider and each slide has something on it.
Debugging and editing this file is becoming a nightmare.
Is it possible to separate each part/component/section/div (whatever) into its own HTML file and import them into another HTML file? Like how it is done on React.
basically:
split index.html into 8 parts
a.html, b.html, and so on.
import a.html into index.html and make it visible in a div,
and do the same for b.html, place it in another div below a.html
You can use PHP and its include() function to have a main (php) file in which you include 8 or whatever number of files that contain HTML code.
Except of the including this hardly requires any other PHP code, i.e. that's easy to learn with any PHP basics tutorial.
I have no idea if the following would be sensible or not but in principle it should work.
You could try using JavaScript's insertAdjacentHTML() method:
In your HTML file:
<!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">
<title>Document</title>
</head>
<body>
<div id='file1-div'></div>
<div id='file2-div'></div>
<script src='file1.js'></script>
<script src='file2.js'></script>
</body>
</html>
Then in file1.js you could have:
const file1Div = document.querySelector('#file1-div');
file1Div.insertAdjacentHTML('beforeend', `
<!-- your HTML goes here -->
<p>Hello World from file1.js</p>
`);
and in file2.js you could have:
const file2Div = document.querySelector('#file2-div');
file2Div.insertAdjacentHTML('beforeend', `
<!-- your HTML goes here -->
<p>Hello World from file2.js</p>
`);
An advantage of this over using PHP or Node.js is you don't need PHP or Node.js running on the server.

How do I mount multiple wasm components to a page?

I have a flask project I am working on. I would like to be able to start replacing some components with wasm.
I was able to get the yew component to mount to a specific <div>, But I'd like to be able to do that, as well as leverage some of the GUI libaries of Rust.
I was able to make some examples in the iced library work as WASM, but that was as standalone. I havent quite wrapped my head around how to wrap them in a <div> and use multiple wasm/rust/yew components on a page.
A very simple example to give you an idea of implementation is below.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="module">
import init from "./static/js/wasm.js";
init();
</script>
<style>
#yewapp{}
</style>
<meta charset="utf-8" />
<title>Flask+Rust</title>
<link rel="shortcut icon" href="#" />
</head>
<body>
<div>
  {{ message }}
</div>
<div id ="yewapp"></div>
  {{ message }} again
</body>
</html>
This works (yew app is just hello world right now).
I like the .mount(div) functionality in yew, but if there is another way to do this I'm open to it.

I am writing a quick web page using html and am running into syntax error

I can't seem to find the error in the code, I am not very familiar with HTML. I keep getting a syntax error on line one:
File "C:\Users\____\Desktop\Flask_test\index.html", line 1
<html>
^
SyntaxError: invalid syntax
Here is my code:
<html>
<head>
<title>Home page</title>
</head>
<body>
<h1>Home Page!</h1>
<p>Hello!</p>
</body>
</html>
I'm not familiar with Flask but I believe it's requesting the !DOCTYPE at the beginning. Try adding <!DOCTYPE html> before the starting HTML tag.
Try adding <!DOCTYPE html> and improve the code's formatting.
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
</head>
<body>
<h1>Home Page!</h1>
<p>Hello!</p>
</body>
</html>
So you are getting Internal Server Error (500)
that means the code of python you have written does work but when a request comes to the server an error occurs, or Flask just cant find your index.html file
by default Flask will search for your index.html file in a folder named "templates" or
you can set the directory of your templates(HTML files) explicitly
Anyway I wrote this script for you, try to run it on your local machine
from flask import Flask, render_template
app = Flask(__name__,
static_url_path='',
static_folder='static',
template_folder='myTemplates')
#app.route('/')
def mainRouter():
return render_template("index.html")
You need to create a directory named "myTemplates" and put your index.html file inside it, you can change the name of course inside the script (template_folder='myTemplates') to use another directory.
and if you have any static files, like images or audio files, videos, etc...
you need to create a directory called "static" and put all your static files there or you can change its name in the script (static_folder='static') to whatever you like.
Add !DOCTYPE + HTML LANG.
<!DOCTYPE html>
<html lang="en-US">
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Home page</title>
</head>
<body>
<h1>Home Page!</h1>
<p>Hello!</p>
</body>
</html>

Html file isn't sinking up with my css file?

All of my html and css and files are in the same templates folder so i don't think that is the problem. I am brand new to frontend development and deeply confused... please help, this is not a good start lol!
-- My base.html file --
<!DOCTYPE html>
<html>
<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>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
<nav class="navigation_bar">
<ul>
<li>
<b>about page</b>
</li>
</ul>
</nav>
{% block content %}{% endblock %}
</body>
</html>
-- main.css --
#import url('https://fonts.googleapis.com/css?family=Montserrat:400,600');
body {
text-align: center;
font-family: 'Montserrat';
}
.navigation_bar a {
text-decoration: none;
}
Maybe it is an issue with my css? Thank you!
I think the problem here is in your server, I assume you are using Flask since you are writing Jinja syntax in your html file, I think the problem is that Flask can't find your css file. you need to tell it exactly where to look for your static file, or you can just make a router to deal with file requests, read the files and send them back to the browser.
The first way
from flask import Flask, render_template
app = Flask(__name__,
static_url_path='',
static_folder='static',
template_folder='templates')
#app.route('/')
def main_page():
return render_template("index.html")
so now Flask will look for your static files inside the folder "static" you need to create it and then put your static files there including your css file, and leave your html file like it is, don't change the path of your css file to include the folder name since Flask will serve it as if it were in the current directory of the script.
The second way
from flask import Flask, render_template, request, Response
app = Flask(__name__)
#app.route('/')
def main_page():
return render_template("index.html")
#app.route('/css')
def giveCSS():
fileContent = ""
file_name = request.args.get("name")
if(file_name):
file = open("css/" + file_name + ".css", "r")
for line in file:
fileContent += line
return Response(fileContent, mimetype='text/css')
I assume you have other css files, you need to change the path of the css file inside the html file to include the query /css/name=main and the css file inside maybe a folder named "css" of course you can change whatever names you don't like but make sure to take care.

Prerender.io with Angular Universal - doesn't render HTML within component tags

I have created an Angular Universal app that consists of nested components.
I need Prerender.io to return the Server-Side-Rendered HTML from my app but Prerender.io only returns the top level component tags and not the HTML within.
It seems that this happens to every Angular app (SRR or not). I would expect it to happen on a none-SSR page but not on SSR.
I followed the guidelines from prerender.io:
git clone https://github.com/prerender/prerender.git
cd prerender
npm install
node server.js
And then tried to go to:
http://localhost:3000/http://localhost:4000/test
The returned html I get is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Documents SSR</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css">
<style></style>
</head>
<body>
<app-root _nghost-sc0="" ng-version="8.2.3" _nghost-serverapp-c0="">
<router-outlet _ngcontent-serverapp-c0=""></router-outlet>
<component1>
<!---->
<component2></component2>
</component1>
</app-root>
</body>
</html>
I would expect Prerender.io to render everything within component2 but as you see, I get nothing.
Am I missing a configuration somewhere or doesn't Prerender.io support Angular?
If I go directly to http://localhost:4000/test I get the full rendered HTML.
EDIT
It could look like Prerender.io doesn't wait for my last ajax call to be done before rendering?
Found the issue - don't use ShadowDom.
My component2 was using encapsulation: ViewEncapsulation.ShadowDom.
Removing that let Prerender give me the entire HTML.