要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

登录--异步发请求--退出

import asyncio
import aiohttp


async def GET_CAPTCHA_JPG(session):
    """
    获取验证码图片,并保存在本地
    """
    async with session.get(url="http://192.168.112.150/api/v1.0/auth/sso/login/kaptcha",
                           params={"time": "null"}) as resp:
        with open(file="CAPTCHA.jpg", mode="wb") as fd:
            while True:
                chunk = await resp.content.read(1024)
                if not chunk:
                    break
                fd.write(chunk)


async def login(session):
    """
    登录系统
    验证码输入CAPTCHA.jpg的内容
    """
    await GET_CAPTCHA_JPG(session)
    print("请输入验证码:", end="")
    captcha = input()
    url = "http://192.168.112.150/api/v1.0/auth/sso/login"
    data = {
        "imgCaptcha": captcha,
        "password": "1234abcd",
        "username": "wangyangzhi"
    }
    # 登录
    async with session.post(url=url, json=data) as resp:
        ret = await resp.json()
        print("登录: ", ret["message"])


async def logout(session):
    """
    退出系统
    """
    url = "http://192.168.112.150/api/v1.0/auth/sso/logout"
    # 退出
    async with session.post(url=url) as resp:
        ret = await resp.json()
        print("退出: ", ret["message"])


async def get_info1(session):
    """
    业务代码1
    """
    async with session.get(url="http://192.168.112.150/api/v1.0/manage/user/getcreat") as resp:
        ret = await resp.json()
        return ret


async def get_info2(session):
    """
    业务代码2
    """
    async with session.get(url="http://192.168.112.150/api/v1.0/manage/user/roles") as resp:
        ret = await resp.json()
        return ret


async def main():
    """登录系统,同步"""
    # 如果要接受来自IP的cookie,需要加unsafe=True
    session = aiohttp.ClientSession(cookie_jar=aiohttp.cookiejar.CookieJar(unsafe=True))
    await login(session)

    """业务代码,异步"""
    result = await asyncio.gather(get_info1(session), get_info2(session))
    print("所有异步请求结果: ", result)

    """退出系统,同步"""
    await logout(session)
    await session.close()


asyncio.run(main())

 

posted on 2021-10-20 10:44  要一直走下去  阅读(167)  评论(0编辑  收藏  举报