`
夏莹_合肥
  • 浏览: 178761 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

python语言web之旅(python, mod_python, pyamf, flex, apache)

阅读更多

本篇文章主要介绍了python怎么样用于web应用。(windows环境下)

 

一. 利用apache的mod_python模块实现python和web服务器之间的通信

 

    1. 下载并安装apache2.2.11 ,python2.5版本请从官网下载http://www.python.org/

 

    2. 下载并安装mod_python3.3.1, 安装的最后请选择好你的apache的路径就好了。mod_python是嵌入Python解析器的一个Apache模块。通过mod_python你可以用python写基于web的应用。

 

    3. 进入apache的安装目录,进入conf目录,打开httpd.conf文件,修改其配置。在一大段LoadModule的下面,添加一行LoadModule python_module modules/mod_python.so,让Apache加载mod_python模块。再添加一个Directory节点,如下

 

<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/pyweb"> # 能用apache访问的目录
    AddHandler mod_python .py
    # SetHandler mod_python
    PythonHandler mod_python.publisher
    PythonDebug On
</Directory>

 

下面来解释一下。AddHandler mod_python .py 这句告诉Apache所有访问pyweb目录下的后缀名为py的请求都将被交给mod_python模块来处理。PythonHandler mod_python.publisher,这句是指定python处理请求的handler是mod_python.publisher(handler类似于servlet,至于publisher这种handler,请参考mod_python手册 的第87页)

 

    4. 在目录pyweb下建立文件index.py,内容如下:

 

def hello(req, name="anonymous"):
    return "Hello %s" % name
 

第一个参数req是mod_python封装的request对象,具体使用方法请见mod_python手册, 第二个参数是请求参数。请在浏览器上访问以下两个URL测试结果

http://localhost/pyweb/index.py/hello(返回 hello anonymous)

http://localhost/pyweb/index.py/hello?name=shane(返回 hello shane)

我们可以看出mod_python的路由规则了,index.py是文件名,hello是方法名。

 

二. python和flex的通信(flex + Apache + mod_python + wsgi + pyamf + python)

 

    1. 下载并安装pyamf 。Adobe的flash和flex使用AMF(Action Message Formate)来进行应用程序和服务器之间的通信。AMF将通信消息序列化成一种非常紧密的二进制形式在网络上进行传输。pyamf用于支持python和flash或flex的客户端进行通信。将python的安装路径加入windows的环境变量,解压缩pyamf,进入其目录,执行python setup.py install --disable-ext,开始安装。

 

    2. 在mod_python的基础上,配置好wsgi。WSGI是指Web Server Gateway Interface,它是为web服务器和应用程序或web框架之间交互定义的一组基于python语言的规范。pyamf框架和Apache交互是遵循wsgi规范的,所以mod_python和pyamf之间还需要架一个wsgi桥梁。下载WSGI gateway for mod_python ,一个python文件。

 

    3. 建立你的web应用的根目录,例如C:\pyweb。解压缩wsgi.rar,把wsgi.py放入C:\pyweb下。再在目录下建立startup.py,内容如下:

 

# -*- coding: UTF-8 -*-
from pyamf.remoting.gateway.wsgi import WSGIGateway

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s'
)

class EchoService(object):
    """
    Provide a simple server for testing.
    """
    def echo(self, data):
        """
        Return data with chevrons surrounding it.
        """
        return '<<%s>>' % data

services = {
   'echo': EchoService(),
   # Add other exposed functions here
}

application = WSGIGateway(services, logger=logging, debug=True)
 

    请注意这里的文件名叫startup.py和文件中的变量名application

 

    4. 为Apache访问C:\pyweb赋予权限。打开httpd.conf,添加如下Directory节点:

 

<Directory "C:/pyweb">
        Order allow,deny
        Allow from all
</Directory>
 

    5. 配置虚拟主机VitualHost。如果不明白什么是虚拟主机,请参考Apache的官方文档http://httpd.apache.org/docs/2.2/vhosts/ 。打开httpd.conf,拉到最下面,去掉Include conf/extra/httpd-vhosts.conf前面的注释。再打开extra/httpd-vhosts.conf文件,修改如下

 

NameVirtualHost *:80

<VirtualHost *:80>
    DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>

        ServerName www.xiaying.com
        DocumentRoot "C:/pyweb"
	
	 CustomLog "logs/www.xiaying.com-access.log" combined
        ErrorLog "logs/www.xiaying.com-error.log"

        LogLevel warn
        ServerSignature Off

        # PyAMF gateway
        <Location /flashservices/gateway>
                SetHandler mod_python
                PythonPath "['C:/pyweb']+sys.path"
                PythonHandler wsgi
                PythonOption wsgi.application startup::application
                PythonOption SCRIPT_NAME /flashservices/gateway

                # Only enable the options below when you're debugging the
                # application. Turn them Off in a production environment.
                PythonDebug On
                PythonAutoReload On
        </Location>

</VirtualHost>
 

    这是一种基于域名的虚拟主机,当我们用www.xiaying.com这个域名访问的时候,就会被定向到C:/pyweb目录。配置域名,请打开system32/drivers/etc/hosts,添加一行127.0.0.1    www.xiaying.com。

    /flashservices/gateway这个定义了PyAMF的gateway,即flex所谓的endpoint,远程调用的URL是:http://www.xiaying.com/flashservices/gateway。

    PythonOption wsgi.application startup::application 其中wsgi:application是键名,在wsgi.py文件中可以找到,startup::application分别对应模块名和模块中的对象名。

 

    6. 下面我们先简单建立一个python客户端测试一下。代码如下:

 

from pyamf.remoting.client import RemotingService

gateway = RemotingService('http://www.xiaying.com/flashservices/gateway')
echo_service = gateway.getService('echo')
print echo_service.echo('Hello python')
 

    记得重启Apache,然后执行以上代码,如果看到<<Hello python>>,则配置成功了。

 

    7. 建立flex的客户端来测试。代码如下:

 

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 
	creationComplete="remoteObject.echo('Hello python')">
	
	<mx:RemoteObject id="remoteObject" destination="echo" endpoint="http://www.xiaying.com/flashservices/gateway" />
	
	<mx:TextInput text="{remoteObject.echo.lastResult}" x="30" y="20"/>
	
</mx:Application>
 

    编译生成main.swf文件,放入文件夹C:\pyweb下,在浏览器敲入网址http://www.xiaying.com/main.swf,看到文本框中出现<<Hello python>>,成功。

 

三. python和flex间的类型映射

 

    1. 用类型对象在flex和python之间进行通信的时候就会涉及到actionscript类型和python类型之间序列化反序列化映射的问题,请见如下代码:

 

    Project.as

 

package {
	
	[Bindable]
	[RemoteClass(alias='com.project.Project')]
	public class Project {
		
		public var project_name:String;
		public function Project() { }
	}
}
 

    [RemoteClass(alias='com.project.Project')],指定了远程的python类。com包下的project模块的Project类,继承自object

 

class Project(object):
    def __init__(self, project_name = None):
        self.project_name = project_name
 

    结束。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics