请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

在协程中总会使用到同步IO

老师,请问一下,我在项目中使用的FastDFS实现的文件上传和下载,这样就没法使用异步了,有什么方案可以解决么?

正在回答 回答被采纳积分+3

2回答

bobby 2019-08-01 14:52:53
import time
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor   
MAX_WORKERS = 4
class Handler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)    
    @run_on_executor
    def background_task(self, i):        """ This will be executed in `executor` pool. """
        time.sleep(10)        
        return i    
        
    @tornado.gen.coroutine
    def get(self, idx):        """ Request that asynchronously calls background task. """
        res = yield self.background_task(idx)        
        self.write(res)


0 回复 有任何疑惑可以回复我~
  • 提问者 微微视界123 #1
    谢谢老师,另外我在使用aiomysql的时候遇到了以下的问题:
    
    async def clean(pool):
        rows = await pool.modify("truncate table django_admin_log_tmp")
        print("清空数据: total=%s" % rows)
        resTotal = await pool.queryOne("select count(*) total from django_admin_log")
        total = resTotal.get("total")
        print("数据总量:%s" % total)
        sql_insert = None
        keys = None
        for startNum, endNum in pool.make_groups(total=total, size=10000):
            sql = "SELECT * from django_admin_log limit :startNum, :endNum"
            dataList = await pool.queryAll(
                sql=sql,
                args={"endNum": endNum, "startNum": startNum}
            )
            print("数据量:%s, 抽样数据:%s" % (len(dataList), dataList[0]))
            if not keys:
                keys = list(dataList[0].keys())
                keys.remove("id")
            if not sql_insert:
                sql_insert = pool.get_insert_sql(table="django_admin_log_tmp", fields=keys)
            await pool._executemany(sql_insert, dataList, commit=True)
            print("插入成功。。。。")
    
    
    
    每次dataList读取出来的数据总量在增加,之后又变小;但是最终插入数据库的总条数不是整个django_admin_log_tmp的数量。
    回复 有任何疑惑可以回复我~ 2019-08-02 09:14:24
  • bobby 回复 提问者 微微视界123 #2
    能否将代码格式化一下 你不要在回复中写,你直接在评论中回复就可以格式化了
    回复 有任何疑惑可以回复我~ 2019-08-05 14:53:39
bobby 2019-07-31 17:48:08

tornado启动的时候有线程池 https://gist.github.com/methane/2185380 可以参照这个将阻塞任务扔到线程池中去运行

0 回复 有任何疑惑可以回复我~
  • 提问者 微微视界123 #1
    老师,这个地址打不开啊
    回复 有任何疑惑可以回复我~ 2019-08-01 09:17:12
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号