Calling a JavaScript function from a .js file in Google App Engine - javascript

I was trying to call a function from a .js file in the Google App Engine enviroment.
the code of the html print goes like this:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class jumpPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('');
self.response.out.write('');
self.response.out.write('<head>');
self.response.out.write('<script type="text/javascript" src="/js/pxc11.js" >');
self.response.out.write('</script>');
self.response.out.write('</head>');
self.response.out.write('<body">');
self.response.out.write('<form name="f1">');
self.response.out.write(' <input type="hidden" name="theStartValue" value="1"><p>');
self.response.out.write(' <input type="button" value="-15" onClick="dummy()">');
self.response.out.write(' <input type="button" value="+15" onClick="dummy()" ><p>');
self.response.out.write('</form>');
self.response.out.write('</body>');
self.response.out.write('');
self.response.out.write('</html>');
application = webapp.WSGIApplication(
[('/tonteria', jumpPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
and then the .js is just this:
<script language="javascript" type="text⁄javascript">
function dummy()
{
alert("POPOPOPOPOPO");
}
<⁄script>
The app.yaml includes a static folder that has the .js file.
handlers:
- url: /js
static_dir: js
- url: /tonteria
script: tonteria.py

.js files contain Javascript, not HTML tags.

Your life might be easier by making the file into an html template and then rendering it with your variables. Google has a great tutorial

Related

Use nodejs module in external javascript from the public folder

I included a module in my js file. Now i defined a button in a ejs file, which calls a function in an external js file from the public folder. How can i use the module in this function?
I tried to pass the module as a parameter, but i didn´t work. Is this even the right way to use this module in my external file?
the route js file
var express = require("express");
var router = express.Router();
var R = require("r-integration");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("Upload", { title: "Upload", para: R });
});
module.exports = router;
my ejs file with the button which calls the function loadScript()
Here i also tried to pass the paramter para to the const rModule
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<button onClick="loadScript()">Test Skript</button>
</body>
<script>
const rModule = para;
</script>
<script src="/javascripts/rScriptTest.js"></script>
</html>
the external js file from the public folder.
But here it says, that rModule is not defined.
function loadScript() {
let result = rModule.executeRScript("./RScripts/test.r");
console.log(result);
}
You can't pass a function though an EJS template. It won't serialize cleanly.
You need:
A JS script/module that will run on a browser
A URL for that file (usually provided with express.static)
You fail at the first hurdle. The module you are trying to use describes itself thus:
This is the R-integration API which allows you to execute arbitrary R commands or scripts directly from the node JS environment. This integration works on Windows and GNU/Linux based systems and uses system calls to access the R binary.
There is no way that it is going to achieve that without using Node.js-specific APIs that are not available in the browser.
You could write a web service in Node.js and interact with it using Ajax instead.

Update image on python flask app using javascript

I'm trying to display an image on a simple website, which I am using Flask for. I already tried to do this using a js script on the website itself, but it didn't work.
However, I do not know how to periodically update/refresh the image.
I'm using html and javascript for the first time right now and I'm too confused to get it to work.
This is the main .py file:
from flask import Flask, render_template
import os
#sorry for the bad code :/
app = Flask(__name__)
#app.route("/")
def running():
return "<p>Website running!</p>"
app.config['UPLOAD_FOLDER'] = os.path.join('static','images')
#app.route("/chart")
def show_img():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'chart.png')
return render_template("chart.html", user_image = full_filename)
if __name__ == "__main__":
app.run(port=3000)
This is chart.html:
<!DOCTYPE html>
<html>
<body>
<img src={{ url_for("static", filename="images/"+"chart.png" ) }}/>
</body>
</html>
What is the easiest way to update/reload the image every 5 seconds?
The filename stays the same, but the image itself changes
Some notes:
When working inside a request, it is better to use current_app
from Flask import current_app
#app.route("/chart")
def show_img():
# current_app.config
full_filename = os.path.join('images', 'chart.png')
return render_template("chart.html", user_image=full_filename)
We removed static as we'll be using static in the template itself.
Since you already have the user_image variable, you can add it to the file directly
<!DOCTYPE html>
<html>
<body>
<img src={{ url_for("static", filename=user_image ) }}/>
</body>
</html>
This will display the image.
Dealing with uploads
If you want to implement uploads etc, use flask-reuploaded, a maintained fork of Flask-uploads.
On the front-end, you need a file upload form. Then you need a route to accept the uploaded file. Then you need to make sure that the uploaded filename is always the same, maybe by deleting existing files beforehand.
A complete demo
Following the official docs, here is a demo.
Folder structure
.
├── app.py
├── static
│   └── images
├── templates
   └── chart.html
chart.html
<!DOCTYPE html>
<html>
<body>
<form method="post" enctype=multipart/form-data action="/upload">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
<br>
<img src={{ url_for("static", filename=user_image ) }}/>
</body>
</html>
app.py
import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
current_file = ''
#app.route("/")
def running():
return "<p>Website running!</p>"
app.config['UPLOAD_FOLDER'] = os.path.join('static','images')
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/upload', methods=['GET', 'POST'])
def upload_file():
global current_file
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
current_file = filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('show_img', name=filename))
#app.route("/chart")
def show_img():
filename = os.path.join('images', current_file)
return render_template("chart.html", user_image=filename)
if __name__ == "__main__":
app.run(port=3000)

Read data from local folder in FLASK

I am building a web API with FLASK and I want to read some images in data folder
venv/data/cartes/carte1.png
carte2.png
carte3.png
carte4.png
in order to show them in an html file index.html and loop over them whit javascript:
#app.route('/')
def index():
return render_template('index.html')
I tried to use this but it gaves error GET LINK... not found:
app.config["CLIENT_IMAGES"] = "/data/cartes"
#app.route("/get-image/<image_name>",methods=['GET', 'POST'])
def get_image(image_name):
try:
return send_from_directory(app.config["CLIENT_IMAGES"], filename=image_name, as_attachment=True)
except FileNotFoundError:
print("failure")
abort(404)
According to the docs:
(https://flask.palletsprojects.com/en/1.0.x/api/#flask.send_from_directory)
#app.route('/get-image/<path:image_name>')
def get_image(image_name):
return send_from_directory('/data/cartes', image_name, as_attachment=True)
You can find more examples here:
https://www.programcreek.com/python/example/65747/flask.send_from_directory
You should use the static directory for that:
https://flask.palletsprojects.com/en/2.0.x/tutorial/static/
With url_for you can generate the relative path to any file in that directory.
The static directory exists, so that there is a clear distinction between public files and server side code files.
If you want to include images in a html file you can use them inside a template as
<img src="{{ url_for('static', filename='smthn.png')}}"></img>

Loading local HTML with local Javascript Sources in a WKWebView (iOS, Swift)

I am trying to load a local html file in a WKWebView for a iOS app (Swift 4.2). Unfortunately, this local file contains javascript code that does not seem to be executed.
Below is this html file (taken from https://www.verovio.org/tutorial.xhtml?id=topic00):
<html>
<head>
<title>Verovio Hello World! example</title>
<script src="verovio-toolkit.js" type="text/javascript" ></script>
<script src="jquery-3.1.1.min.js" type="text/javascript" ></script>
</head>
<body>
Hello World!
<div id="svg_output"/>
<script type="text/javascript">
var vrvToolkit = new verovio.toolkit();
$.ajax({
url: "Beethoven_StringQuartet_op.18_no.2.mei"
, dataType: "text"
, success: function(data) {
var svg = vrvToolkit.renderData(data);
$("#svg_output").html(svg);
}
});
</script>
</body>
</html>
And below the view controller file written in swift:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
}
}
Files are local under "Build Phases/Copy Bundle Resources" in the project properties. I also tried to put them in a directory but without any success. Below the file organization inside the project.
EDIT: When I change the url in the html file from Beethoven.mei to https://www.verovio.org/gh-tutorial/mei/Beethoven_StringQuartet_op.18_no.2.mei (same file but on Verovio's website), anything works good!!
So:
Local .js resources work fine
The issue comes from jquery not able to load local text file
Any idea on how to make jquery able to load the local file?
Thank you!
M.
According to the docs, loadFileURL does this:
If readAccessURL references a single file, only that file may be loaded by WebKit. If readAccessURL references a directory, files inside that file may be loaded by WebKit.
The url you got is a url of a file, namely the HTML file. You need the url of the directory. You can do this by calling deletingLastPathComponent:
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
First check your index.html file has scr path for js. if like below, that means js files contain in js folder. so you need to add reference to that folder while add to project.
<script src="js/jquery.js"></script>
then get the main resource path like below
let path = Bundle.main.resourcePath! + "/\(folderName)/\(fileName)"
print("path:=",path )
after that load that file to webView
do {
let contents = try String(contentsOfFile: path, encoding: .utf8)
let baseUrl = URL(fileURLWithPath: path)
webView.loadHTMLString(contents as String, baseURL: baseUrl)
} catch {
print ("File HTML error")
}
You can use the loadHTMLString method to load the HTML, as below:
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html")!
do {
let html = try String(contentsOf: url)
webView.loadHTMLString(html, baseURL: url.deletingLastPathComponent())
} catch ....
The baseURL point to your app directory in file system. You can write in the src property of the script tag relative location that is interpreted as relative to baseURL.

how to add bootstrap, css, images ,js into google app engine?

I have created the web application using bootstrap.I uploaded it to the google app engine.My problem is ,it doesn't show any images,js or css i have added.Please help me. My folder structure is like below.
-myapp
-css
-js
-images
-fonts
-index.html
-otherfiles.html....
I edited the app.yaml as below
application: website-example
version: 1
runtime: python
api_version: 1
default_expiration: "7d"
handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css|swf|xml))
static_files: \1
upload: (.*\.(gif|png|jpg|ico|js|css|swf|xml))
- url: /(.*\.html)
static_files: \1
upload: index.html
- url: /.*
script: main.p
I edited the main.py as below.
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class IndexHandler(webapp.RequestHandler):
def get(self):
if self.request.url.endswith('/'):
path = '%sindex.html'%self.request.url
self.redirect(path)
def post(self):
self.get()
application = webapp.WSGIApplication([('/.*', IndexHandler)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Please help me.I can't figure this out.
For your case, I'd use something more like:
application: website-example
version: 1
runtime: python
api_version: 1
default_expiration: "7d"
handlers:
- url: /css
static_dir: css
- url: /js
static_dir: js
- url: /img
static_dir: images
- /index.html
static_files: index.html
upload: index\.html
- url: /.*
script: main.py
The basic idea behind the static dirs for css, js and images is that everything under those dirs will be served statically, whenever the request url starts with those urls (so, you can serve things like /img/sub_dir/foo.png)
For the static html, I used a single file example, but you could as well put them in a separate dir and serve statically from there

Categories