• Python CGI编程和CGIHTTPServer



    Python2.7 的CGIHTTPServer

    可以作为一个简单的HTTP服务器,能够调用cgi脚本

    1 在任意目录下创建一个特殊的目录 cgi-bin ,用于存放自己写的脚本(.py或.cgi)

    2 在 cgi-bin 所在目录 执行 python -m CGIHTTPServer ,启动服务器

    3 在浏览器输入 IP:8000/cgi-bin/xxx.py   即可调用cgi-bin目录下的xxx.py脚本了(Linux可能要更改权限755)


    示例1

    hello.py

    #
    !/usr/bin/python #for Linux Windows: #!C:/Python34/python.exe # -*- coding: utf-8 -*- print "Content-type:text/html " #HTTP的header 必不可少 表示头部结束,后面的内容都为body print ''' <html> <head> <title>Hello from Python CGI</title> </head> <body> <h1>Hello! This is my first CGI program!!!</h1> </body> </html> '''


    Headers
    描述
    Content-type: 请求的与实体对应的MIME信息。例如: Content-type:text/html
    Expires: Date 响应过期的日期和时间
    Location: URL 用来重定向接收方到非请求URL的位置来完成请求或标识新的资源
    Last-modified: Date 请求资源的最后修改时间
    Content-length: N 请求的内容长度
    Set-Cookie: String 设置Http Cookie

    Apache 执行cgi脚本

      修改配置文件 /path/to/conf/httpd.conf

      1 开启加载模块 

        LoadModule cgid_module /usr/lib/apache2/modules/mod_cgid.so

      2 配置脚本目录别名  

        ScriptAlias /cgi-bin/  /home/zoro/cgi-bin/      #注意最后一个斜杠前后要保持一致   别名和目录名都可以随意起 

      3 设置脚本目录访问权限

        <Directory "/home/zoro/cgi-bin">

          Options ExecCGI              //

          Require all granted  

        </Directory>

      

      另一个例子:  

      /home/sqd/cgi-bin/hello.sh  

    #/bin/sh
    
    echo "Content-Type: text/html; charset=utf-8"   #header
    
    echo                 #表示header结束 不能少
    
    echo "<h1>Hello from sh CGI.</h1>"

      chmod 755 hello.sh

      缺少header会报错: Internal Server Error

      查看错误日志(/usr/local/apache2/logs/error_log)可见:malformed header from script 'hello.sh': Bad header: Hello from sh CGI.

      

    KEEP LEARNING!
  • 相关阅读:
    JavaScript对象
    JavaScript基础
    MySQL总结
    前端的基础知识汇总
    反射,面对对象高阶
    django中的认证登陆与用户的创建
    django的cookie和session
    ajax的json包含于xml的区别
    django的分页系统
    django的orm简签
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4929773.html
Copyright © 2020-2023  润新知