从 Python 快速启动 CGI 服务器

很多人知道 Python 3 可以快速启动一个 HTTP 服务器:

$ python3 -m http.server 8000

今天我查阅 http.server 模块发现它支持运行 CGI 脚本,只要加上 --cgi 选项。

入门 Web 后端的初学者一定是要学习 CGI 的(不管是学历史还是学概念都有好处),而配置 Apache / NGINX 环境对他们来说可能比较困难。我发现用 Python 这种自带的基础服务器既方便又简单。

例子

我们来写一个 Hello World 的 Python CGI 程序 hello.py 放在 cgi-bin/ 里:

#!/usr/bin/python3
print('Content-type: text/html')
print()
print('Hello world!')

再写一个前端网页 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello Test</title>
</head>
<body>
    <form action="/cgi-bin/hello.py" method="post">
        <button type="submit">Hello</button>
    </form>
</body>
</html>

整个目录结构为:

cgi-bin/
    hello.py
index.html

然后将 CGI 脚本赋予运行权限:

$ chmod a+x cgi-bin/hello.py

运行测试

运行

$ python3 -m http.server --cgi 8000

浏览器访问 http://127.0.0.1:8000/

图片

点击按钮:

图片

(本文完)

转载于:https://www.cnblogs.com/gscnblog/p/10394782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值