How do you attach a python file in html?

There are two subproblems in your problem:

  • Generate HTML to show your data
  • Serve that HTML

Mako can help you with the first one. For the second one there are different solutions available that depend on your situation.

Generate HTML

First you have to decide on a template, that means on the general skeleton in which your data will then be filled in. If you only want to show your data without any further information enigmas answer will work, but if it gets more complicated it is useful to use something as mako. How does a general template look like? Here is a really simple one:



Hello world!


This doesn't do very much. It's just like a single string. So lets get some python in it:



${x}


This template contains a variable which you will need to provide:

template = Template(filename="yourtemplate.template") # or how ever you named your template
print(template.render(x="Hello World!")

You will at least need for loops:

% for a in [1,2,3]
${a}
% endfor

This is the basic syntax for a loop. Of course you can do more complex things. Imagine mylist is a list of Person instances with a name and a age:

% for person in mylist
Name: ${person.name}
Age: ${person.age}
% endfor

You can use arbitrary HTML inside of that. Ofcourse mako can do more powerfull things, but a single stackoverflow post is to little space for that. You can read the basic usage and/or Syntax page of the mako language for mor information. But with the here presented structures you should be able to finish your task.

Serve HTML

You still need to somehow bring the HTML out to the web or where ever you want it. You have multiple possibilities that depend on what you want:

Static or dynamic

  • Is your data static? That means, will your data change in near time? If no, than you can simply generate the HTML on your local computer and then push the html to a simple webserver that serves html.

  • Is your data dynamic? That means your data changes often and it is not reasonable to powerup your local machine, run your script and then push the HTML. Instead you have to tell the server that serves your webpage to run your script whenever the data changes. There are more then one possibility to do that, you can use CGI (a webserver like nginx or apache calls your python script and serves the output) or a wsgi framework like django or flask or others. Of course these also need to be served, either from a "typical" webserver like apache or nginx or something like gunicorn

Lan or WWW?

  • If you only need it to be available in the LAN you can simply run a webserver on your local computer. If you do not expect much traffic and security is not a concern you could use the http server in the python standard library.

  • If you need it to be available on the web you need to look for a webserver. There are a few services that are free of charge for low traffic. To name a few: heroku which has a focus on python, so it's suited for the dynamic use case. Github pages where you can directly serve HTML from a github repository. I think it can only serve static HTML.

Allows you to be able to embed Python within HTML documents, similiar to mod_Python or PHP.

Summary

By taking advantage of both the Module: digiweb and a slightly modified version of PythonInsideHTML.zip from the BSD licensed project Karrigell Python web server to make it a stand alone library. It is possible to run embed Python within a HTML document that can be executed at run time.

Inside HTML

Syntax

By enclosing Python statements within a <% %> tag the Python interpreter will execute said statements. In the following example a "stored_time" variable will be created and will save the time on the local scope.

<% import time %>
<% stored_time = time.strftime("%d:%m:%y",time.localtime(time.time())) %>

If enclosed with <%= %> it will evaluate the statement and replace the tag with the result of the executed statement. In the following example the HTML created will contain the day:month:year from the devices internal clock.

<% import time %>
<%= time.strftime("%d:%m:%y",time.localtime(time.time())) %>

Indentation

Declared Indentation

A file is converted into Python code, which must be indented according to Python rules ; whereas in normal HTML indentation is used only for readability.

So beware if you mix Python and HTML :

    1 <% for i in range(10): %>
    2 <%= i %>*<%= i %> :  <%= i*i %> 

This will work because after a loop or a condition the following HTML is automatically indented by PIH.

To decrement indentation, use <% end %> :

    1 <% for i in range(10): %>
    2 <%= i %>*<%= i %> :  <%= i*i %> 
    3 <% end %>
    4 

done

in this example, "done" will be written after the for loop is finished.

Another example for an if... else... :

    1 <% if i: %>
    2   output someting
    3 <% end %>
    4 <% else: %>
    5   output someting else
    6 <% end %>
    7 

done

(Don't forget the last <% end %> otherwise "done" would have the same indentation as line 5) But this :

    1 <% for i in range(10):
    2    data= '%s * %s' %(i,i) %>
    3     <%= i*i %> 
    4 

done

Won't work, because after the print statement on line 2 indentation goes back to 0 (it begins with plain HTML).

The Tag

If you have complex code where Python and HTML are mixed, embed it between the tags and :

    1  
    2  <% for i in range(10):
    3    data= '%s * %s' %(i,i) %>
    4     <%= i*i %> 
    5  
    6  

Table

7 8 9 10 11
A cell

means : from now on, and until the matching tag, use the indentation in PIH source and leave it as it is to produce Python code In the above example, indentation is used until line 5 and ignored afterwards If the tag itself is indented, the following code is indented relatively to it :

    1   
    2     
    3       
    4       
    5     
    6     
    7     <% for i in range(10): %>
    8       
    9       
    10      
    11      
    12    
    13  
NumberSquare
<%= i %><%= i**2 %>

In line 7, <% is aligned on so the Python code will not be indented.

Ending Script

If you want to exit the script before the end of the document, raise a

SCRIPT_END exception
  raise SCRIPT_END,message

Writing to HTML output

If you want to write to the HTML output without using the evaluating tags you can write directly to the Python code output via

py_code.write( "

Heading

" )

Working example from the Python

For this example we will create a generic handler for a filetype for the web server by using the Module:digiweb.

            # test_pih.py
import sys,time,digiweb
sys.path.append("WEB/Python/PythonInsideHTML.zip")
from PythonInsideHTML import PIH

def http_handler(type, path, headers, args):
 exec PIH("WEB/Python%s"%(path)).PythonCode()
 return (digiweb.TextHtml,py_code.getvalue())


hnd = digiweb.Callback(http_handler)
while (True):
  time.sleep(1000)

Now you can just upload a file ending in a via the Python file management section of the webui, then just navigate to http://device_address/filename.

For example uploading the following (template.pih) will demonstrate displaying information about the HTTP request passed to the http_handler. The Python code generated by this script is run on the same scope as the http_handler function so has access to the arguments (type, path, headers, args).

Request info

<%= type %> request for path '<%= path %>'

Headers: <% for h in headers: %> <% end %>
<%= h %> <%= headers[h] %>

Args: <%= args %>

Navigating your browser to "http://device_address/template.pih" will give you a page displaying information about the HTTP request.

GET request for path '/template.pih'
________________________________________
Headers:
host	device_address
referer
agent	Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.48 Safari/525.19
________________________________________
Args: None
________________________________________

Source

by importing the following module you can use these features: Media:PythonInsideHTML.zip

Related

Module: digiweb‎

© 2021 Digi International Inc. All rights reserved.
Python inside HTML updated on 11 Jun 2018 12:08 PM

How to get HTML file form URL in Python.
Call the read function on the webURL variable..
Read variable allows to read the contents of data files..
Read the entire content of the URL into a variable called data..
Run the code- It will print the data into HTML format..

Can we add Python file in HTML?

It is possible to run embed Python within a HTML document that can be executed at run time.

How do I run a Python script in HTML?

The Best Answer is. 3.. To run, open command prompt to the New folder directory, type python server.py to run the script, then go to browser type localhost:5000 , then you will see button. You can click and route to destination script file you created.