$30 off During Our Annual Pro Sale. View Details »
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Programação Assíncrona com Asyncio
Search
Allisson Azevedo
March 25, 2017
Technology
0
110
Programação Assíncrona com Asyncio
Palestra ministrada no PythonDay Campina Grande 2017
Allisson Azevedo
March 25, 2017
Tweet
Share
More Decks by Allisson Azevedo
See All by Allisson Azevedo
Crawleando sites com NodeJS
allisson
0
160
Introdução a linguagem Go
allisson
0
310
Docker + Django
allisson
5
650
Construindo um micro framework web em Python
allisson
0
230
Consumindo API's OAuth{1,2} com Python
allisson
1
190
Tarefas assíncronas com django e celery
allisson
1
24k
Deploy completo de uma aplicação Django
allisson
6
510
Desenvolvimento Web com Django
allisson
0
140
Otimizando sites com o nosql redis
allisson
4
170
Other Decks in Technology
See All in Technology
シンプルを極める。アンチパターンなDB設計の本質
facilo_inc
1
1k
MCP・A2A概要 〜Google Cloudで構築するなら〜
shukob
0
150
その設計、 本当に価値を生んでますか?
shimomura
2
160
モバイルゲーム開発におけるエージェント技術活用への試行錯誤 ~開発効率化へのアプローチの紹介と未来に向けた展望~
qualiarts
0
260
研究開発部メンバーの働き⽅ / Sansan R&D Profile
sansan33
PRO
3
21k
一億総業務改善を支える社内AIエージェント基盤の要諦
yukukotani
8
2.8k
useEffectってなんで非推奨みたいなこと言われてるの?
maguroalternative
9
6.2k
ページの可視領域を算出する方法について整理する
yamatai1212
0
160
Introduction to Sansan, inc / Sansan Global Development Center, Inc.
sansan33
PRO
0
2.9k
著者と読み解くAIエージェント現場導入の勘所 Lancers TechBook#2
smiyawaki0820
6
2.5k
プロダクトマネジメントの分業が生む「デリバリーの渋滞」を解消するTPMの越境
recruitengineers
PRO
3
380
ブラウザ拡張のセキュリティの話 / Browser Extension Security
flatt_security
0
260
Featured
See All Featured
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
1.8k
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
How GitHub (no longer) Works
holman
316
140k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
26
3.2k
Become a Pro
speakerdeck
PRO
30
5.7k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
120
20k
Building Applications with DynamoDB
mza
96
6.8k
Thoughts on Productivity
jonyablonski
73
5k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
52
5.7k
A Modern Web Designer's Workflow
chriscoyier
697
190k
GraphQLの誤解/rethinking-graphql
sonatard
73
11k
The Language of Interfaces
destraynor
162
25k
Transcript
PROGRAMAÇÃO ASSÍNCRONA COM ASYNCIO PythonDay Campina Grande 2017 Allisson Azevedo
1
ALLISSON AZEVEDO allissonazevedo.com youtube.com/user/allissonazevedo github.com/allisson twitter.com/allisson linkedin.com/in/allisson/ allisson.github.io/slides/
[email protected]
2
THE C10K PROBLEM Como lidar com 10k conexões simultâneas http://www.kegel.com/c10k.html
3
CONCORRÊNCIA Asynchronous I/O O exemplo do garçom Não confundir com
paralelismo 4
PROGRAMAÇÃO SÍNCRONA import time import requests from github import REPOS,
ACCESS_TOKEN start = time.time() for repo_url in REPOS: response = requests.get(repo_url, params={'access_token': ACCESS repo_info = { 'name': response['name'], 'full_name': response['full_name'], 'stargazers_count': response['stargazers_count'] } print(repo_info) end = time.time() print('Tempo de execução={:.2f} segundos'.format(end - start)) 5
PROBLEMAS COM PROGRAMAÇÃO SÍNCRONA Uma requisição http por vez 6
CONCORRÊNCIA USANDO THREADS import time import threading import queue import
requests from github import REPOS, ACCESS_TOKEN def grab_data_from_queue(): while not q.empty(): repo_url = q.get() response = requests.get(repo_url, params={'access_token' repo_info = { 'name': response['name'], 'full_name': response['full_name'], 'stargazers_count': response['stargazers_count'] } 7
PROBLEMAS COM THREADS Consumo de recursos Global Interpreter Lock (GIL)
8
CONCORRÊNCIA USANDO PROCESS import time import multiprocessing import requests from
github import REPOS, ACCESS_TOKEN def grab_data_from_queue(): while not q.empty(): repo_url = q.get() response = requests.get(repo_url, params={'access_token' repo_info = { 'name': response['name'], 'full_name': response['full_name'], 'stargazers_count': response['stargazers_count'] } print(repo_info) 9
PROBLEMAS COM PROCESS Consumo de recursos 10
CONCORRÊNCIA USANDO CONCURRENT.FUTURES import time from concurrent import futures import
requests from github import REPOS, ACCESS_TOKEN def get_repo_info(repo_url): response = requests.get(repo_url, params={'access_token': ACCESS repo_info = { 'name': response['name'], 'full_name': response['full_name'], 'stargazers_count': response['stargazers_count'] } print(repo_info) 11
PROBLEMAS COM CONCURRENT.FUTURES ThreadPoolExecutor - usa threads ProcessPoolExecutor - usa
process 12
ASYNCHRONOUS I/O COM PYTHON Twisted Tornado Eventlet Gevent Asyncio 13
ASYNCIO Python 3.4+ Tulip PEP-3156 14
HELLO WORLD import asyncio async def hello_world(): print('Hello World!') loop
= asyncio.get_event_loop() loop.run_until_complete(hello_world()) 15
HELLO WORLD COM TASKS import asyncio async def hello_world(name): print('Hello
World, {}!'.format(name)) loop = asyncio.get_event_loop() tasks = [] for name in ('fulano', 'cicrano', 'beltrano'): task = asyncio.ensure_future(hello_world(name)) tasks.append(task) loop.run_until_complete(asyncio.wait(tasks)) 16
CONCORRÊNCIA USANDO ASYNCIO import time import asyncio import aiohttp from
github import REPOS, ACCESS_TOKEN async def get_repo_info(repo_url): async with aiohttp.ClientSession() as session: async with session.get(repo_url, params={'access_token': ACC response_data = await response.json() repo_info = { 'name': response_data['name'], 'full_name': response_data['full_name'], 'stargazers_count': response_data['stargazers_count' } print(repo_info) 17
AIO LIBS https://github.com/aio-libs https://github.com/python/asyncio/wiki/ThirdParty 18
PACO import time import paco import aiohttp from github import
REPOS, ACCESS_TOKEN async def get_repo_info(repo_url): async with aiohttp.ClientSession() as session: async with session.get(repo_url, params={'access_token': ACC response_data = await response.json() repo_info = { 'name': response_data['name'], 'full_name': response_data['full_name'], 'stargazers_count': response_data['stargazers_count' } print(repo_info) 19
AIOHTTP from aiohttp import web async def handle(request): return web.json_response({'message':
'Hello World'}) app = web.Application() app.router.add_get('/', handle) web.run_app(app, host='127.0.0.1', port=8080) 20
SANIC from sanic import Sanic from sanic.response import json app
= Sanic() @app.route('/') async def test(request): return json({'message': 'Hello World'}) if __name__ == '__main__': app.run(host='127.0.0.1', port=8080) 21
AIOREDIS import asyncio import aioredis loop = asyncio.get_event_loop() async def
main(): redis = await aioredis.create_redis(('localhost', 6379), loop=lo await redis.set('key', 'hello world') val = await redis.get('key') print(val) redis.close() await redis.wait_closed() loop.run_until_complete(main()) 22
AIOMCACHE import asyncio import aiomcache loop = asyncio.get_event_loop() async def
main(): mc = aiomcache.Client('127.0.0.1', 11211, loop=loop) await mc.set(b'key', b'hello world') value = await mc.get(b'key') print(value) loop.run_until_complete(main()) 23
AIOPG import asyncio import aiopg from speakers import SPEAKERS dsn
= 'dbname=pythonday user=pythonday password=pythonday host=127. async def get_pool(): return await aiopg.create_pool(dsn) async def create_table(): pool = await get_pool() async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute('DROP TABLE IF EXISTS speakers') 24
AIOPG SQLALCHEMY import asyncio from aiopg.sa import create_engine import sqlalchemy
as sa from speakers import SPEAKERS metadata = sa.MetaData() speakers_table = sa.Table( 'speakers', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.String(255)) ) async def get_engine(): return await create_engine( 25
PYTEST-ASYNCIO import pytest import aiohttp from github import REPOS, ACCESS_TOKEN
async def get_repo_info(repo_url): async with aiohttp.ClientSession() as session: async with session.get(repo_url, params={'access_token': ACC response_data = await response.json() return { 'name': response_data['name'], 'full_name': response_data['full_name'], 'stargazers_count': response_data['stargazers_count' } 26
PERGUNTAS? 27
OBRIGADO! 28