コード例 #1
0
def route_login(request):
    headers = {
        'Content-Type': 'text/html',
    }
    log('from route_login --> cookies: ', request.cookies)
    # 由cookie得到的用户实例,可能为None
    u = current_user(request)
    # 若有手动输入账号密码且用POST
    # 2个 if 解决 有没有  和 对不对 的问题。
    if request.method == 'POST':
        form = request.form()
        # 创建一个新的用户实例
        if User.validate_login(form):
            # 设置session_id
            session_id = random_str()
            log("from route_login --> session_id: ", session_id)
            u = User.find_by(username=form.get('username'))
            session[session_id] = u.id
            headers['Set-Cookie'] = 'sid={}'.format(session_id)
            result = '登录成功'
        else:
            result = '用户名或者密码错误'
    else:
        result = '请POST登录'
    body = template('login.html', result=result, username='******')
    # 第一次输入用户名密码并提交{{username}}并不会改变,第一次提交cookie中还没有user字段而current_user需要根据这个判断
    # 但是可以替换,如下代码所示
    if u is not None:
        body = body.replace('游客', u.username)
    header = response_with_headers(headers)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
コード例 #2
0
def route_login(request):
    """
    登录页面的路由函数
    """
    log('login, cookies', request.cookies)
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_login():
            session_id = random_str()
            u = User.find_by(username=u.username)
            s = Session.new(dict(
                session_id=session_id,
                user_id=u.id,
            ))
            s.save()
            log('session', s)
            headers = {
                'Set-Cookie': 'sid={}'.format(session_id)
            }
            # 登录后定向到 /
            return redirect('/', headers)
    # 显示登录页面
    body = template('login.html')
    return http_response(body)
コード例 #3
0
def route_login(request):
    """
    登录页面的路由函数
    """
    log('login, cookies', request.cookies)
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_login():
            session_id = random_str()
            u = User.find_by(username=u.username)
            s = Session.new(dict(
                session_id=session_id,
                user_id=u.id,
            ))
            s.save()
            log('session', s)
            headers = {'Set-Cookie': 'sid={}'.format(session_id)}
            # 登录后定向到 /
            return redirect('/', headers)
        else:
            username = '******'
            result = '用户名或密码不正确'
            body = template('login.html', username=username, result=result)
            return http_response(body)

    # 显示登录页面
    u = current_user(request)
    if u is None:
        username = '******'
        result = '请登录'
    else:
        username = u.username
        result = '登录成功'

    body = template('login.html', username=username, result=result)
    return http_response(body)