个人工具

Mod python入门

来自Ubuntu中文

跳转至: 导航, 搜索

mod_python

mod_python 是Apache网络服务器的扩展模块,它可以让python解释器直接成为Apache的一部分,使用mod_python处理程序框架可以访问丰富的API,深入Apache的内核等。 除了基本功能外,它还带有用于web开发的处理程序:

  • CGI处理程序,允许使用mod_python解释器运行CGI脚本
  • PSP处理程序,允许使用HTML以及Pyhthon代码混合编程创建可执行网页(executable webpage), 或者Python服务页(Python Server Page)
  • 发布处理程序,允许使用URL调用Pyhthon函数。
官方主页:http://modpython.org/

配置Apache

如果安装了mod_python后,可以检查Apache的相关配置是否启用,如果需要,请添加如下行至 http.conf或apache.conf (不同发行版可能使用不同的名字) 具体如下:

LoadModule python_module /usr/lib/apache2/modules/mod_python.so

如果要使用CGI处理程序,请将下面的配置加入 http.conf或apache.conf 中

<Directory /path/to/your/directroy >
AddHandler python-program .py
PythonHandler mod_python.publisher
PythonDebug On
</Directory>

Demo PyCGI

提交页面 /var/www/submit.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>OpenSSL证书认证管理中心</title>
</head>
<form action="http://127.0.0.1/pycgi/form/show" method="POST">
    Common Name <input type="text" name="name" />
                <input type="submit" value="提交" />
</form>
</html>

服务端处理脚本

/var/www/pycgi/form.py

#!/usr/bin/env python

import mod_python 
def show(req, name):
	s = """\
<html>
Dear %s,<br>
Thank You for your kind comments, we
will get back to you shortly.
</html>""" % name
        return s

Python logging 模块

import os
import logging
# 初始化  
logger = logging.getLogger()
  
#设置日志文件名称及其存储类型  
file = logging.FileHandler("/tmp/ca-create.log")  
logger.addHandler(file)  
#设置日志记录格式 
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")  
file.setFormatter(formatter)   
#设置日志记录格式  
logger.setLevel(logging.NOTSET) 

#使用示例

result=os.system('openssl genrsa -out %s 2048' % CA_CONFIG)
logger.info(result)