我在python金字塔中进行简单的身份验证,这里是security.py,我在做认证部分。
security.py
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from .models.user import User
class MyAuthenticationPolicy(AuthTktAuthenticationPolicy):
def authenticated_userid(self, request):
user = request.user
if user is not None:
return user.id
def get_user(request):
user_id = request.unauthenticated_userid
if user_id is not None:
user = request.dbsession.query(User).get(user_id)
return user
def includeme(config):
settings = config.get_settings()
authn_policy = MyAuthenticationPolicy(
settings['auth.secret'],
hashalg='sha512',
)
config.set_authentication_policy(authn_policy)
config.set_authorization_policy(ACLAuthorizationPolicy())
config.add_request_method(get_user, 'user', reify=True)
该设置被添加到第一次运行的init文件中,并且请求方法也被添加到请求中。
这是我的登录视图文件,其中主要是在检查用户名和密码并编写记住代码和存储用户信息之后,但这部分可能无效。
default.py
@view_config(route_name='auth', match_param='action=in', renderer='string',
request_method='POST')
@view_config(route_name='auth', match_param='action=out', renderer='string')
def sign_in_out(request):
username=request.POST.get('username')
if username:
user=UserService.by_name(username)
if user and user.verify_password(request.POST.get('password')):
headers=remember(request,user.name)
return HTTPFound(location=request.route_url('admin'),headers=headers)
else:
headers=forget(request)
return HTTPFound(location=request.route_url('home'),headers=headers)
验证用户名和密码后,请输入此处。我已经检查过该部分正在工作我正在从上面复制这个
的标题=记住(请求,user.name)
返回HTTPFound(location = request.route_url(' admin'),headers = headers)
管理员路线在文件中呈现admin.jinja2 的 admin.jinja2
welcome {{request.user.name}}
这样做会引发一个错误 的 jinja2.exceptions.UndefinedError
UndefinedError:' pyramid.util.Request object'没有属性'用户'