CGIHTTPRequestHandler 在 python 中运行 php 或 python 脚本

发布于 2024-10-22 12:14:17 字数 976 浏览 2 评论 0原文

我正在 Windows 上编写一个简单的 python Web 服务器..

它可以工作,但现在我想运行动态脚本(php 或 py)而不仅仅是 html 页面..

这是我的代码:

from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler

class RequestsHandler(CGIHTTPRequestHandler):
    cgi_directories = ["/www"] #to run all scripts in '/www' folder
    def do_GET(self):
        try:
            f = open(curdir + sep + '/www' + self.path)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404, "Page '%s' not found" % self.path)

def main():
    try:
        server = HTTPServer(('', 80), RequestsHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()

如果我将 php 代码放在 www 文件夹中我获取页面但代码没有被解释

我必须做什么?谢谢

I'm writing a simple python web-server on windows..

it works but now I want to run dynamic scripts (php or py) and not only html pages..

here is my code:

from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler

class RequestsHandler(CGIHTTPRequestHandler):
    cgi_directories = ["/www"] #to run all scripts in '/www' folder
    def do_GET(self):
        try:
            f = open(curdir + sep + '/www' + self.path)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404, "Page '%s' not found" % self.path)

def main():
    try:
        server = HTTPServer(('', 80), RequestsHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()

if I put php code in www folder I get the page but the code isn't interpreted

what I have to do? thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

壹場煙雨 2024-10-29 12:14:18

您的第一个 Python CGI 网站

对于制作第一个 Web 服务器的人,我将这个简单的示例与使其正常工作所需的所有步骤放在一起。需要创建两个文件。第一个 server.py 是运行 Web 服务器的脚本。第二个是 Python CGI 脚本,服务器将运行该脚本并将其输出作为“网页”发送到浏览器。

首先为服务器创建一个项目文件夹,例如您的主目录中的 simple_server ,或者您喜欢放置项目的任何位置。

在该文件夹中创建一个名为cgi-bin的子文件夹。然后将第一个脚本复制到文件 server.py 中,并将其放入 simple_server 中。然后创建文件 my_cgi_script.py 并将其放置在 cgi-bin 文件夹中。 这些文件位于本指南正文的下方。

目录结构应如下所示:

|
-- [simple_server]
      |
      -- server.py
      |
      -- [cgi-bin]
            |
            -- my_cgi_script.py

您需要在my_cgi_script.py上设置权限以使其可执行 - 否则Web 服务器无法运行它来生成网页输出。如果您使用的是 Linux 或 MacOS,请在命令 shell 中输入:

$ chmod +x cgi-bin/my_cgi_script.py

在 Windows 上,使用文件资源管理器找到该文件并右键单击它,并确保其权限允许执行。

打开命令 shell,cd 进入 simple_server 文件夹并执行 server.py 脚本:

$ cd simple_server
$ python server.py

它应该静默运行,到目前为止没有任何输出。然后在您最喜欢的浏览器的新选项卡中,浏览到以下 URL:

http://localhost:8000/cgi-bin/my_cgi_script.py

“hello world!”应该会像网页一样出现在浏览器中,并带有大量空白(如果您没有立即看到它,请在左上角查找)。好了,你已经做到了!您已经使用 Python CGI 制作了您的第一个网站!

server.py

from http.server import HTTPServer, CGIHTTPRequestHandler

if __name__ == '__main__':
    try:
        CGIHTTPRequestHandler.cgi_directories = ['/cgi-bin']

        httpd = HTTPServer(('', 8000),             # localhost:8000
                           CGIHTTPRequestHandler)  # CGI support.

        print(f"Running server. Use [ctrl]-c to terminate.")

        httpd.serve_forever()

    except KeyboardInterrupt:
        print(f"\nReceived keyboard interrupt. Shutting down server.")
        httpd.socket.close()

cgi-bin/my_cgi_script.py

#!/usr/bin/env python
# The line above ^ is important. Don't leave it out. It should be at the
# top of the file.

import cgi, cgitb # Not used, but will be needed later.

print("Content-type: text/html\n\n")
print("hello world!")

如果你运行它,你可能会想
“刚刚发生了什么?” server.py 设置并正在运行 Web 服务器。它被配置为使用CGIHTTPRequestHandler运行脚本。此请求处理程序将运行 cgi-bin 文件夹中的文件作为脚本。它使用命令 shell 来执行此操作。

my_cgi_script.py 顶部,#!/usr/bin/env python 行告诉命令 shell 使用 Python 解释器执行文件中的代码。

服务器将您在浏览器中输入的 URL 理解为文件的路径 - 在本例中为 CGI 脚本 my_cgi_script.py,位于 cgi-bin 文件夹下:http://localhost:8000/cgi-bin/my_cgi_script.py

如果您查看服务器运行的命令 shell,您可以看到详细说明其处理的 Web 流量的消息。每次您访问此服务器进程时,它都会输出更多消息 - 继续尝试在浏览器中刷新并观看它。

您现在可以修改 my_cgi_script.py 以输出更多文本,或者可以让它输出 HTML 标记并生成更有趣的网页。

要创建包含 CGI 脚本的网页,请创建一个名为 index.html 的文件,并将其放置在包含 server.py 的文件夹中 - index 的内容.html 如下。

index.html

<!DOCTYPE html>
<html>
  <body>

    <h1>My First Heading</h1>
    <p>My first paragraph.</p>

    <!-- Simple example to include text from the CGI script in this web page. -->

    <object type="text/html" data="/cgi-bin/my_cgi_script.py"></object>

  </body>
</html>

目录结构现在应如下所示:

|
-- [simple_server]
      |
      -- server.py
      |
      -- index.html
      |
      -- [cgi-bin]
            |
            -- my_cgi_script.py

完成后,如果您停止了服务器进程,请再次启动它并尝试浏览到 http://localhost:8000 并验证您看到“hello world!”在“我的第一段”下方。 index.html 是一个特殊的文件名,Web 服务器将其用作其 URL 的默认页面。现在您已具备创建出色网站的所有基础知识!

展望未来,对于学习或认真开发的最佳 Web 开发框架应该是什么,存在各种不同的看法。从这个示例中,您应该了解非常基本的配置、设置和浏览器/服务器交互。

那么现在的问题是,接下来该何去何从?您可以继续追求上述模型,并学习如何使用 Python CGI 脚本将更多功能添加到基本站点中,并将它们绑定到 HTML 页面中的表单操作。这将是一条完全有效的路径,你可能会学到很多东西。

有人向我推荐了一个很好的网站,它使用名为 Django 的生产级 Web 服务器。据我所知,它有非常好的教程和其他资源来帮助开始 Web 开发。

该网站是 Django Girls 教程。不要被网站的名称吓倒,任何人都可以从本教程中受益,它很好地介绍了使用 Django 进行 Web 开发所需的工具和技术。

Django Girls 是一个活跃的女性开发者社区,在世界各地举办活动,并将她们与其他可以帮助她们进步的人联系起来。

Django Girls 教程:https://tutorial.djangogirls.org/en/

更深入的 Python CGI示例: https://www.tutorialspoint.com/python/python_cgi_programming.htm

用于学习HTML,这个网站有很好的教程: https://www.w3schools.com/html/default.asp

CGI 支持模块参考,cgihttps ://docs.python.org/3/library/cgi.html

包含本示例中使用的类的文档可以在以下位置找到:https://docs.python.org/2/library/internet.html

Your First Python CGI Website

For someone making their first web server, I put this simple example together with all the needed steps to get it working. There are two files that need to be created. The first, server.py is the script that runs the web server. The second is a Python CGI script that the server will run and send its output to the browser as a "web page".

First create a project folder for the server, something like simple_server in your home directory, or wherever you like to put your projects.

In that folder create a subfolder called cgi-bin. Then copy the first script to a file, server.py and place that in simple_server. Then create the file, my_cgi_script.py and place that in the cgi-bin folder. These files are below in the body of this howto.

Directory structure should look like this:

|
-- [simple_server]
      |
      -- server.py
      |
      -- [cgi-bin]
            |
            -- my_cgi_script.py

You will need to set the permissions on my_cgi_script.py to make it executable - otherwise the web server can't run it to generate the web page output. If you're on Linux or MacOS, in the command shell enter:

$ chmod +x cgi-bin/my_cgi_script.py

On Windows, locate the file with the file explorer and right-click it, and make sure its permissions allow execution.

Open the command shell, and cd in to the simple_server folder and execute the server.py script:

$ cd simple_server
$ python server.py

It should run silently without any output so far. Then in a new tab in your favorite browser, browse to this URL:

http://localhost:8000/cgi-bin/my_cgi_script.py

"hello world!" should appear in the browser with a lot of whitespace as the web page (look for it in the upper left corner if you don't see it right away). There, you've done it! You've made your first website with Python CGI!

server.py

from http.server import HTTPServer, CGIHTTPRequestHandler

if __name__ == '__main__':
    try:
        CGIHTTPRequestHandler.cgi_directories = ['/cgi-bin']

        httpd = HTTPServer(('', 8000),             # localhost:8000
                           CGIHTTPRequestHandler)  # CGI support.

        print(f"Running server. Use [ctrl]-c to terminate.")

        httpd.serve_forever()

    except KeyboardInterrupt:
        print(f"\nReceived keyboard interrupt. Shutting down server.")
        httpd.socket.close()

cgi-bin/my_cgi_script.py

#!/usr/bin/env python
# The line above ^ is important. Don't leave it out. It should be at the
# top of the file.

import cgi, cgitb # Not used, but will be needed later.

print("Content-type: text/html\n\n")
print("hello world!")

If you got it running, you may be wondering
'what just happened?' server.py set up and is running a web server. It is configured to run scripts using the CGIHTTPRequestHandler. This request handler will run files within the cgi-bin folder as scripts. It uses the command shell to do this.

At the top of my_cgi_script.py, the #!/usr/bin/env python line tells the command shell to execute the code in the file using the Python interpreter.

The URL you entered in the browser is understood by the server as a path to a file - in this case the CGI script, my_cgi_script.py, under the cgi-bin folder: http://localhost:8000/cgi-bin/my_cgi_script.py

If you take a look at the command shell that the server is running in, you can see messages detailing the web traffic it's handled. Each time you access this server process, it will output more messages - go ahead and try refresh in the browser and watch it.

You can now modify my_cgi_script.py to output more text, or you could have it output HTML tags and generate a more interesting web page.

To create a web page that incorporates the CGI script, create a file named index.html and place it in the folder with server.py - the content for index.html is below.

index.html

<!DOCTYPE html>
<html>
  <body>

    <h1>My First Heading</h1>
    <p>My first paragraph.</p>

    <!-- Simple example to include text from the CGI script in this web page. -->

    <object type="text/html" data="/cgi-bin/my_cgi_script.py"></object>

  </body>
</html>

The directory structure should now look like this:

|
-- [simple_server]
      |
      -- server.py
      |
      -- index.html
      |
      -- [cgi-bin]
            |
            -- my_cgi_script.py

Once that's done, if you stopped the server process, start it up again and try browsing to http://localhost:8000 and verify you see "hello world!" below "My first paragraph." index.html is a special file name that web servers use as the default page for their URL's. Now you have all the basics in place to create a great website!

Moving forward, there are various opinions on what the best web development framework should be for learning, or serious development. From this example you should get a sense for very basic configuration, setup, and browser/server interaction.

So now, the question is where to go from here? You could continue to pursue the above model, and learn how to put more functionality into the basic site using Python CGI scripts, and bind them to form actions in the HTML page. That would be a perfectly valid path, and you'd likely learn a lot.

Someone recommended to me a good site that uses a production quality web server called Django. From what I gather, it has very good tutorials and other resources to help get started in web development.

That site is Django Girls Tutorial. Don't be put off by the name of the site, anyone can benefit from the tutorial and it provides a very good introduction to the tools and technology you'll need to progress in web development with Django.

Django Girls is an active developer community for women that hosts events around the world, and connects them with others that can help with their progress.

Django Girls Tutorial: https://tutorial.djangogirls.org/en/

More in-depth Python CGI examples: https://www.tutorialspoint.com/python/python_cgi_programming.htm

For learning HTML, this site has good tutorials: https://www.w3schools.com/html/default.asp

Reference on the CGI support module, cgi: https://docs.python.org/3/library/cgi.html

Documentation that includes the classes used in this example can be found within: https://docs.python.org/2/library/internet.html

妖妓 2024-10-29 12:14:18

我认为你已经过度工程化了。

#!/usr/bin/env python
import CGIHTTPServer

def main():

    server_address = ('', 8000)
    handler = CGIHTTPServer.CGIHTTPRequestHandler
    handler.cgi_directories = ['/cgi']
    server = CGIHTTPServer.BaseHTTPServer.HTTPServer(server_address, handler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()

I think you are over engineering.

#!/usr/bin/env python
import CGIHTTPServer

def main():

    server_address = ('', 8000)
    handler = CGIHTTPServer.CGIHTTPRequestHandler
    handler.cgi_directories = ['/cgi']
    server = CGIHTTPServer.BaseHTTPServer.HTTPServer(server_address, handler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()
可爱咩 2024-10-29 12:14:18

你使php文件可执行吗?
chmod +x spam.php (对于 Linux,我不知道如何使文件在 Windows 上可执行)

您需要在 PC 上安装 PHP 解释器以及

来自回复的源 此处

您还应该考虑使用 作为间接替代方案。

Did you make the php file executable??
chmod +x spam.php (for Linux, I have no Idea how to make files executable on windows)

You would need the PHP interpreter installed on your PC as well

source from a reply HERE

You should also consider using THIS as an indirect alternative.

终难遇 2024-10-29 12:14:18

问题出在 CGIHTTPServer 类上。它不设置 CGI 环境变量。
此问题已在这里修复:
https://github.com/gabrielgrant/tonto/blob/master/tonto.py

The problem is with the CGIHTTPServer Class. It doesn't set CGI env variables.
This has been fixed here:
https://github.com/gabrielgrant/tonto/blob/master/tonto.py

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文