异常处理

  • use_ex_handle: 是否使用异常处理
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from school_api import SchoolClient
from school_api.exceptions import SchoolException, LoginException, IdentityException

# 将use_ex_handle 设置为False时,模块将抛出异常信息。
school = SchoolClient('http://210.38.137.126:8016', use_ex_handle=False)


# 异常处理装饰器
def service_resp():
    def decorator(func):
        def warpper(*args, **kwargs):
            try:
                client = school.user_login(*args, **kwargs)
                data = func(client)
            except IdentityException as reqe:
                # 账号密码错误
                return {'error': reqe}
            except LoginException as reqe:
                # 登录失败 (包含以上错误)
                return {'error': reqe}
            except SchoolException as reqe:
                # 请求失败 (包含以上错误)
                return {'error': reqe}
            except Exception:
                # 模块报错 (包含以上错误)
                return {'error': '教务请求失败'}
            else:
                # 数据处理 (如:缓存)
                return data

        return warpper
    return decorator


@service_resp()
def bind_account(user):
    # 绑定用户,并保存用户信息
    return user.get_info()


@service_resp()
def get_schedule(user):
    # 获取课表
    return user.get_schedule()


@service_resp()
def get_score(user):
    # 获取成绩
    return user.get_score()


if __name__ == '__main__':
    account = 'user'
    password = 'password'
    data = bind_account(account, password, use_cookie_login=False)
    print(data)

results matching ""

    No results matching ""