在HTML中调用Python代码的技巧

当我们利用html代码制作网页时,可以用以下方法进行python代码的调用:

1.简单的python代码例如输出‘hello world’时,可以选择直接在网页写入python代码的方式调用,这时候我们就需要了解Pyscript了。以下是在网页里直接运行简易python语段的代码:

 <html>
		<head>  
			<meta charset="utf-8">  
		  </head>  
        <body>
		   <pyscript> print('Hello world') </pyscript>
        </body>
     </html>

2.当python代码稍微比较复杂,且处于网页构建初期时,我们可以考虑用flask框架对网页的按钮进行整体布局。

方法 1)

当网页代码较为简单时,可以直接用html代码代替render_template:

test1.py

def run():
  print('hello world')
run()

test.py(含flask包)

from flask import(
    Flask, render_template, request, redirect, globals
)
import test1

app= Flask(__name__)

@app.route("/",methods=['GET', 'POST'])
def index():
     return '<form action = "http://localhost:5000/b" method = "post"></form><a href="/test"><button onclick="">进入测试</button></a><a href="/test1">
    

@app.route("/test",methods=['GET', 'POST'])
def test():
    test1.run()
    return '<form action = "http://localhost:5000/b" method = "post"></form><a href="/test"><button onclick="">进入测试</button></a>
if __name__ == '__main__':
    app.run(debug=True)

运行test1.py,ctrl+单击点开下图终端中出来的网址:

 

点击按钮运行即可出现hello word字样。

方法 2) 

当网页代码较为复杂且长时,可以使用render_template来进行前后端交互。此时我们需要在包含flask的python代码同文件夹下新建一个template文件夹:

test.py代码同上,

b.html

<html>
		<head>  
			<meta charset="utf-8">  
		  </head>  
        <body>   
           <form action = "http://localhost:5000/" method = "post">
           </form>
		   <a href="/test"><button onclick="">进入测试</button></a>
        </body>
     </html>

 test1.py

from flask import(
    Flask, render_template, request, redirect, globals
)
import test1

app= Flask(__name__)

@app.route("/",methods=['GET', 'POST'])
def index():
     return  render_template(
        "b.html"
     )
    

@app.route("/test",methods=['GET', 'POST'])
def test():
    test1.run()
    return render_template(
         "b.html"
     )

if __name__ == '__main__':
    app.run(debug=True)

 测试的方式同方法1),这里不多赘述。

3.网页设计初期,以上两种方法足以,但是博主在设计网页时是设计到一半才发现,在前期写纯Html文件后再使用flask框架设计按钮响应python脚本,会出现网页不稳定的情况,博主的图啊网页跳转都不见了。经过研究之后,博主又发现了一个不管在网页设计前期中期都可以使用的python脚本调用方法!那就是ActiveX控件。

这个控件只有IE浏览器中有(至少博主在熟悉的其他浏览器中没有找到这个控件),在我们想要使用它之前需要检查我们的IE浏览器是否已经启用ActiveX控件。手动打开IE的ActiceX控件需要如下几步:打开设置-Internet选项-安全-自定义级别-把和ActiveX有关的选项全部点启用或者提示。

 然后我们运行一下代码进行测试。

a.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="gb2312">
    <title>ceshi</title>
<script language="javascript">   
function exec1 (command) {   
  var ws = new ActiveXObject("WScript.Shell");   
  ws.exec(command);   
}   
</script> 
  </head>
  <body>
    <button class='button1' onclick="exec1('python  D:/xgcs/test1.py')">执行程序</button></p>
  </body>
</html>

利用IE浏览器打开网址,点击按钮运行即可。

 运行前会出现弹窗如下所示,点是和允许即可。 

 由于是输出,所以黑框一闪而逝很正常,要想看到print出来的hello world字样,得再加个输入input()。或者你的python运行出来是个ui窗口,那也会停留很久,别把黑框点叉叉即可。

希望以上博主的经验对大家有帮助,嘻嘻。

 

物联沃分享整理
物联沃-IOTWORD物联网 » 在HTML中调用Python代码的技巧

发表评论