推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
yoke123
V2EX  ›  Python

Python 异步和线程的一些疑问

  •  
  •   yoke123 · May 22, 2018 · 3814 views
    This topic created in 3053 days ago, the information mentioned may be changed or developed.
    json_data = [
        'aaa': {
            'url': '....',
            'data': '...'
        },
        'bbb': {
            'url': '....',
            'data': '...'
        },
        'ccc': {
            'url': '....',
            'data': '...'
        },
    
        ...
     ]
    

    利用 json_data 里面的 url 地址去请求 返回数据 然后替换 url 的值

    同步请求太慢了 如何利用异步或者线程请求

    7 replies  •  2018-05-22 14:08:14 +08:00
    zhantss
        1
    zhantss  
       May 22, 2018   ❤️ 1
    用协程
    asyncio+aiohttp
    ltoddy
        2
    ltoddy  
       May 22, 2018
    用线程池, futures 模块里面的。
    enenaaa
        3
    enenaaa  
       May 22, 2018
    requests-futures
    可以用现成的库
    prim
        4
    prim  
       May 22, 2018
    gevent + requests
    几行代码
    diggerdu
        5
    diggerdu  
       May 22, 2018
    multiprocessing.pool.imap_async
    whx20202
        6
    whx20202  
       May 22, 2018
    你只是说太慢了,那么简单的话 起几个线程,异步然后 join 就行了
    速度取决于最慢的那个

    如果数目很多,就用上面说的就行了。 几个没必要用那些协程库
    NxnXgpuPSfsIT
        7
    NxnXgpuPSfsIT  
       May 22, 2018
    没懂替换 url 的值,如果是替换 data 的值的话是不是这个意思?

    import trip

    json_data = {'a': {'url': 'https://www.v2ex.com', 'data': '' },}

    @trip.coroutine
    def fetch(k):
    r = yield trip.get(json_data[k]['url'])
    json_data[k]['data'] = r.content

    def main():
    yield [fetch(k) for k in json_data]

    trip.run(main)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2562 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 13:36 · PVG 21:36 · LAX 06:36 · JFK 09:36
    ♥ Do have faith in what you're doing.