python小技巧大应用--用aiohttp实现HTTP C/S收发JSON数据

用了两天时间,查找资料,不断的测试,终于实现想要的小应用.通过aiohttp实现的C/S架构的收发JSON数据的应用

前文实测基础,请参考:python小技巧大应用--实测aiohttp可正常运行的写法

在此直接上代码,希望与大家分享结果

1)服务端模块test_aiohttp_HTTPServer.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test aiohttp server '

__author__ = 'TianJiang Gui'

import asyncio
from aiohttp import web

async def index(request):
    await asyncio.sleep(0.5)
    return web.Response(body=b'

Index

' , content_type='text/html') async def get_json(request): data = await request.json() name = data["name"] print('请求get的信息data为: %s' % str(data)) try: return web.json_response({'code': 0, 'data': name}) except Exception as e: return web.json_response({'msg': e.value}, status=500) async def post_json(request): # put或者post方式参数获取 data = await request.json() name = data["name"] print('请求post的信息data为: %s' % str(data)) try: return web.json_response({'code': 0, 'data': name}) except Exception as e: return web.json_response({'msg': e.value}, status=500) if __name__ == '__main__': app = web.Application() app.add_routes([web.get('/', index), web.get('/getjson', get_json), web.post('/postjson', post_json)]) web.run_app(app,host='127.0.0.1',port=8100)

2)客户端模块test_aiohttp_HTTPClient.py,用于测试

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test aiohttp HTTPClient '

__author__ = 'TianJiang Gui'

import aiohttp
import asyncio

async def get_json(session,url):
    # 传输json格式的数据
    headers = {'content-type': 'application/json'}
    params = {'name': 'TianJiang Gui', 'age': '44'}
    async with session.get(url, json=params, headers=headers) as response:
        r = await response.json(content_type=None)
    return r

async def post_json(session,url):
    # 传输json格式的数据
    headers = {'content-type': 'application/json'}
    params = {'name': '桂天江', 'age': '33'}
    async with session.post(url, json=params, headers=headers) as response:
        r = await response.json(content_type=None)
    return r

async def main():
    async with aiohttp.ClientSession() as session:
        response_json = await get_json(session, 'http://127.0.0.1:8100/getjson')
        print("通过get_json返回的数据:",response_json)

        response_json = await post_json(session, 'http://127.0.0.1:8100/postjson')
        print("通过post_json返回的数据:",response_json)
        await session.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

运行结果如下:服务端运行结果

python小技巧大应用--用aiohttp实现HTTP C/S收发JSON数据_第1张图片

客户端运行结果:

python小技巧大应用--用aiohttp实现HTTP C/S收发JSON数据_第2张图片

总结:希望我所付出的劳动能帮到大家,也请大家多多支持(一键三连:点赞,收藏,打赏:)

你可能感兴趣的:(python,http,c语言)