python并发_python中的并发执行

def_user_batch_import(self, q, account_id):from flask importrequestfrom app.api.apis importimport_user_phone, import_user_birthdate

failure_list= list() #所有错误结果的数据

failure_dict = dict() #unique_id错误的字典

success = list() #所有正确结果的数据

wrong_format = list() #所有格式错误的数据

res_dic = dict() #return返回的数据

#headers_token = request.headers["Authorization"] if 'Authorization' in request.headers and len(

#request.headers["Authorization"].split(" ")) == 2 else ''

headers_token =AccessToken

header= {"Authorization": "Bearer %s" %headers_token}

request_query=[]while q.qsize() >0:

query=q.get()#res_phone = impot_user_phone(query["pseudonym[unique_id]"])

res_phone = import_user_phone(query["pseudonym[unique_id]"])

res_birthdate= import_user_birthdate(query["user[birthdate]"])#res_password = impot_user_password(query["pseudonym[password]"])

#res_id_card = import_user_id_card(query["user[id_card]"])

#if res_id_card in ["", None]:

#res_user_id_card_num = 0

#else:

#res_user_id_card_num = User.query.filter(User.id_card == query["user[id_card]"], User.workflow_state != "deleted").count()

#if isinstance(res_phone, dict) or isinstance(res_password, dict) or isinstance(res_id_card, dict) or res_user_id_card_num != 0:

#if isinstance(res_phone, dict) or isinstance(res_id_card, dict) or res_user_id_card_num != 0:

if isinstance(res_phone, dict) orisinstance(res_birthdate, dict):

wrong_format.append(query["pseudonym[unique_id]"])

query["errcode"] = 1

if "errcode" not inquery.keys():

request_query.append(query)#将loop对象设置为全局对象

loop =asyncio.new_event_loop()

asyncio.set_event_loop(loop)

canvas_url= API_CANVAS_HOST + '/api/v1/accounts/{account_id}/users'.format(account_id=account_id)

results=loop.run_until_complete(self.url_res(canvas_url, header, request_query))#关闭loop对象

loop.close()print("results----------------")print(results)for result inresults:print(result)print(result.json())if result.status_code == 403:return {"errcode": 400, "errmsg": u"无此权限"}

res_json=result.json()if "errors" inres_json.keys():try:

failure_dict["phone"] = res_json["errors"]["unique_id"]

failure_dict["message"] = res_json["errors"]["pseudonym"]["unique_id"][0]["message"]

failure_list.append(failure_dict.copy())exceptException as e:

failure_list.append({"canvas_errors": res_json, "errmsg_e": str(e)})else:

success.append(res_json["login_id"])

res_dic["wrong_format"] =wrong_format

res_dic["success_event"] =success

res_dic["failure_event"] =failure_listreturn {"errcode": 0, "errmsg": "ok", "data": res_dic}#if len(res_dic["wrong_format"]) == 0 and len(res_dic["failure_event"]) == 0:

#return {"errcode": 0, "errmsg": "ok"}

#else:

#return {"errcode": 400, "errmsg": "failure", "data": res_dic}

asyncdefdo_some_work(self, url, header, query):return requests.post(url, headers=header, data=query)

asyncdefurl_res(self, url, header, request_query):

tasks=[]for query inrequest_query:

coroutine=self.do_some_work(url, header, query)

temp=asyncio.ensure_future(coroutine)

tasks.append(temp)return await asyncio.gather(*tasks)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
gRPC 是一种高性能、开源的 RPC 框架,支持多种编程语言。在 Python ,我们可以使用 gRPC 提供远程过程调用服务。 以下是在 Python 使用 gRPC 的基本步骤: 1. 安装 gRPC:使用 pip install grpcio 命令安装 gRPC。 2. 定义服务和消息:使用 proto3 编写 .proto 文件,定义服务和消息。 3. 生成代码:使用 protoc 命令生成 Python 代码。 4. 实现服务:在 Python 实现服务端和客户端。 5. 启动服务:启动服务端程序。 6. 调用服务:在客户端程序调用远程服务。 以下是一个简单的示例,演示如何在 Python 使用 gRPC: 1. 定义服务和消息 ```protobuf syntax = "proto3"; package helloworld; // 定义消息 message HelloRequest { string name = 1; } message HelloReply { string message = 1; } // 定义服务 service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } ``` 2. 生成代码 使用以下命令生成 Python 代码: ```bash python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto ``` 3. 实现服务 在 Python 实现服务端和客户端。 ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': serve() ``` ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='world')) print("Greeter client received: " + response.message) if __name__ == '__main__': run() ``` 4. 启动服务 在终端运行以下命令启动服务: ```bash python greeter_server.py ``` 5. 调用服务 在终端运行以下命令调用服务: ```bash python greeter_client.py ``` 以上是在 Python 使用 gRPC 的基本步骤。在生产环境,我们需要考虑更多的实现细节,例如错误处理、认证和安全等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值