I'm trying to have it so that when my web page is loaded, a python script is executed. The website is run on an apache server and the script is in the same directory as the index.html (it's a very small project).
Is there anyway I can do this? I'm not trying to output the data from the python file to the webpage, nor am I trying to affect anything client-side, I simply want the python script to execute and do it's thing whenever the web page is loaded.
Is there some sort of javascript function that I can use? I've searched around but really haven't found anything similar. Thanks!
Hopefully, your web server is already set up to run Python scripts. Presumably it will recognize an index.py file as any other index.(html|cgi|pl|etc.) document. Create the following as index.py in your DocumentRoot:
my_webpage = """
Content Type: text/html\n\n
<html>
<head>
<title>Python-generated text!</title>
</head>
<body>
<h1>I just made an HTML page with Python!</h1>
</body>
</html>
"""
print(my_webpage)
# now that that's out of the way, let's run our script
import stuff
def myfunc():
# awesomeness goes here...
and make sure it's executable. Now, whenever a user requests http://www.yourserver.com/ the server will run index.py, which prints out the HTML content, including the headers, then goes on to run the rest of your script.
I had to do this too. I had a python script(which gets me data from another website) which gets executed when you click on a button.
I used Ruby on Rails for my client side code. I embedded the script file in my ruby controller which then gets called by my form and hence it gets executed.
eg:
cmd = " python getData.py "
exec( cmd )
Related
I am new to this topic and I have developed a .php file, which has an html code inside, which makes a series of functions through javascript and this through ajax, executes a php code, which registers data in the database, the code works correctly, when opening the url, internally it does the whole process.
But what I want now is to schedule this code to be executed every day at a certain time, but when doing it directly with my hosting, it returns the html code and does not execute it. I also used cron-job.org and it returns the same, it returns all the html code in text format, but it does not execute the functions and others that I have in javascript and php.
I would appreciate if you could help me.
What I would do, create a new PHP file that contains all function calls that normally would be executed through AJAX requests. Then schedule this new PHP file in a cronjob.
You could also script the whole thing as if you were a visitor of the page through a headless browser, for example PhantomJS or Selenium. And then schedule that.
It is not possible to run js on server side using php, but if your script can run on web-server you can use CURL to run it as a web-page. You can also run it on localhost. Set up CURL and the set cron job like this curl https://localhost/script.php. Another way to run script on the web-server is wget, something like this: wget https://localhost/script.php
I currently have a python script that updates certain CSV files when ran (it web scrapes and updates the information of a CSV file). In my HTML page (index.html), I have a script tag inside index.html that reads the CSV file and displays it as a table on the webpage. However, what I now need to do is update the CSV file by pressing an HTML button on the webpage. This will update the CSV file so when I run the button to run the JS script, it will have updated values from the file.
I searched and found it very hard to understand what they meant by using flask and Django (I don't know anything about setting up servers). I don't want to set up a Django webpage because I want to work with my current pure HTML webpage I wrote.
I would appreciate it if the answer is up to date with the current standard solutions for running python scripts in HTML.
Please ask if you need more information. Thanks.
You need to setup a web server. Flask can be used for that purpose. So you can create the following script:
from datetime import datetime
from flask import Flask, redirect, request
app = Flask(__name__)
#app.route('/')
def index():
with open('index.html') as fh:
return fh.read()
#app.route('/update')
def update_file():
with open('data.txt', 'w') as fh:
fh.write(datetime.now().strftime('%H:%M:%S'))
return redirect(request.referrer)
The #app.route('/') provides your landing page which is stored in index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<form action="/update">
<input type="submit">
</form>
</body>
</html>
This HTML page contains a submit button which refers to /update. In the web server script above this route is registered with the update_file function. Here you can implement your logic to react to the button press (in the example it writes the current time to data.txt on the server). Since the script operates on the server and your browser operates on the client this only works if that is actually the same machine, i.e. if your using it locally as an interface to your programs. If you want to separate server and client you'll need to introduce a way for transferring the data.
Now you can run the web server as follows:
$ FLASK_APP=script.py flask run
[...]
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now you can navigate to the address indicates above and you'll be on the landing page. Pressing the button updates the file:
$ tree .
.
├── data.txt <-- This file gets updated.
├── index.html
├── __pycache__
│ └── script.cpython-38.pyc
└── script.py
You can't run python in html. You can just use javascript. but you can pass the information as json and then use javascript if you don't want to change the language or using python frameworks.
I have a Python file, called function.py, which contains this code:
def double(x):
return x * 2
I also have this HTML code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
alert(double(4));
</script>
</body>
</html>
Is there a way for me to load the Python file in HTML of JavaScript, or is that impossible?
No. You cannot execute python directly in your web page. The web page is in the browser and the browser does not know how to execute python.
So, the python needs to run on the server. You have a couple options for how you can access the python on the server from your web page:
You can use a template system that allows you to insert python generated results in the web page BEFORE it is sent to the browser so when it gets to the browser, your python code has already been run and the results were placed into the web page for your page Javascript to access in the browser.
You can make an Ajax call with Javascript from your web page to your server and you can code your python server to respond to that Ajax call and return results. The Javascript in the web page can then do whatever it wants to with the results of the Ajax call.
It is a rather wierd problem. Consider the following small perl code:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw{ :standard };
use CGI::Carp qw{ fatalsToBrowser };
my $q = CGI->new;
print "Content-type: text/html\n\n";
print "<head>\n";
print "<script src='/home/bloodcount/Desktop/pm.js' type='text/javascript'></script>\n";
print "</head>\n";
print "<body>\n";
print "<h1>Click any number to see its factors</h1>\n";
print "</body></html>";
It prints a very small html page and includes a jasvascript file. The problem is that the javascript file isn't included. The "physical" copy is in the correct place. I thought that something may be wrong with the code I am generating so I copied the raw html which comes out if you run this file in the console which is:
Content-type: text/html
<head>
<script src='/home/bloodcount/Desktop/pm.js' type='text/javascript'></script>
</head>
<body>
<h1>Click any number to see its factors</h1>
</body></html>
I ran it in chrome and it worked perfectly. The javascript file has exactly one line if code which is:
console.log("It works!");
Any ideas what may be causing this?
Note: I know that the second code listing doesn't have !DOCTYPE.
Since you are able to execute the CGI within your browser you must have a local web server running. Your <script src='...'> path is likely unreachable from the browser due to a lack of access rights or the proper alias configured within your web server.
It works from the static file because the browser is then going though filesystem directly, so the JS file path name resolves.
You have to put the .js file somewhere that the web server knows about, and then formulate your src path correctly.
Check your web server logs and documentation to see how to set up the proper access rights and/or aliases. Note you probably do not want to expose ~/Desktop to the internet.
As an example, if you are using Apache, see USERDIR, ACCESS CONTROL, ALIAS.
After some tinkering I found the solution:
Apache searches for scripts and files only in the folder for this website meaning that each website has one specific folder where you must put the scripts. The base folder path is: /var/www/ and from there on you must find your website.
This means that when before the set path was: /home/bloodcount/Desktop/pm.js
it actually searched for the path /var/www/home/bloodcount/Desktop/pm.js which didn't exist. It wasn't searching in the real desktop, nor was there a permission problem.
I have a page that when loaded I would like it to run a perl script. Is this possible to do with javascript? I have never ran a perl script on the web before and the only way I have seen to do it is link to it.
There are 3 ways:
If it's a dynamic page (CGI or other), as long as your script backing the page is an executable Perl script returning valid HTTP response, you're good. If you need to execute a separate Perl script, you can do it using the usual system() call (ideally, the functionality should be a Perl library call so your script can then execute it without spawning a system call). This approach of course works with ANY language that the back-end script is written in, e.g. if it's a Java Servlet, or any other code, it can also execute a system call to your Perl script.
If it's a static HTML page, you can have an "onload" JavaScript event (or just a JS function call inside a <script> tag) which executes an AJAX call to a different dynamic page (say http://yourserver/scripts/run_script_X ) running the script as per previous bullet point.
Just to be clear, the script will be running on the web server and not in a browser/client system; so you need some sort of mechanism for allowing the results of the script to affect your web page if you wish to have such an effect.
$.ajax({url: 'http://yourserver/scripts/run_script_X'}); // jQuery example
As an oldie variation on the last approach, you can also have your page have a <IFRAME> whose URL points to http://yourserver/scripts/run_script_X (make the iframe small/invisible if you don't care about the results of running the script as per your comment).
<!-- The rest of your HTML code -->
<IFRAME
SRC="http://yourserver/scripts/run_script_X"
style="display: none;"
/>
Irelevant comment made prior to the comments on this answer:
Without a lot more context on what you want the page to be (CGI script, static HTML, etc...) and what you want the script to do and how you want the results of running the script to affect your page, it's hard to suggest anything more precise.