python中的并发执行
一. Gevent实例
import gevent
import requests
from gevent import monkey
# socket发送请求以后就会进入等待状态,gevent更改了这个机制
# socket.setblocking(False) -->发送请求后就不会等待服务器响应
monkey.patch_all() # 找到内置的socket并更改为gevent自己的东西 def fetch_async(method, url, req_kwargs):
print(method, url, req_kwargs)
response = requests.request(method=method, url=url, **req_kwargs)
print(response.url, response.content) # ##### 发送请求 #####
gevent.joinall([
# 这里spawn是3个任务[实际是3个协程],每个任务都会执行fetch_async函数
gevent.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),
gevent.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),
gevent.spawn(fetch_async, method='get', url='https://github.com/', req_kwargs={}),
])
二. grequests实例
grequests实际上就是封装了gevent里面的方法,然后配合requests实现异步的IO
grequests = gevent + request
grequests.map() 内部实现
import grequests # 实际上就是requests + gevent
request_list = [
# 发送get请求
grequests.get('https://www.baidu.com/', timeout=10.001),
grequests.get('https://www.taobao.com/'),
grequests.get('https://hao.360.cn/')
]
# ##### 执行并获取响应列表 #####
response_list = grequests.map(request_list) # 实际上内部循环执行gevent内部的joinall()方法
print(response_list) # ##### 执行并获取响应列表(处理异常) #####
# def exception_handler(request, exception):
# print(request,exception)
# print("Request failed") # response_list = grequests.map(request_list, exception_handler=exception_handler)
# print(response_list)
三. 项目中的应用
def user_batch_import(self, token, file, data):
v = self._user_role(token, {})
if "errcode" in v.keys():
return v if 'user[college_id]' not in v:
return {"errcode": 2, "errmsg": str(v)} import xlrd
show_url = Graphics.upload_image(file, data["context_type"], data["content_type"])
data_path = Graphics.format_nginx_data_url(show_url)
book = xlrd.open_workbook(data_path)
names = book.sheet_names() res = None
for name in names:
sheet = book.sheet_by_name(name)
nrows = sheet.nrows # 行
if nrows == 0:
print(nrows)
continue
else:
q = queue.Queue(maxsize=nrows)
threading.Thread(args=(q,)) first_line = sheet.row_values(0)
if first_line != ['编号', '姓名', '邮箱', '密码', '电话', '地址', '角色'] and len(first_line) != 7:
return {"errcode": 400, "errmsg": u"不支持此格式顺序的输入;正确格式:['编号', '姓名', '邮箱', '密码', '电话', '地址', '角色']"} for temp in range(1, nrows):
rows = sheet.row_values(temp, start_colx=0, end_colx=None) if rows[6] == "老师":
rows[6] = "TeacherEnrollment"
elif rows[6] == "学生":
rows[6] = "StudentEnrollment"
elif rows[6] == "助教":
rows[6] = "TaEnrollment"
elif rows[6] == "设计者":
rows[6] = "DesignerEnrollment"
elif rows[6] == "观察者":
rows[6] = "ObserverEnrollment"
else:
return {"errcode": 400, "errmsg": u"所写角色不存在,可选:【老师, 学生, 助教, 观察者, 设计者】"} query = {"user[name]": rows[1], "pseudonym[unique_id]": rows[2], "pseudonym[password]": rows[3],
"user[tel]": rows[4], "user[company]": rows[5], "user[time_zone]": "Beijing",
"user[locale]": "zh-Hans", "user[terms_of_use]": True, "user[role_name]": rows[6],
"user[college_id]": v["user[college_id]"]} q.put(query) res = self._user_batch_import(q)
return {"errcode": 0, "errmsg": str(res)} def _user_batch_import(self, q):
from app.api.apis import very_email, very_password, very_phone
header = {"Authorization": "Bearer %s" % AccessToken}
request_res = []
while q.qsize() > 0:
query = q.get()
if very_email(query["pseudonym[unique_id]"]) and very_phone(query["user[tel]"], "tel") and very_password(
query["pseudonym[password]"], "password"):
pass
else:
del query response = grequests.post(API_CANVAS_HOST + '/api/v1/accounts/{account_id}/users'.format(account_id=1),
headers=header, data=query)
request_res.append(response) res = grequests.map(request_res)
return res
python中的并发执行的更多相关文章
- Python中的并发编程
简介 我们将一个正在运行的程序称为进程.每个进程都有它自己的系统状态,包含内存状态.打开文件列表.追踪指令执行情况的程序指针以及一个保存局部变量的调用栈.通常情况下,一个进程依照一个单序列控制流顺序执 ...
- python中使用excutemany执行update语句,批量更新
python中使用excutemany执行update语句,批量更新 # coding:utf8 import pymysql import logging connection = pymysql. ...
- python中try except执行顺序
python中try except finally的执行顺序 先执行try中语句 如果try中抛出异常, 执行异常中语句. 如果try 或 except 中没有return语句,执行完try 或者 e ...
- python中subprocess.Popen执行命令并持续获取返回值
先举一个Android查询连接设备的命令来看看Python中subprocess.Popen怎么样的写法.用到的命令为 adb devices. import subprocess order='ad ...
- Python中的并发
目录 Python并发 并发三种层次 协程 生成者消费者 新关键字 网络io 线/进程 例子 线程池 进程通信 并发池 future对象 executor对象 参考 Python并发 并发三种层次 个 ...
- python中实现并发的手段之 协程
几种实现并发的手段 进程 启动多个进程 进程之间是由操作系统负责调用线程 启动多个线程 真正被CPU执行的最小单位实际是线程 开启一个线程 创建一个线程 寄存器 堆栈 关闭一个线程协程 本质上是一个线 ...
- 用greenlet实现Python中的并发
from greenlet import greenlet def test1(): print 12 gr2.switch() print 34 def test2(): print 56 gr1. ...
- python中关于不执行if __name__ == '__main__':测试模块的解决
1.新建测试脚本文件: 2.编辑测试脚本 import unittest import requests import json import HTMLTestRunner ur1 = 'http:/ ...
- Python中使用eval执行下面函数的结果怎么是字符串'10020'?
定义了函数: def add(a,b): s='a+b' c=compile(s,'','eval') gArea,lArea = {},{} gArea['a']=str(a10) gArea['b ...
随机推荐
- Tishreen-CPC 2018 G. Colors Overflow(分块)
Problem G. Colors Overflow Input file: standard input Output file: standard output Balloon Color: Da ...
- JavaWeb-SpringSecurity使用短信验证码登陆
相关博文 JavaWeb-SpringBoot_一个类实现腾讯云SDK发送短信 传送门 系列博文 项目已上传至guthub 传送门 JavaWeb-SpringSecurity初认识 传送门 Java ...
- apache httpd.conf 文件的 详解
文章 摘自 :http://www.php100.com/html/webkaifa/apache/2009/0418/1192.html ServerRoot /usr/local Server ...
- Git 推送文件到远程仓库
Configure Git for the first time: git config --global user.name "xxxxx xx"git config --glo ...
- sklearn4_混合分类器
python机器学习-乳腺癌细胞挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003&u ...
- 【React自制全家桶】四、React中state与props的分析与比较
一.state 1.state的作用 state是React中组件的一个对象.React把用户界面当做是状态机,想象它有不同的状态然后渲染这些状态,可以轻松让用户界面与数据保持一致. React中,更 ...
- 整型,长整型,无符号整型等 大端和小端(Big endian and Little endian)
一.大端和小端的问题 对于整型.长整型.无符号整型等数据类型,Big endian 认为第一个字节是最高位字节(按照从低地址到高地址的顺序存放数据的高位字节到低位字节):而 Little endian ...
- C++函数传值问题
在做题出现个神奇的事情,C++的传值跟其他OOP语言不一样.首先做个测试,看看下面输出结果是什么? void F(int a,int b,int c){ cout<<a<<b& ...
- 007. Reverse Integer
题目链接:https://leetcode.com/problems/reverse-integer/description/ Given a 32-bit signed integer, rever ...
- C#反射动态创建实例并调用方法
在.Net 中,程序集(Assembly)中保存了元数据(MetaData)信息,因此就可以通过分析元数据来获取程序集中的内容,比如类,方法,属性等,这大大方便了在运行时去动态创建实例. MSDN解释 ...