How to change value with PyScript wihtout reloading page - python

is it possible to print my example code like i would do it in an normal Console. it just prints the values at once without waiting and doesn't delete the previous one.
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset ="UTF-8">
<meta http-equive ="X-UA-Compatible" content "IE=edge">
<meta name ="viewpoert" content="width = device-width, initial-scale=1.0">
<title> Document </title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div id="myNum" style="background: red;"></div>
<py-script>
import asyncio
for x in range (1,10):
element = document.getElementById('myNum')
element.innerHTML = x
await asyncio.sleep(1)
</py-script>
</body>
</html>

You need to update the DOM to overwrite the previous value:
...
<body>
<div id="myNum" style="background: red;"></div>
<py-script>
import asyncio
for x in range (1,10):
element = document.getElementById('myNum')
element.innerHTML = x
await asyncio.sleep(1)
</py-script>
</body>
</html>

Related

Why wont py script write file?

Shouldnt it create a file and write asd in it? When it prints out fgh.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<py-script>
f = open("file.txt", "a", encoding="UTF-8")
f.write("asd")
print("fgh")
</py-script>
</body>
</html>

Run python from HTML

I need to run some python code when HTML button click,
I try this code but when I clicked the button nothing happened.
This is my code:
'''
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.9.0/brython.min.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
def change_image():
from browser import document, html
document["image"].clear()
document["image"] <= html.IMG(src="flowers.jpg")
document["next"].bind("click", change_image)
</script>
<img id="image" src="image.png">
<input id="next" type="button" value="next state"/>
</body>
</html>
'''
What is my problem??
Your code has a problem.Change it as follows
<script type="text/python">
from browser import document, html #Use the form outside the function
def change_image(item):
document["image"].clear()
document["image"].src="flowers.jpg" #change attributes
document["next"].bind("click", change_image)
</script>
Full code
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.9.0/brython.min.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document, html
def change_image(item):
document["image"].clear()
document["image"].src="https://www.w3schools.com/html/img_chania.jpg"
document["next"].bind("click", change_image)
</script>
<img width=200 id="image" src="https://www.w3schools.com/html/pic_trulli.jpg">
<input id="next" type="button" value="next state"/>
</body>

How to insert values coming from python into the body section of an html file?

from bs4 import BeautifulSoup
import requests
def getnames():
#i = 1
#for i in range(1,60):
url = requests.get('http://store.steampowered.com/search/?specials=1&page=1')#{}.format(i)
soup = BeautifulSoup(url.content,"html.parser")
games = (soup.find('div',"leftcol large").find_all('a',"search_result_row ds_collapse_flag"))
for game in games:
picture = game.find('div',"col search_capsule").img
name_of_game = game.find("span","title")
discount = game.find('div',"col search_discount responsive_secondrow")
from_price = game.find('div',"col search_price discounted responsive_secondrow").span.strike
to_price_w_from = game.find("div","col search_price discounted responsive_secondrow").span.extract()
to_price = game.find('div', "col search_price discounted responsive_secondrow")
print(name_of_game)
#i+=1
this is the code I use to get the names of the games at discount. When I run the function, what it prints out is that
<span class="title">No Man's Sky</span>
<span class="title">Little Nightmares</span>
<span class="title">Kerbal Space Program</span>
<span class="title">Mafia III</span>
<span class="title">Mafia II</span>
..............
There is nothing wrong with it. I want to make a container that contains some of the information above and send it to the "index.html" file which is in the same folder. Again, there is nothing wrong with making a container but the problem is I can't send it into the body part of html file. I have tried a few things but couldn't manage to send it. How can I insert what I have into the body section of html?
What you need to do is to make a new BeautifulSoup object of the existing index.html file. Modify it with the new data, then overwrite index.html with the string representation of the object. Modifying the tree section of the bs4 documentation provides info on the various methods available to do this.
A simple example.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Page</title>
</head>
<body>
<!-- I want to insert here-->
</body>
</html>
Code to modify the file
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('index.html'), 'html.parser')
p_tag = soup.new_tag("p")
p_tag.string = 'This is the new paragraph'
soup.body.append(p_tag)
with open("index.html", "w") as file:
file.write(str(soup))
Modified index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Page</title>
</head>
<body>
<!-- I want to insert here-->
<p>This is the new paragraph</p></body>
</html>
You need to have a index file as a template with replaceable code holder - a special pythonic tag. Read the index template and replace your content at specific place. Replace index.html
Following quick example
--- index template ---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" rel="stylesheet">
<title>Demo</title>
</head>
<body>
<div class="container mt-1 mb-1">
<div id="main_ad_block">
<div class="card-columns mt-1 mb-1" id="sub_ad_block">
%(ads_block)s
</div>
</div>
</div>
<script crossorigin="anonymous"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script crossorigin="anonymous"
integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script crossorigin="anonymous"
integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
</body>
</html>
--- python code ---
INDEX_TEMPLATE = './www/templates/index_template.html'
INDEX_FILE = './www/templates/index.html'
str_ads = """<span class="title">No Man's Sky</span>
<span class="title">Little Nightmares</span>
<span class="title">Kerbal Space Program</span>
<span class="title">Mafia III</span>
<span class="title">Mafia II</span>"""
# read template index file
with open(INDEX_TEMPLATE, 'r') as input_file:
str_template = input_file.readlines()
str_template = [line % {'ads_block': str_ads} for line in str_template]
with open(INDEX_FILE, 'w') as output_file:
output_file.writelines(str_template)
Have a look at the;
str_ads = """<span class="title">No Man's Sky</span>
<span class="title">Little Nightmares</span>
<span class="title">Kerbal Space Program</span>
<span class="title">Mafia III</span>
<span class="title">Mafia II</span>"""
this is your html to insert into index.
and,
get python code to insert your html to replaceable code holder "%(ads_block)s",
str_template = [line % {'ads_block': str_ads} for line in str_template]
of course, you may need to tweak this to suite your requirement.

AngularJS not working with Flask

I have this simple app:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>working app</title>
<script type="text/javascript" src="static/js/angular.min.js"></script>
<script type="text/javascript">
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.message = "Howdy!!";
}])
.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('{a');
$interpolateProvider.endSymbol('a}');
}]);
</script>
</head>
<body ng-app="myApp">
<h1>Hello!</h1>
<div ng-controller="myCtrl">
<span>{message}</span>
<span>{{ '{{message}}' }}</span>
</div>
</body>
I'm getting {message} {{message}} in html page not scope value. I don't have any idea, where I'm going wrong. I really appreciate any sort of help in this!
To achieve your expected result, use below option to bind your scope value
{a message a}
Start tag and end tag should be '{a' and 'a}' respectively without {{}} inside them
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>working app</title>
<script type="text/javascript">
</script>
</head>
<body ng-app="myApp">
<h1>Hello!</h1>
<div ng-controller="myCtrl">
<span>{a message a}</span>
</div>
</body>
JS:
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.message = "Howdy!!";
}])
.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('{a');
$interpolateProvider.endSymbol('a}');
}]);
Codepen= http://codepen.io/nagasai/pen/JKrVgV

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