Skip to content

Instantly share code, notes, and snippets.

@ThunderWiring
Created September 6, 2021 10:36
Show Gist options
  • Save ThunderWiring/b1e934d2246f659e6a5c008f98456af6 to your computer and use it in GitHub Desktop.
Save ThunderWiring/b1e934d2246f659e6a5c008f98456af6 to your computer and use it in GitHub Desktop.
call python from js
const onLoadClick = () => {
console.log('Load click')
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", '/serve_load', false); // false for synchronous request
xmlHttp.send(null);
}
import os
import http.server
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pyscript import save_pic
class ImageRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/webviewer.html'
elif self.path == '/serve_load':
save_pic()
return http.server.SimpleHTTPRequestHandler.do_GET(self)
server_object = HTTPServer(server_address=('', 8080), RequestHandlerClass=ImageRequestHandler)
server_object.serve_forever()
import requests
import os
class MyBusinessLogic:
def __init__(self):
self.urls = [
'https://i.cbc.ca/1.5256404.1566499707!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_780/cat-behaviour.jpg',
'https://ichef.bbci.co.uk/news/976/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg',
]
self.filename = 'cat_pic.jpg'
self.idx = 0
self.pic_url = self.urls[0]
def do_something(self):
self.idx += 1
self.pic_url = self.urls[self.idx % len(self.urls)]
try:
os.remove(self.filename)
except OSError as e:
print('excep', e)
with open(self.filename, 'wb') as handle:
response = requests.get(self.pic_url, stream=True)
if not response.ok:
print(response)
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
logic = MyBusinessLogic()
def save_pic():
logic.do_something()
<!DOCTYPE html>
<html>
<script src="jsfile.js"></script>
<head>
Demo
</head>
<body>
<div>
Click to load an Image
<div>
<button onclick="onLoadClick()">Load Image</button>
<div>
<img id="my_image_id" src="cat_pic.jpg" />
</div>
</body>
</html>
@ThunderWiring
Copy link
Author

  1. All files should be in same dir
  2. run server using python .\py_server.py from the dir where py_server.py is
  3. open browser at localhost:8080

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment