如何在HTML文件中插入Python代码
如何在HTML文件中插入Python代码?
<html>
<head>
</head>
<h1>Hello Python!</h1>
<body>
Here i want to insert Python Code
</body>
</html>
4 个回答
1
这是一个关于CGI
的简单示例
print('Content-Type: text/html')
print('\n\n')
print('''<html>
<head>
</head>
<h1>Hello Python!</h1>
<body>''')
# Here insert Python Code
print('''</body>
</html>''')
这是一个关于WSGI
的简单示例
def application(environ, start_response):
output = '''<html>
<head>
</head>
<h1>Hello Python!</h1>
<body>'''
# Here insert Python Code which appends string to `output`
output += '''</body>
</html>'''
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
1
我觉得你想用Python语言来设计一个网站或网络服务。为了实现这个目标,你需要使用Flask或Django这两个框架(我个人更喜欢Flask)。Flask里面包含了werkzeug和jinja2这两个工具包。不过,你不能用Python写出像JavaScript那样的东西。
1
我觉得你想做的事情和在PHP中使用<php> smth </php>
标签是一样的。
但是这是不可能的。你可以试试像Brython这样的东西。
这可能是唯一的选择。或者你也可以试试Coffeescript,它和Python、Ruby挺像的。
不过如果你只想在服务器端做这件事,也就是说代码是在服务器上执行,而不是在浏览器里,那么你可以看看Flask。这个框架非常简单易用,还有很棒的模板引擎。
PS. 在HTML中包含除了JS以外的其他代码,或者编译成JS的语言,这不是个好主意。这样做只会带来麻烦。