python作为一种动态解释型语言,在实现各种框架方面具有很大的灵活性。

最近在研究python web框架,发现各种框架中需要显示的定义各种路由和Handler的映射,如果想要实现并维护复杂的web应用,灵活性非常欠缺。

如果内容以“约定即配置”的方式完成handler和路由的映射操作,可以大大增加python web框架的灵活性,此时动态映射是必不可少的。

在java mvc框架中,可利用反射机制,实现动态映射,而python也可以利用本身的特性,实现动态映射。

1、获得指定package对象(其实也是module)

为了遍历此包下的所有module以及module中的controller,以及controller中的function,必须首先获得指定的package引用,可使用如下方法:

__import__(name, globals={}, locals={}, fromlist=)加载package,输入的name为package的名字字符串

controller_package=__import__('com.project.controller',{},{},["models"])

ps:直接使用__import__('com.project.controller')是无法加载期望的package的,只会得到顶层的package-‘com’,除非使用如下方法迭代获得。

def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

官方文档描述如下

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned,not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components.

2、遍历指定package下的所有module

为了获得controller_package下的module,可先使用dir(controller_package)获得controller_package对象范围内的变量、方法和定义的类型列表。然后通过

for name in dir(controller_package):
  var=getattr(controller_package,name)
  print type(var)

遍历此package中的所有module,并根据约定的controller文件命名方式,发现约定的module,并在module中发现约定好的class。

如果name代表的变量不是方法或者类,type(var)返回的值为"<type 'module'>"。

3、遍历指定module中的class

依然使用dir(module)方法,只不过type(var)返回的值为"<type 'classobj'>"。

4、遍历指定class中的method

依然使用dir(class)方法,只不过type(var)返回的值为"<type 'instancemethod'>"或者<type 'function'>,第一种为对象方法,第二种为类方法。

5、遍历指定method中的参数名

使用method的func_code.co_varnames属性,即可获得方法的参数名列表。

以上方法,适合在python web运行前,对所有的controller提前进行加载,如果需要根据用户的请求再动态发现controller,依然可以使用上面的方法完成,只是会更加的简单,需要需找的controller路径已知,只需递归获得controller的引用即可,再实例化,根据action名,执行执行的action。

总结:主要使用的方法

__import__('name')、dir(module)、type(module)、getattr(module,name)

												

python 动态加载module、class、function的更多相关文章

  1. Python 动态加载并下载"梨视频"短视频

    下载链接:http://www.pearvideo.com/category_1 import requests from lxml import etree import re from urlli ...

  2. python 动态加载类对象

    第一步 加载模块 module  =__import__("modulename",fromlist=['']) 第二部 加载类对象 cls = getattr(module, & ...

  3. Python 动态加载 Extension Manager Classes

    看着看着发现了一个库:stevedore(http://stevedore.readthedocs.org/en/latest/managers.html),但是感觉文档做得不行啊,都没个tutori ...

  4. __import__ 与动态加载 python module

    原文出处: koala bear    Direct use of __import__() is rare, except in cases where you want to import a m ...

  5. 黄聪:AngularJS 动态加载控制器实例-ocLoazLazy

    一.AngularJS动态加载控制器和视图实例 路由配置关键代码: //二级页面 $stateProvider.state('main', { url: '/:name', /**如果需要动态加载数据 ...

  6. 动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法. 1.动态加载js 方法一:动态加载js文件 // 动态加载js脚本文件 function loadScript(url) { v ...

  7. JS动态加载 js css

    1.动态加载js function loadScript( url ){ var script = document.createElement( "script" ); scri ...

  8. 动态加载js,css(项目中需要的)

    最近做的一个项目需要加入百度统计,大家都知道百度统计在页面引用就是一坨js,实现方法很简单引用到页面就ok了. 那么问题来了,虽然我不知道百度统计的原理是啥,我的测试服引用了百度统计,百度统计账号里面 ...

  9. python基础-动态加载lazy_import(利用__import__)

    看了一天动态加载,普遍有这么几种方法,总结一下,由简入深,本文仅对查到的栗子们做个引用……省去你们大把查资料的时间= = 主要思想:把模块(文件)名.类名.方法名当成了变量 然后利用__import_ ...

随机推荐

  1. 敏捷开发之Scrum扫盲篇(转)

    转:http://www.cnblogs.com/taven/archive/2010/10/17/1853386.html 现在敏捷开发是越来越火了,人人都在谈敏捷,人人都在学习Scrum和XP.. ...

  2. 在MVC3或asp.net中修改KindEditor实现上传图片时添加水印

    主要修改两个文件:image.js和upload_json.ashx文件. 一.修改image.js文件 打开kindeditor/plugins/image目录下的image.js文件,找到 '&l ...

  3. 分布式缓存 memcache学习

    1.使用分布式缓存是为了解决多台机器共享信息的问题,通过访问一个ip和端口来可以访问不同的IIS服务器 2.memcache基础原理 在Socket服务器端存储数据是以键值对的形式存储 内存处理的算法 ...

  4. ytu 2011: C语言实验——找中间数(水题)

    2011: C语言实验——找中间数 Time Limit: 1 Sec  Memory Limit: 64 MBSubmit: 212  Solved: 122[Submit][Status][Web ...

  5. js实现iframe自适应高度

    转自:http://www.jb51.net/article/15780.htm 对于自适应高度的代码有很多,可效率什么的考虑进来好代码就不多见了,不过思路倒是差不多的! 不带边框的iframe因为能 ...

  6. Android项目环境搭建

    安装步骤: ①     安装JDK1.6 在Windows上配置Java环境变量 # JAVA_HOME(C:\Program Files\Java\jdk1.6.0_06),Path(C:\Prog ...

  7. loj 1011(状态压缩+记忆化搜索)

    题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=25837 思路:状态压缩+记忆化搜索. #include<io ...

  8. 让html元素随浏览器的大小自适应垂直居中

    转自:http://www.cnblogs.com/linjiqin/archive/2011/06/15/2081362.html 表格可以实现td中的元素垂直居中显示,但是前提条件必须定义td的高 ...

  9. coalesce

    coalesce我理解就是将多个partition合并成少量的partition. data.coalesce(2,true) 第一个参数是partition数量 第二个参数是合并是是否进行shuff ...

  10. Windows计数器做性能监控(window server 2008服务器)

    使用Windows计数器 一.创建数据收集器集 二.创建数据收集器 三.使用数据收集器 1.修改数据收集器的属性 2.手动启用.手动停止数据收集器集 3.计划任务 4.在性能监视器中查看 一.性能监视 ...