pyramid开发者文档: https://trypyramid.com/documentation.html
在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结构,提供了开发的最简途径。此外,它还是高效开发重用代码的首选平台之一。
按照官方文档即可。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”
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()
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)
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’)修饰。
views类的函数中调用model中定义的接口。
我们访问数据库,实际上是访问数据库中存储的表格。所以model类的函数是通过entity类的实例来和数据库交互的。