首页 > 解决方案 > 是否可以使用 python 编写网站的后端,以便我可以调用 python 方法并显示其输出?

问题描述

我正在尝试创建一个以我在 python 上开发的算法为中心的网站。我的愿景是用户会输入一些东西,然后接收使用 python 生成的输出。我也在尝试调用 python 文件,因为我需要实现的 python 代码量很大。

为简单起见,我将如何将此 python 文件实现到带有输入空格的网站中:

数学.py

def calc(a, b):
   c = a + b
   return c

我试图理解 brython 并使用了他们提供的示例,但是它不起作用:

索引.html

<html>
  <script src="https://raw.githack.com/brython-dev/brython/master/www/src/brython.js"></script>
  <script src="https://raw.githack.com/brython-dev/brython/master/www/src/brython_stdlib.js"></script>

  <body onload="brython()">
    <input type="text" id="text" placeholder="Enter anything in mind">
    <span id="output"></span>
      <script src="C:\ExampleCode\example.py"
              type="text/python" id="script1"></script>
  </body>
</html

example.py(我也试过“.bry”)

从浏览器导入文档 def show_text(e): document['output'].textContent = e.target.value; 文档['text'].bind('input', show_text)

标签: javascriptpythonhtmlbackendbrython

解决方案


将html更改为:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://cdn.jsdelivr.net/npm/brython@3/brython.min.js">
</script>
<script src="https://cdn.jsdelivr.net/npm/brython@3/brython_stdlib.js">
</script>
  </head>
<body onload="brython()">
<script type="text/python">

<<your brython code here>>

</html>

这会从 cdn 加载 brython 并运行它。然后取决于您的代码是否可以在 brython 上下文中运行。

替代方案:Flask、Falcon 和许多其他框架。


推荐阅读