pyramid.doc_第1页
pyramid.doc_第2页
pyramid.doc_第3页
pyramid.doc_第4页
pyramid.doc_第5页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

基于Python2.7的Windows环境下pyramid配置步骤前言:pyramid是一个很好的利用Python开发web的框架。奉行Simplicity(简约),Minimalism(极简主义),Documentation(完善的文档),Speed(很快上手,开发快),Reliabitity(可信赖的,if it aint tested, it is broke!),Openness(开放的)。1.必须先安装Python2.7;2.下载ez_setup.py,将这个文件复制到C盘根目录。3.将Python注册到环境变量中去打开windows命令窗口cmd,运行一下命令:C: c:python27python ez_setup.py运行结果如上图,就说明成功了。4.安装pyramid的沙盒环境:virtuallenv。VirtualEnv用于在一台机器上创建多个独立的python运行环境,VirtualEnvWrapper为前者提供了一些便利的命令行上的封装。使用 VirtualEnv 的理由: 隔离项目之间的第三方包依赖,如A项目依赖django1.2.5,B项目依赖django1.3。为部署应用提供方便,把开发环境的虚拟环境打包到生产环境即可,不需要在服务器上再折腾一翻。“安装过程:在运行:C: c:python27Scriptsvirtualenv -no-site-packages env就会在C盘根目录下生成一个新的folder: env打开这个目录双击active.bat,等他一闪而过后运行: c: cd env运行:c:env Scriptseasy_install pyramid用pyramid创建一个完整的WEB Project撰写于 2012-06-12 分类: python 标签: python pyramid 概要:最近公司开展新项目,依然用的是 pyramid ,只是数据库从 mongoDB 改为 mySQL ,这个 project 差不多是我自己来完成的,总结了一下创建项目的基本步骤,算是比较完整的,分享一下。之前公司用pyramid做开发,那时候刚开始学习,有很多不懂,都是别人定义好的,我只是拿来用,所以一些原理不是太清楚。最近公司开展新项目,依然用的是pyramid,只是数据库从mongoDB改为mySQL,这个project差不多是我自己来完成的,总结了一下步骤。一、创建一个pyramid project我的开发环境:WIN7 32bit + python 2.6.6 + mysql 5.5.20 + mongodb 2.0.3在项目目录下执行:pcreate -s starter myproject这个命令应该很熟悉了吧,pcreate是装了pyramid之后在python/Scripts/目录生成的一个可执行文件,通常把python/Scripts/加入到系统环境变量以方便使用。然后,以develop的方式来run我们的项目,production.ini则是生产环境(线上)的配置文件:python setup.py develop如果项目多人参与开发,那么每个人都可以拷贝一份development.ini根据当前开发环境来配置,然后以此来run项目:pserve development.ini -reloadreload参数说明:当修改项目下的.py文件或者配置文件后pserve自动重启,方便开发调试。二、配置development.ini你可以在这里设置一些配置,比如mysql的主机、用户名、密码,debug是否开启,如:; For mysqlmysql.host = localhostmysql.port = 3306mysql.user = rootmysql.passwd = rootmysql.db = myprojectmysql.charset = utf8引用的时候可以这样写:settingsmysql.host数据库的连接状态我们肯定想一直保持,要不然每次都要connect一下很麻烦,所以可以在myproject/_init_.py里面把db_connect放在request里面,方便调用:import pymysqlfrom pyramid.config import Configuratorfrom pyramid.events import NewRequestdef main(global_config, *settings): config = Configurator(settings=settings) # connect mysql def add_mysql_db(event): db_host = settingsmysql.host db_port = int(settingsmysql.port) db_user = settingsmysql.user db_pass = settingsmysql.passwd db_name = settingsmysql.db db_charset = settingsmysql.charset conn = pymysql.connect(host = db_host, port = db_port, user = db_user, passwd = db_pass, db = db_name, charset = db_charset) event.request.db = conn.cursor() config.add_subscriber(add_mysql_db, NewRequest)三、route & view在上面那个_init_.py里面有一个home的route,可以看到写法。route和view是成对出现的,项目里面的route很多,如果都写在这不方便管理,所以我们新建一个文件专门存放route,view不必非要紧挨着route,仔细看配置文件会发现config.scan(),他会帮我们快速配对route和view,通常config.scan(myproject),应该很容易理解吧(myproject相当于一个package)。route的写法可以查看pyramid文档,就不在此啰嗦了,后面我把一个完整的配置文件共享出来。四、renderer一个html模板pyramid默认使用Chameleon模板引擎,支持.pt后缀的模板文件。我们常用.html,那么就选用另外一个模板引擎Mako,使用时要配置一下,很简单,在上面那个_init_.py的main()函数里加上:config.add_renderer(.html, pyramid.mako_templating.renderer_factory)在development.ini文件里制定mako模板路径:; For Mako Templatemako.directories = myproject:templatesmako.strict_undefined = true五、session factory关于session,一般设定方式如下:import pyramid_beaker# set session factorysession_factory = pyramid_beaker.session_factory_from_settings (settings)config.set_session_factory (session_factory)pyramid_beaker.set_cache_regions_from_settings (settings)也要在development.ini设置一下:; For pyramid_beakersession.type = filesession.data_dir = %(here)s/data/sessions/datasession.lock_dir = %(here)s/data/sessions/locksession.key = myproject_sessionsession.cookie_on_exception = true;cache.regions = default_term, second, short_term, long_term;cache.type = memory;cache.second.expire = 1;cache.short_term.expire = 60;cache.default_term.expire = 300;cache.long_term.expire = 3600分号是注释作用。用的话直接在request.session里面取:request.session.get(username)六、权限系统这个有点小复杂,可以看手册里面security和resources。资源-权限-角色-用户这个思路,理解起来就是赋予用户某些角色,然后是对资源授权,注意:权限是角色固有的,而非和用户绑定在一起,以后有时间好好分享一下。以上六步算是比较完整的了。development.ini配置较简单,下面是myproject/_init_.py的配置:import pymysql,pymongoimport pyramid_beakerfrom pyramid.config import Configuratorfrom pyramid.events import NewRequestfrom urls import add_web_routedef main(global_config, *settings): This function returns a Pyramid WSGI application. config = Configurator(settings=settings) config.add_static_view(static, myproject:static, cache_max_age=3600) # set session factory session_factory = pyramid_beaker.session_factory_from_settings (settings) config.set_session_factory (session_factory) pyramid_beaker.set_cache_regions_from_settings (settings) # render a html template config.add_renderer(.pt, pyramid.mako_templating.renderer_factory) config.add_renderer(.html, pyramid.mako_templating.renderer_factory) # MongoDB def add_mongo_db(event): settings = event.request.registry.settings db = pymongo.Connection(settingsmongodb.url)settingsmongodb.db_name event.request.mongo_db = db config.add_subscriber(add_mongo_db, NewRequest) # connect mysql def add_mysql_db(event): db_host = settingsmysql.host db_port = int(settingsmysql.port) db_user = settingsmysql.user db_pass = settingsmysql.passwd db_name = settingsmysql.db db_charset = settingsmysql.charset conn = pymysql.connect(host = db_host, port = db_port, user = db_user, passwd = db_pass, db = db_name, charset = db_charset) event.request.db = conn.cursor() config.add_subscriber(add_mysql_db, NewRequest) # config.add_route(home, /) # add route add_web_route(config) config.scan(myproject) return config.make_wsgi_app()下面是myproject/urls.py:# -*- coding: utf-8 -*-_author_ = luchanghongdef add_web_route(config): # web common config.add_route (name = web.index, pattern = /)下面是development.ini:app:mainuse = egg:myprojectpyramid.reload_templates = truepyramid.debug_authorization = falsepyramid.debug_notfound = falsepyramid.debug_routematch = falsepyramid.default_locale_name = en; pyramid.includes = pyramid_debugtoolbar; For pyramid_beakersession.type = filesession.data_dir = %(here)s/data/sessions/datasession.lock_dir = %(here)s/data/sessions/locksession.key = myproject_sessionsession.cookie_on_exception = true;cache.regions = default_term, second, short_term, long_term;cache.type = memory;cache.second.expire = 1;cache.short_term.expire = 60;cache.default_term.expire = 300;cache.long_term.expire = 3600; For Mako Templatemako.directories = myproject:templatesmako.strict_undefined = true; For Mongomongodb.url = mongodb:/mongodb.db_name = myproject; For mysqlmysql.host = localhostmysql.port = 3306mysql.user = rootmysql.passwd = rootmysql.db = myprojectmysql.charset = utf8server:mainuse = egg:waitress#mainhost = port = 6543# Begin logging configurationloggerskeys = root, myprojecthandlerskeys = consoleformatterskeys = genericlogger_rootlevel = INFOhandlers = consolelogger_myprojectlevel = DEBUGhandlers =qualname = myprojecthandler_consoleclass = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = genericformatter_genericformat = %(asctime)s %(levelname)-5.5s %(name)s%(threadName)s %(message)s# End logging configuration注意我的项目名称是:myprojectPyramid中的安全权限策略细说Authentication和Authorization撰写于 2013-05-16 分类: python 标签: python pyramid security authentication authorization 概要:安全和权限策略是Pyramid中一个重要的组成部分,主要分为authentication(认证)和authorization(授权)两个部分。安全策略Pyramid提供一个可选的声明式的授权系统,当一个view被调用的时候,可以根据request里面的权限凭证和上下文去决定授权与否。下面看官方文档里关于工作流程的描述: A request is generated when a user visits the application. Based on the request, a context resource is located through resource location. A context is located differently depending on whether the application uses traversal or URL dispatch, but a context is ultimately found in either case. See the URL Dispatch chapter for more information. A view callable is located by view lookup using the context as well as other attributes of the request. If an authentication policy is in effect, it is passed the request; it returns some number of principal identifiers. If an authorization policy is in effect and the view configuration associated with the view callable that was found has a permission associated with it, the authorization policy is passed the context, some number of principal identifiers returned by the authentication policy, and the permission associated with the view; it will allow or deny access. If the authorization policy allows access, the view callable is invoked. If the authorization policy denies access, the view callable is not invoked; instead the forbidden view is invoked.Pyramid的安全策略明确的分为 认证 和 授权 两个部分。认证过程可以理解为包含在一个request中的权限凭证转换成一个或者多个principal标识符的机制。这些标识符实际上在request过程中代表用户和用户组。授权取决于这些标识符、被调用的view视图和上下文资源。使用认证和授权策略下面还是以lbew项目为例说明。 首先在_init_.py中添加一些配置: # use authentication and authorization from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from lbew.security import groupfinder authn_policy = AuthTktAuthenticationPolicy(hereseekrit, callback = groupfinder, hashalg = sha512) authz_policy = ACLAuthorizationPolicy() config = Configurator(settings = settings, root_factory = lbew.resources.RootFactory, authentication_policy = authn_policy, authorization_policy = authz_policy) # 也可以用下面的配置方式 config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy)AuthTktAuthenticationPolicy有很多参数,这里使用callback和hashalg,剩下的可以参考官方文档。 新建lbew/resources.py,然后code: _author_ = luchanghong #!/usr/bin/env python #-*- coding: utf8 -*- from pyramid.security import Allow, Deny, Everyone class RootFactory(object): _acl_ = (Allow, Everyone, view), (Allow, group:viewers, view2), (Allow, group:editors, edit) def _init_(self, request): pass在_init_.py中已经指定root_factory = lbew.resources.RootFactory,否则是系统default root_factory。 新建lbew/security.py,然后code: _author_ = luchanghong #!/usr/bin/env python #-*- coding: utf8 -*- USERS = editor:editor, viewer:viewer GROUPS = editor:group:editors, viewer:group:viewers def groupfinder(userid, request): if userid in USERS: return GROUPS.get(userid, )这就是为了callback使用,如果没有callback函数,那么principal只能是everyone。没有接触过Pyramid的朋友可能在这一块很迷茫,事已至此,我们主要解决两个问题: view视图如何设置上权限? 授权到底是怎样的过程?在这之前还要了解一下ACL和ACE的概念。 ACE(Access Control Entry)是单一的权限控制入口,这个元组一般组成形式是(允许/拒绝,用户/用户组,操作/(操作1,操作2,);而ACL(Access Control List)就是多个ACE组成的一个列表。下面是官方文档中的一个例子:from pyramid.security import Everyonefrom pyramid.security import Allow_acl_ = (Allow, Everyone, view), (Allow, group:editors, add), (Allow, group:editors, edit), 更多的资料参考官方文档。为view视图添加permission首先打开授权调试工具,在配置文件development.ini中把pyramid.debug_authorization设为true(line 10):app:mainuse = egg:lbewpyramid.reload_templates = truepyramid.debug_authorization = true下面的例子以之前项目为例。打开lbew/views/account.py,然后code:_author_ = luchanghong#!/usr/bin/env python#-*- coding: utf8 -*-from pyramid.view import view_configclass Account(object): def _init_(self, context, request): self.request = request self.context = context # everyone can visit view_config(route_name = signup, renderer = string) def signup(self): print self.context return welcome to signup.打开浏览器访问:6543/account/signup看到相应输出,然后看一下调试信息:Starting server in PID 16407.serving on :65432013-05-16 17:49:48,495 DEBUG lbewDummy-2 debug_authorization of url :6543/account/signup (view name u against context ): Allowed (no permission registered)从调试信息可以看到现在没有permission注册,而且context关联的是在_init_.py中设置的lbew.resources.RootFactory,否则就是默认的。这里我们就来解决上面说的第一个问题:view和factory关联以及设置permission。在配置route的时候可以指定使用的factory,然后找到context:# lbew/routes.pyconfig.add_route(name = signup, pattern = /account/signup, factory = lbew.resources.RootFactory)指定factory参数之后,就会忽略_init_.py里root_factory的设置。然后为view添加permission:view_config(route_name = signup, renderer = string, permission = view)def signup(self): print self.context return welcome to signup.此时重启pserve,刷新上个页面看一下调试信息(先不管favicon.ico相关信息):2013-05-16 18:19:43,033 DEBUG lbewDummy-4 debug_authorization of url :6543/account/signup (view name u against context ): ACLAllowed permission view via ACE (Allow, system.Everyone, view) in ACL (Allow, system.Everyone, view), (Allow, group:viewers, view2), (Allow, group:editors, edit) on context for principals system.Everyone可以看出此时用户的principals是system.Everyone,而RootFactory中允许view操作的是(Allow, system.Everyone, view),所以可以成功授权。为了验证,我们做个修改:# lbew/resources.pyclass RootFactory(object): _acl_ = (Allow, luchanghong, view), (Allow, group:viewers, view2), (Allow, group:editors, edit) def _init_(self, request): pass再次调试会发现出现403 forbidden,调试信息:2013-05-16 18:27:06,604 DEBUG lbewDummy-3 debug_authorization of url :6543/account/signup (view name u against context ): ACLDenied permission view via ACE in ACL (Allow, luchanghong, view), (Allow, group:viewers, view2), (Allow, group:editors, edit) on context for principals system.Everyone由于我设置只有luchanghong才能有view的权限,所以目前无权限访问。总结这一块涉及的比较多,所以写的时候感觉无从下手,关键是要理解。现在解决第二个问题,个人总结如下: 根据route指定的factory去获取context以及ACL | 根据request的url找到对应的route 如果没有permission则意味着没有权限限制,任何人都能访问 | | | | 根据route_name找到对应的view视图并获取permission 浏览器发起request | | 如果有permission则根据此 + 当前的principals + ACL去授权 | |默认的principals是system.Everyone 根据request获取principals |通过登陆获取userid以及user group,增加principals的值有时间来写一下如何通过userid获取user一些信息并添加到principals,以及用户退出后重置principals。在Pyramid中使用SESSION撰写于 2013-05-14 分类: python 标签: python pyramid session 概要:伴随项目的开发,需要使用SESSION来保存用户产生的数据。SEESION in Pyramid安装官网上SESSION文档的描述,一般有两种SESSION Factory和两种关于SESSION的用法。默认的SESSION Factory在_init_.py中添加一些代码:from pyramid.session import UnencryptedCookieSessionFactoryConfigmy_session_factory = UnencryptedCookieSessionFactoryConfig(itsaseekreet)from pyramid.config import Configuratorconfig = Configurator(session_factory = my_session_factory)# 上面一行代码也等价于下面config.set_session_factory(my_session_factory)pyramid_beakerpyramid_beaker文档参见官网。首先要安装pyramid_beaker这个package,可以在setup.py中添加需要的包,然后执行下面# 编辑setup.pyrequires = pyramid, SQLAlchemy, transaction, pyramid_tm, pyramid_debugtoolbar, zope.sqlalchemy, waitress, mako, pyramid_beaker, # 执行程序python setup.py develop有以下三种使用方法: 在项目配置文件如develop.ini中添加一个配置 pyramid.includes = pyramid_debugtoolbar pyramid_tm pyramid_beaker 在_init_.py添加一行: config.include(pyramid_beaker) 在develop.ini里添加配置 # # pyramid_beaker # session.type = file session.data_dir = %(here)s/data/sessions/data session.lock_dir = %(here)s/data/sessions/lock # key和secert都是自定义的 session.key = key_lbew session.secret = secret_lbew_webl session.cookie_on_exception = true然后在_init_.py里的main函数中添加几行配置:# use sessionfrom pyramid_beaker import session_factory_from_settingssession_factory = session_factory_from_settings(settings)config.set_session_factory(session_factory)SESSION存储调用写个测试页面,在views/account.py中code:_author_ = luchanghong#!/usr/bin/env python#-*- coding: utf8 -*-from pyramid.view import view_configclass Account(object): def _init_(self, request): self.request = request print self.request.session, self.request.session.get(aaa, None), self.request.session.created view_config(route_name = signup, renderer = string) def signup(self): self.request.sessionaaa = bbb return Welcome to register.查看输出结果:Starting server in PID 11688.serving on :6543aaa: bbb, _accessed_time: 1368526206.591521, _creation_time: 1368514712.58489 bbb 1368514712.58可以看出SESSION操作就和字典一样。CSRF TOKEN为了防止恶意表单提交,可以使用SESSION生成一个CSRF TOKEN,在处理表单数据之前做校验:# 把csrf_token传到页面里做一个隐藏字

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论