如何在服务器上运行 .cgi 文件? 我在运行 python 脚本和 html 表单时遇到了一个主要问题,因为浏览器在浏览器窗口中显示了源代码。 如何通过在服务器端运行 html 而不将其暴露给客户端的浏览器来打印输出?
答案 0 :(得分:0)
我找到了问题的答案:
第 1 步:将您的 python 文件命名为 .cgi
而不是 .py
。.py
文件仅在 python 终端内运行,或者如果您可以编辑服务器配置文件以显示 .py
文件扩展名就好像它们是 .cgi
文件一样。如果您没有那个特权,您可以使用 .cgi
作为文件扩展名,在您的服务器上运行 python 并在客户端打印输出。
注意:您可以在服务器端使用您的 Python 代码,但您无法在客户端运行它,因此始终知道您在做什么 .cgi gives you that power
第 2 步:将您的 .html
代码与 Python 代码链接起来,您只需将 .cgi
文件的链接提供给表单元素的 action 属性即可。见下文:-
<form action="server_action.cgi">
<input name="Message" type="input">
</form>
这只是一个例子,我没有在上面链接真正的 .cgi
文件。
注意:要在同一 html 页面中打印输出,只需使用此代码
print('Content-Type:text/html')
print()
print(
在以上两行之后,只需将您的 html 代码复制并粘贴到此方括号内)
功能。只需复制并粘贴上面的代码即可查看其工作原理。
注意 "
应该写成 \"
在方括号内,否则 python 将在整个代码呈现之前关闭它的打印 "
。它也会在客户端产生错误。
第 3 步:(最重要)处理:这一步是 Python 函数发挥作用的地方,它可以理解用户在其输入中所说的内容并根据需要进行输出。我在下面写了一个例子,不要在这里运行这个代码,它不会产生输出,因为在 STACKOVERFLOWS EDITOR 上没有安装 Python 库。[SKIP THIS CODE BELOW IF YOU ALREADY HAVE XAMPP INSTALLED AND KNOW HOW TO RUN CGI FILES ON IT
]
如果你没有安装 https://www.apachefriends.org/index.html XAMPP托管服务器。
在 xampp for windows 中运行 Python 下面是如何设置 xampp 以运行 .cgi
文件的说明:
STEP-1:[Download Python]
Download & install the latest version of python from www.python.org Download
Python & click on the windows installer of any version [ex. python-3.6.2]
STEP 2: [Install Python] Install in any directory of your harddrive [ex.
D:\python-3.6.2]
Click on config button just right to the Start Button and open `httpd.conf`
file and make the changes as said in the linked post BELOW ⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇
[RUN PYTHON SCRIPTS WITH XAMPP][1]
Running Python scripts with Xampp
我之前讨论过的 server_action.cgi
的代码
在代码的开头使用 XAMPP Note that #!C:\Python39\python.exe
的安装。这是你的python解释器的位置(尽管如果你的服务器提供自己的库来解释cgi文件,则不需要)
#!C:\Python39\python.exe
import cgi
import cgitb
import cgitb
cgitb.enable()
import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")
print("<TITLE>CGI script output</TITLE>")
print("<H1>This is my first CGI script</H1>")
print("Hello, world!")
print("""<form action="server_action.cgi">
<input name="Message" type="input">
</form>""")
form = cgi.FieldStorage()
text=form["Message"].value
#'Message' is the value of my 'name' attribute used in my <input name=""> tag
Use
print("""
this
format
""") to print multiple lines in one print output.
import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")
This was used
to prevent displaying error on the clients browser if any occured.
```/path/to/logdir``` is the path where you want to store the error that was
prevented directly on the browser window ```display=0```
答案 1 :(得分:-1)
尝试使用流行的 Python Web 框架 django。如需更多信息,请访问 https://www.djangoproject.com/