Использование cherrypy в двух модулях, но только с одним экземпляром cherrypy - PullRequest
1 голос
/ 03 апреля 2012

Я использую cherrypy для проекта и использую его в основном скрипте на python main.py В методе основного приложения я импортирую модуль под названием аутентификация

from authentication import auth и затем передайте ему переменную args. вишня использовалась здесь уже, очевидно,

@cherrypy.expose
def auth(self, *args):
    from authentication import auth
    auth = auth()

    page = common.header('Log in')

    authString = auth.login(*args)

    if authString:
        page += common.barMsg('Logged in succesfully', 1)
        page += authString
    else:
        page += common.barMsg('Authentication failed', 0)

    page += common.footer()

    return page

Из файла authentic.py я хочу установить переменные сеанса, чтобы я снова включил cherrypy

def login(self, *args):
    output = "<b>&quot;args&quot; has %d variables</b><br/>\n" % len(args)

    if cherrypy.request.body_params is None:
        output += """<form action="/auth/login" method="post" name="login">
            <input type="text" maxlength="255" name="username"/>
            <input type="password" maxlength="255" name="password"/>
            <input type="submit" value="Log In"></input>
        </form>"""
        output += common.barMsg('Not a member yet? Join me <a href="/auth/join">here</a>', 8)

    return output

Проблема заключается в ошибке HTTPError: (400, 'Unexpected body parameters: username, password'), когда я использую это. Я хочу, чтобы экземпляр cherrypy из main.py был доступен в authentication.py для установки переменных сеанса здесь. Как я могу это сделать?

Я также попытался передать объект cherrypy следующим образом authString = auth.login(cherrypy, *args) и пропустил его включение в authentication.py, однако получил ту же ошибку

1 Ответ

1 голос
/ 03 апреля 2012

Извините, что отвечаю на этот вопрос так быстро, но небольшое исследование показывает, что аргумент ** kwargs, опущенный в методе auth, приводит к тому, что cherry_parameters будет отклонен cherrypy, поскольку он не ожидал их.Чтобы это исправить:

main.py

@cherrypy.expose
def auth(self, *args, **kwargs):
    from authentication import auth
    auth = auth()

    page = common.header('Log in')

    authString = auth.login(cherrypy, args)

    if authString:
        page += common.barMsg('Logged in succesfully', 1)
        page += authString
    else:
        page += common.barMsg('Authentication failed', 0)

    page += common.footer()

    return page

authentication.py

def login(self, cherrypy, args):
    output = "<b>&quot;args&quot; has %d variables</b><br/>\n" % len(args)

    if cherrypy.request.body_params is None:
        output += """<form action="/auth/login" method="post" name="login">
            <input type="text" maxlength="255" name="username"/>
            <input type="password" maxlength="255" name="password"/>
            <input type="submit" value="Log In"></input>
        </form>"""
        output += common.barMsg('Not a member yet? Join me <a         href="/auth/join">here</a>', 8)

    return output
...