As mentioned here, I can import Python codes inside .html files using <% and %> tags. Just to try it, I wrote the below code in notepad and save it as a file named test.html :
<html>
<title>
</title>
<body>
<%print ("Hello")%>
</body>
Once I do a double click on the test.html, Chrome opens with the below line on the top :
<%print ("Heloo")%>
What I must I do to have 'Hello' in output?
Note: "print" is an example, What kind of ways is there to import and run python codes in html files?
That page is related to Karrigell a Python web framework, you can only have Python and HTML files (Web pages) if you use a Python web framework like web.py, Pylons, Django, and others.
Browsers can only execute JavaScript code, other programming languages have to use special components to be executed by browsers.
Related
I am trying to get HTML/webpage interface to run a python script I wrote that generates a graph and saves it in a local directory. I would like to click a single button and have the python code run, generate the graph and save it in a folder which then HTML could embed it on the HTML page. My issue is this code isn't working, the code is not run and no new graph is generated. Both the HTML and Python file (Create_Chart.py) are in the same folder.
Python code
globals().clear()
import numpy as np
import matplotlib.pyplot as plt
import os
rand=np.random.normal(100,1,size=[100,1])
chart=plt.plot(rand)
plt.savefig(r'C:\Users\...\example_chart.png')
HTML/Javascript code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function goPython(){
$.ajax({url: "Create_Chart.py",context: document.body}).done(function() {alert('finished python script');;});
}
</script>
</body>
</html>
I am trying to follow the example from this other stackoverflow thread. What am I doing wrong?
How can I execute a python script from an html button?
The javascript code is being called from the following link 'http://code.jquery.com/jquery-3.3.1.min.js'. Do I need to install Jquery on my local computer?
You'll need a webserver software (as in nginx) which understands how to run python scripts (as in a WSGI application). The script then needs to be something that understands HTTP. Your script needs then to answer with an HTTP response.
Since you're asking a question on that level, these are many concepts. I suggest you to watch into Django or FastAPI (Python web frameworks; google them). Those come with inbuild test webservers and get you started.
I've created a local address http webserver that will hopefully be able to open both HTML webpages and python scripts that create HTML webpages, but I keep getting a 501 error because I can't figure out how to get the webserver to recognize the code correctly. Another note: I'm coding on Windows, I'm not using Cygwin (I don't know anything about Cygwin, so if it's the recommended method here tips on how to get started with it would be appreciated.)
Anyways, here's what I've got.
I have created a folder in C:\ called server_test, and inside this folder is where I have been putting all my relevant HTML and python files. I've been editing my .py files in PyDev in eclipse (C:\workspace) and then copying the files over and putting them in C:\server_test.
To get my server running, I navigate to \server_test in cmd, open python, then create a webserver using HTTPServer, CGIRequestHandler, the current directory, address 127.0.0.1, and a port of my choosing (usually 9090). Once I've done this, I can go to my web browser and type in the address for one of my HTML pages and it runs perfectly fine. However, I currently have an HTML page meant to call a python script (also located in \server_test) that will create another HTML page, but I can't get it to work.
My HTML code looks like this:
<html>
<title>Debug Page</title>
<body
<h1>This is a test file. </h1>
<form method=POST action="my_code_2.py">
<P><input type=submit>
</form>
</body></html>
And then my 'my_code_2.py' looks like this:
#!C:\Python35-32\python.exe
import cgi
import cgitb; cgitb.enable()
print("Content-type: text/html\r\n\r\n")
print('<html>')
print('<h1>')
print('<title>This is a second test.</title>')
print('</h1>')
print('</body')
print('</html>')
From what I've read about shebang lines, it appears Windows native doesn't support them? So how can I make sure that my computer knows it's supposed to run the code as Python? At the moment, when I press the button on my first HTML page, the page http://127.0.0.1:port/my_code_2.py is merely a white page with my python code printed on it.
Try changing the extension to .cgi on your python file and see if that helps. You'll probably want to use something like bottle.py or django tho if you're running python on a webserver. Bottle is easier to learn but with fewer features.
http://bottlepy.org/docs/dev/index.html
https://www.djangoproject.com/
I have python script that scrapes text from a database and creates a word cloud. I'd like to create a bottle-based web page that runs the python script and then displays a word cloud generated by the script.
Thus far I have a python script.py:
from bottle import *
#route('/static/<filepath:path>')
def server_static(filepath):
return static_file(filepath,root='C:\wordcloud')
#route('/')
def main():
picture_name = 'wordcloud.png'
return template('template.tpl', picture=picture_name)
run(host='localhost',port=8080,debug=True)
and a template-file template.tpl:
...
<body>
<div class = "container">
%import script
<img src="/static/{{picture}}">
</div>
</body>
...
I'm able to generate the word cloud when I enter to localhost:8080 for the first time. However after the first time when I refresh the page, the web page just loads the "old" word cloud (it displays the word cloud, but uses the old image). Also, I'm sure that there is some better and more convenient way to do all this. Any advices?
Thanks!
The reason this happens is that web browsers will cache things like images based on their URIs. The usual hack around this is to add a meaningless parameter to the URI, as in <img src="/static/{{picture}}?v={{version}}">. In this case you could use something like int(time.time()) as {{version}}.
An alternative solution would be use something like inline SVG to place the "image" right in the HTML.
I have just started learning about webscraping using selenium and mechanize with great results. I was wondering if it was at all possible to scrape a cgi python script from a site as well so I can replicate the sites functionality offline.
Here is an example script.
http://www.tutorialspoint.com/cgi-bin/hello.py
When I attempt to scrape this file I get the html output from the script instead of the script itself. Which is this:
<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
</body>
</html>
The details of the python script can be found here:
http://www.tutorialspoint.com/python/python_cgi_programming.htm
If you can provide any insight I would be extremely grateful.
Thanks
Each site consists of two parts: the back-end and front-end.
"Back-end" means on the server side, usually PHP, Python, ASP or JSP languages.
"Front-end" means client side: HTML, JavaScript and CSS.
You, as a surfer view only the front-end, and this is what you scrape. You have no access to the back end.
I would like to change the logo of a website based on which menu is currently activated/seen by the user browsing the website.
For instance I have www.urltowebsite.com/menu1 = Header Logo 1
And then I have www.urltowebsite.com/menu2 = Header Logo 2
And on top of this I want to add an else statement stating that: If any other menu is selected, use header logo 3.
How can I make this possible with Python? I cant seem to wrap my head around what to define where and how to call up the different functions on the HTML website.
Oh and I insist doing this with Python. And preferably without any framework such as Django. But if needs be I can install web.py
EDIT:
Am I forced to go with php then? I would like to once and for all start utilizing Python on my web projects.
The website is made in simple HTML as I said first. The Javascript functions are only used to serve the HTML menu's through AJAX. Again this does not matter much for what I am trying to do, as menu's have classes and I can define those in php and thus change my logo/header.
What I want to do is to use Python in this instance. Here is a code snippet from the site:
<div id="header">
<span class="title"><img src="http://www.url.com/subfolder/images/logo.png"/>
</span>
</div>
And some more relevant to this:
<div id="menu">
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
<li>004</li>
<li>005</li>
<li>006</li>
<li>007</li>
<li>008</li>
</ul>
</div>
So can I use python here?
You're asking to do the wrong thing the wrong way.
In order to change the logo based on the URL in Python , you need Python to generate the page and know what that url is.
There are two ways to do that in Python:
Use an existing Web Framework
Write your own Web Framework
"Python" doesn't know or care what your URL is - the frameworks and support libraries ( Django, Pyramid, Bottle, Flash, Tornado, Twisted, etc) figure out what the URL is by an integration with an underlying web server ( though some have their own webserver coupled in ). Similarly, PHP doesn't really know or care what the URL is - that information comes from an integration with Apache or FCGI/Nginx/etc. PHP tends to ship with most/all of that integration done. It's also worth noting that PHP is not just a language, but a web framework. Python is just a language.
Most Python frameworks will be written to the WSGI spec and have a "request" object that has all the data you want ( and many use the WebOb librbary for that ).
If you plan on doing everything with static HTML files, then you have a few options:
have a single static directory. use javascript to figure out the addressbar location, and render the corresponding logo / write the headers & footers.
have a "template" directory of all your HTML. use a Python script build a static version of each website with the custom headers/footers and configure your webserver to serve a different one for each domain.
No, Python cannot run inside the HTML web page. If you're really serving plain HTML pages then you must use javascript to execute code in the browser once the page is loaded. However, since you mention using AJAX, it sounds like it's not really true that you're serving plain HTML but rather have some server side code. If so, that server side code is the place to put your HTML-construction logic. To know the best way to do that, you would have to describe what's happening on the server.
Although I haven't used it, I have heard that the pyhp project more or less provides php-like embedded functionality for python.