Python web开发框架—— Pyramid学习(一)

pyramid开发者文档: https://trypyramid.com/documentation.html

一、pyramid简介

在Python web 开发框架里有多种选择,有Django、Tornado、Flask、web2py、Pylons、Pyramid等等,
Pyramid以其高效率和快节奏的开发能力而出名。官方文档是这样描述的:Pyramid is a small, fast, down-to-earth Python web framework. It is developed as part of the Pylons Project. It is licensed under a BSD-like license. 此开源Web框架有一个独立于平台的MVC结构,提供了开发的最简途径。此外,它还是高效开发重用代码的首选平台之一。

二、pyramid安装

按照官方文档即可。As an example, for Python 3.6+ on Linux:
#set an environment variable to where you want your virtual␣environment
$ export VENV=~/env
#create the virtual environment
$ python3 -m venv $VENV
#install pyramid
$ $VENV/bin/pip install pyramid
#or for a specific released version
$ $VENV/bin/pip install “pyramid==1.9.4”

For Windows:
#set an environment variable to where you want your virtual environment
c:> set VENV=c:\env
#create the virtual environment
c:> python -m venv %VENV%
#install pyramid
c:> %VENV%\Scripts\pip install pyramid
#or for a specific released version
c:> %VENV%\Scripts\pip install “pyramid==1.9.4”

三、pyramid框架下程序解析:

1. ini.py中main()是程序入口
2. main
	 def main(global_config, **settings):
	    init_log()
	    # 初始化db
	    init_db(settings)
	    # 认证并授权(保证db初始化成功的前提下)
	    ...
	    #重点看下面:
	    config = Configurator(settings=settings, root_factory=RootFactory)
	    config.set_authentication_policy(authentication_policy)
	    config.set_authorization_policy(authorization_policy)
	    config.set_session_factory(session_factory)
	    config.add_static_view('static', 'static', cache_max_age=3600)
	    #配置路由:
	    config.add_route('home', '/')
	    config.include(routes_config)
	    config.scan()
	    #Publish a WSGI app using an HTTP server
	    return config.make_wsgi_app()
3. 路由:即根据url,对应所要执行的函数。route文件夹下,admin.py:
	def routes_config(config):
		#配置路由
		config.include(admin_route, route_prefix='')
	def admin_route(config):
	    admin_route_maps = {
	        'admin': '/admin',
	    }
	    for (k, v) in admin_route_maps.items():
	        #添加路由
	        config.add_route(k, v) 
4. views:views类主要负责生成客户端即将渲染的界面。home_views.py:
    class HomeViews:
         def __init__(self, request):
             self.request = request
             self.params = request.params
             self.user_id = self.request.unauthenticated_userid    
          
         @view_config(route_name='home',request_method='GET',renderer='emotion:templates/layout.jinja2')
         def home(self):
             if not self.user_id:
                  return HTTPFound(location='/admin/login')
             user_menus = Permission(self.user_id).interceptor_user_menus()
         		  return {'menus': user_menus}

对于有路由的函数,用@view_config(route_name=‘route name’,,request_method=’ method’,renderer=‘template’)修饰。

5. model:model类负责对数据库的操作,封装好与数据库交互的接口。

views类的函数中调用model中定义的接口。

6. entity:entity中每个类代表数据库中的一种表格。

我们访问数据库,实际上是访问数据库中存储的表格。所以model类的函数是通过entity类的实例来和数据库交互的。

你可能感兴趣的:(Python,web)