python aiohttp post 的使用

本文详细介绍了如何使用Python的aiohttp库进行HTTP POST请求,包括设置请求头、发送JSON数据等关键步骤,适合Python异步网络编程的学习者参考。
# -*- coding: utf-8 -*-
import datetime, os, sys
import time
import datetime
import socket
import grequests
import json
import asyncio
from aiohttp import ClientSession
tasks = []
tasksResult=[]
a = time.time()
async def request_run(i, semaphore):
    async with semaphore:
        async with ClientSession() as session:
            parameter={"ServiceList":"INTERNET","Host":"www.baidu.com","DataBlockSize":64,"NumberOfRepet":5,"Timeout":1000}
            tmp={}
            tmp=parameter
            tmp["Username"]=i
            url='http://192.168.1.6:8190/public/test/testing/ping'
            async with session.post(url, data=json.dumps(tmp)) as resp:
                #response = await resp.read()
                response = await resp.json()
                print("req")
                print(response)
                reqResult={}
                reqResult["Username"]=i
                reqResult["reqresult"]=response
                tasks.append(reqResult)

async def getResult_run(i, semaphore):
    async with semaphore:
        async with ClientSession() as session:
            tmp={}
            tmp["Username"]=i
            url='http://192.168.1.6:8190/public/test/testing/ping/getpinginfo'
            async with session.post(url, data=json.dumps(tmp)) as resp:
                response = await resp.json()
                print("result")
                print(response)
                reqResult={}
                reqResult["Username"]=i
                reqResult["result"]=response
                tasksResult.append(reqResult)


async def run_req(userAccountList):
    numlist=userAccountList.split(",");
    semaphore = asyncio.Semaphore(100)
    to_get = [request_run(i, semaphore) for i in numlist]  
    await asyncio.wait(to_get)


async def run_get(userAccountList):
    numlist=userAccountList.split(",");
    semaphore = asyncio.Semaphore(100)

    to_getResult = [getResult_run(i, semaphore) for i in numlist]  
    await asyncio.wait(to_getResult)


if __name__ == "__main__":
    while True:
        userAccountList=''
        if len(sys.argv) >1 :
            userAccountList = sys.argv[1]
        loop = asyncio.get_event_loop()
        loop.run_until_complete(run_req(userAccountList))
        #loop.run_until_complete(run_req(userAccountList))
        loop.close()
        print("req")
        print(tasks)
        print("result")

        print(tasksResult)
        b = time.time()
        print(b-a)
        break;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值