Найти - Пользователи
Полная версия: BaseController
Начало » Pyramid / Pylons / TurboGears » BaseController
1
dorian
Доброго времени суток. Наследуюсь от базового контроллера:

class SbeBaseController(BaseController):
def __call__(self, environ, start_response):
“”“Invoke the Controller”“”
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ
try:
return WSGIController.__call__(self, environ, start_response)
finally:
if (session.has_key('USER') and not session.a_IsLogged) or not session.has_key('USER'): redirect_to('login')

Получаю ошибку последней строки:
<class ‘paste.httpexceptions.HTTPFound’>: 302 Found The resource was found at login
В чем трабла?
j2a
Зацикленный редирект?
dorian
Нет не зацикленый. Потому как контроллер на который редиректится наследуется от стандартного базового котнтроллера
j2a
config/middleware.py не трогал? версия pylons шаблона и текущая версия pylons совпадают?
dorian
Нет не трогал. Все в первоначальном виде. Pylons ставил раз поэтому версии совпадают.
j2a
Информации мало. Воспроизведи ошибку в тестовом приложении, выложи куда-нибудь, посмотрим.
dorian
Итак имеем base.py
"""The base Controller API

Provides the BaseController class for subclassing, and other objects
utilized by Controllers.
"""
from pylons import c, cache, config, g, request, response, session
from pylons.controllers import WSGIController
from pylons.controllers.util import abort, etag_cache, redirect_to
from pylons.decorators import jsonify, validate
from pylons.i18n import _, ungettext, N_
from pylons.templating import render

import sbe.lib.helpers as h
import sbe.model as model

class BaseController(WSGIController):

def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
return WSGIController.__call__(self, environ, start_response)


class SbeBaseController(BaseController):
def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
try:
return WSGIController.__call__(self, environ, start_response)
finally:
if (session.has_key('USER') and not session['USER'].a_IsLogged) or not session.has_key('USER'): redirect_to('login')

# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
or __name == '_']
Один из контроллеров наследуем от стандартного BaseController login.py
#-*- coding: utf-8 -*-
import logging

from sbe.lib.base import *
from pylons.i18n import get_lang, set_lang
from sbe.lib import auth

log = logging.getLogger(__name__)

class LoginController(BaseController):

def index(self):
c.loginarea_title = _('Login into Administration')
c.login_title = _('User Name')
c.password_title = _('Password')
c.error_message = list()
c.submit_btn_value = _('Login')
if len(request.POST):
if not auth.User().CheckUser(request.POST['login'], request.POST['password']):
c.error_message.append(_('Invalid Username or Password.'))
else:
redirect_to('admin')
return render('/auth/auth.mako')
Все доугие контроллеры наследуем от SbeBaseController, который редиректит на описный выше контроллер в случае если пользователь не авторизован admin.py
import logging
from sbe.lib.base import *

log = logging.getLogger(__name__)

class AdminController(SbeBaseController):

def index(self):
return render('/layouts/main_layout.mako')
пытаемся ломануться без авторизации сразу на http://localhost:5000/admin (по задумке должен произойти редирект на login.py) но получаем ошибку:
URL: http://localhost:5000/admin
Module pylons.error:245 in respond
<< try:
__traceback_supplement__ = Supplement, self, environ
app_iter = self.application(environ, detect_start_response)
try:
return_iter = list(app_iter)>> app_iter = self.application(environ, detect_start_response)
Module pylons.wsgiapp:315 in __call__
<< def __call__(self, environ, start_response):
environ['pylons.environ_config'] = self.econf
return self.app(environ, start_response)>> return self.app(environ, start_response)
Module beaker.cache:180 in __call__
<< environ['paste.registry'].register(self.cache, self.cache_manager)
environ[self.environ_key] = self.cache_manager
return self.app(environ, start_response)>> return self.app(environ, start_response)
Module beaker.session:405 in __call__
<< return start_response(status, headers, exc_info)
try:
response = self.wrap_app(environ, session_start_response)
except:
ty, val = sys.exc_info()[:2]>> response = self.wrap_app(environ, session_start_response)
Module routes.middleware:104 in __call__
<< environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1]

response = self.app(environ, start_response)
del config.environ
del self.mapper.environ>> response = self.app(environ, start_response)
Module pylons.wsgiapp:95 in __call__
<<
controller = self.resolve(environ, start_response)
response = self.dispatch(controller, environ, start_response)

if 'paste.testing_variables' in environ and hasattr(response,>> response = self.dispatch(controller, environ, start_response)
Module pylons.wsgiapp:237 in dispatch
<< if log_debug:
log.debug("Calling controller class with WSGI interface")
return controller(environ, start_response)

def load_test_env(self, environ):>> return controller(environ, start_response)
Module sbe.lib.base:35 in __call__
<< return WSGIController.__call__(self, environ, start_response)
finally:
if (session.has_key('USER') and not session['USER'].a_IsLogged) or not session.has_key('USER'): redirect_to('login')

# Include the '_' function in the public names>> if (session.has_key('USER') and not session['USER'].a_IsLogged) or not session.has_key('USER'): redirect_to('login')
Module pylons.controllers.util:92 in redirect_to
<< for c in response.cookies.values():
found.headers.add('Set-Cookie', c.output(header=''))
raise found>> raise found
<class 'paste.httpexceptions.HTTPFound'>: 302 Found The resource was found at login
ума не приложу как это понять
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB