oficina python: hackeando a web com python 3

122
Hackeando a Web com Python 3 Marcel Caraciolo @marcelcaraciolo Desenvolvedor, Cientista, Instrutor, co- fundador do PyCursos, contribui com projetos open-source na área de ML, trabalha com Python há 6 anos, interessado em mobile, educação, machine learning and dadoooossss! Recife, Brazil - http://aimotion.blogspot.com http://bit.ly/IxkwD4

Upload: marcel-caraciolo

Post on 18-Dec-2014

3.269 views

Category:

Technology


23 download

DESCRIPTION

Workshop realizado na II Edição do Talk a Bit no CIN/UFPE. Em 30.11.2013

TRANSCRIPT

Page 1: Oficina Python: Hackeando a Web com Python 3

Hackeando a Web com Python 3

Marcel Caraciolo @marcelcaraciolo Desenvolvedor, Cientista, Instrutor, co- fundador do PyCursos, contribui com projetos open-source na área de ML, trabalha com Python há 6 anos, interessado em mobile, educação, machine learning and dadoooossss! Recife, Brazil - http://aimotion.blogspot.com

http://bit.ly/IxkwD4

Page 2: Oficina Python: Hackeando a Web com Python 3

Quem é Marcel ?

Este sou eu!

Page 3: Oficina Python: Hackeando a Web com Python 3
Page 4: Oficina Python: Hackeando a Web com Python 3

Tutorial para iniciantes!

Page 5: Oficina Python: Hackeando a Web com Python 3

Material adaptado dos Slides do Professor Fernando Masanori!

!

!

!

www.slideshare.net/fmasanori/hackeando-o-facebook-e-o-twitter-com-python-3-

campus-party-2013

Page 6: Oficina Python: Hackeando a Web com Python 3

Agenda• Intro ao Python 3

Brincando com Facebook

Brincando com Reddit & MongoDB

Brincando com Open Data & Twitter

Material para Casa

Brincando com Foursquare

Page 7: Oficina Python: Hackeando a Web com Python 3

Conhecendo a audiência• Professores

Estudantes

Sabem programar

Profissionais de TI

Sabem programar em Python

Page 8: Oficina Python: Hackeando a Web com Python 3

Primeiro prêmio

Page 9: Oficina Python: Hackeando a Web com Python 3

We love Python!

Page 10: Oficina Python: Hackeando a Web com Python 3

• Permite focar no problema, sem perder tempo na sintaxe

• Interativa

• Alta produtividade

• Baterias inclusas

• Comunidade livre, forte, diversificada, alegre e acolhedora

• Orientada a objetos, funcional, estruturada

• Uso geral vs nichos

• Simples de iniciar, sem esgotar

Page 11: Oficina Python: Hackeando a Web com Python 3

We Love Python

Page 12: Oficina Python: Hackeando a Web com Python 3

http://www.python.org/psf/diversity/

We Love Python

Page 13: Oficina Python: Hackeando a Web com Python 3

Meta: 20 % de presença feminina em 2015

We Love Python

Page 14: Oficina Python: Hackeando a Web com Python 3
Page 15: Oficina Python: Hackeando a Web com Python 3

Meta: 25% não americanos em 2015

We Love Python

Page 16: Oficina Python: Hackeando a Web com Python 3

We Love Python Hello World

Page 17: Oficina Python: Hackeando a Web com Python 3

We Love Python Hello World

Page 18: Oficina Python: Hackeando a Web com Python 3

Origem do nome Python

Page 19: Oficina Python: Hackeando a Web com Python 3

1h video/s 4 billion views

Python: quem usa Quem usa ?

Page 20: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 21: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 22: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 23: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 24: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 25: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 26: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa Python: quem usa

Page 27: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Você  sabia  que  o  “Pi”  do  nome  se  origina  de  Python?

Page 28: Oficina Python: Hackeando a Web com Python 3

Quem usa ?Python: quem usa

Page 29: Oficina Python: Hackeando a Web com Python 3

PopularidadePopularidade Github e StackOverflow

Page 30: Oficina Python: Hackeando a Web com Python 3

PopularidadeJobTrends Indeed.com

Page 31: Oficina Python: Hackeando a Web com Python 3

PopularidadeLinguagem do ano TIOBE em 2007 e 2010

Linguagem Favorita do LinuxJournal: 2009 a 2012

Page 32: Oficina Python: Hackeando a Web com Python 3

PopularidadeLinguagem do ano TIOBE em

2007 e 2010

Page 33: Oficina Python: Hackeando a Web com Python 3

O que falam de Python ?

“Se o Voldemort quisesse ser realmente imortal, ele teria programado uma horcrux recursiva  em  Python.”  Harry Potter.

O que falam de Python

Page 34: Oficina Python: Hackeando a Web com Python 3

O que falam de Python ?

“A vida é melhor sem chaves“. “A  vida  é  curta!  Você  precisa  de  Python”.

“Python me ajuda a focar nos meus conceitos em vez de ficar brigando com a linguagem”.

“Eu  não  preciso  digitar  muito.  Mas  o  que  eu  digito  é  certo”. Bruce Eckel, autor do best seller “Thinking in  Java”.

O que falam de Python

Page 35: Oficina Python: Hackeando a Web com Python 3

O que falam de Python ?

“Python é uma das cinco mais importantes linguagens que todo programador deve  conhecer”  Bjarne Stroustrup, criador de C++

O que falam de Python

Page 36: Oficina Python: Hackeando a Web com Python 3

Simples de Aprender

Neil Ibata, 15 anos, foi aprender a programar em Python com o pai e virou capa da revista Nature.

Linguagem poderosa, mas simples de aprender

Page 37: Oficina Python: Hackeando a Web com Python 3

Simples de Aprender

Programa de uma menina de 12 anos do Projeto CEDET Decolar

Linguagem poderosa, mas simples de aprender

Page 38: Oficina Python: Hackeando a Web com Python 3

Tempo para ser produtivo

C 2 anos Java 6 meses Python 1 mes

Tempo Para Ser Produtivo

Page 39: Oficina Python: Hackeando a Web com Python 3

Poder de Expressividade Expressive Power

Language Statements Lines C 1 1 Java 2.5 1.5 Python 6 6.5

Page 40: Oficina Python: Hackeando a Web com Python 3
Page 41: Oficina Python: Hackeando a Web com Python 3

Segundo prêmio

Page 42: Oficina Python: Hackeando a Web com Python 3

• Conta no Facebook • Internet • Python 3 • IDLE ou semelhante • Vamos fazer um aquecimento • Tutorial completo da linguagem

em Python for Zombies (YouTube)

Check List

Page 43: Oficina Python: Hackeando a Web com Python 3

Aquecimento: Install Python 3

• Windows – download

– executar > next > next...

• Linux – sudo apt-get install idle-python3.3

• Mac OS X – sudo port install python32

Page 44: Oficina Python: Hackeando a Web com Python 3

Aquecimento: Using Python 3

• Windows

– Iniciar > Programas > Python3.3 >

IDLE (Python GUI)

• Linux (terminal)

– idle-python3.3 &

• Mac OS X (terminal)

– IDLE3.3 &

Page 45: Oficina Python: Hackeando a Web com Python 3

Aquecimento: hello world

No modo interativo você recebe a resposta para cada comando executado

Page 46: Oficina Python: Hackeando a Web com Python 3

Aquecimento: modo interativo

• 2**100000 • dir(“abacate”) • help(“abacate”.upper) • “abacate”.upper() • a  =  “abacate” • b = 42 • a, b = b, a • print (a, b)

Page 47: Oficina Python: Hackeando a Web com Python 3

Aquecimento: modo interativo

• import random • random.randint(1, 100) • random.randint(1, 100) • random.choice(42, 13, 24, 7, 3, 10) • print (chr(33000)) • import this • import antigravity

Page 48: Oficina Python: Hackeando a Web com Python 3

Aquecimento: errando

No Python os espaços iniciais são importantes

Page 49: Oficina Python: Hackeando a Web com Python 3

Aquecimento: errando

Page 50: Oficina Python: Hackeando a Web com Python 3

String diferente de inteiro

Page 51: Oficina Python: Hackeando a Web com Python 3

Aquecimento: edition mode

No  modo  edição  você  precisa  “rodar”  o  programa  (Run Module ou F5)

Page 52: Oficina Python: Hackeando a Web com Python 3

Aquecimento: edition mode

Page 53: Oficina Python: Hackeando a Web com Python 3

Aquecimento: edition mode

Sempre  use  a  extensão  “.py”  para  não  perder  as  cores  do  seu  programa

Page 54: Oficina Python: Hackeando a Web com Python 3

Aquecimento: jogo simples

https://gist.github.com/fmasanori/6029123 https://gist.github.com/marcelcaraciolo/7715647

Page 55: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/marcelcaraciolo/7715664

Page 56: Oficina Python: Hackeando a Web com Python 3

for == while enrustido

Códigos equivalentes: for durante o dia vira while à noite

Page 57: Oficina Python: Hackeando a Web com Python 3

for == while enrustido

Códigos equivalentes

Page 58: Oficina Python: Hackeando a Web com Python 3

for == while enrustido

Códigos equivalentes

Page 59: Oficina Python: Hackeando a Web com Python 3

Aquecimento: criptografia

Feito por outra menina de 12 anos

Page 60: Oficina Python: Hackeando a Web com Python 3

• O dicionário em si consiste em relacionar uma chave a um valor específico

• Diferentemente das listas, onde o índice é um número, dicionários utilizam suas chaves como índice

• Para adicionar novos elementos não preciso de append, basta fazer a atribuição – Se a chave já existe: o valor associado é alterado – Se a chave não existe: a nova chave é adicionada

Dictionaries

Page 61: Oficina Python: Hackeando a Web com Python 3

Dictionaries

Page 62: Oficina Python: Hackeando a Web com Python 3

Dictionaries

Page 63: Oficina Python: Hackeando a Web com Python 3

• Faça um programa que leia o arquivo alice.txt e conte o número de ocorrências de cada palavra no texto. Obs.: para saber os caracteres especiais use import string e utilize string.punctuation

• http://www.gutenberg.org/cache/epub/11/pg11.txt

Dictionaries

http://www.gutenberg.org/cache/epub/11/pg11.txt

Page 64: Oficina Python: Hackeando a Web com Python 3

Dictionaries

https://gist.github.com/4673017 https://gist.github.com/marcelcaraciolo/7715709

Page 65: Oficina Python: Hackeando a Web com Python 3

JSON killer module JSON Killer!

Page 66: Oficina Python: Hackeando a Web com Python 3

• http://json.org/ • Independente de linguagem • Pares nome/valor • Lista ordenada • Muito adotado atualmente • Alternativa para o XML

– XML mais verbosa – XML menor legibilidade

Java Script Object Notation JavaScript Object Notation

Page 67: Oficina Python: Hackeando a Web com Python 3

Chuck Norris Nerdy Jokes

https://gist.github.com/4745061

Chuck Norris Nerdy Jokes

https://gist.github.com/marcelcaraciolo/7715734

Page 68: Oficina Python: Hackeando a Web com Python 3

Facebook Hacking

Page 69: Oficina Python: Hackeando a Web com Python 3

Hackers não são  “do  mal”?

Facebook Hacking

Page 70: Oficina Python: Hackeando a Web com Python 3

“O Facebook é dirigido por hackers. A maioria das pessoas pensa de um hacker como alguém que invade um sistema de computador. Mas nós vemos isso como uma filosofia. Aqui, os hackers assumem que sempre há uma maneira melhor, mais eficiente de resolver problemas.” facebook.com/careers (2012)

Facebook Hacking

Page 71: Oficina Python: Hackeando a Web com Python 3

{'first_name': 'Marcel',! 'gender': 'male',! 'id': '100000202630360',! 'last_name': 'Caraciolo',! 'link': 'http://www.facebook.com/marcel.caraciolo',! 'locale': 'en_US',! 'name': 'Marcel Caraciolo',! 'username': 'marcel.caraciolo'}

https://gist.github.com/marcelcaraciolo/7715741

Page 72: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/marcelcaraciolo/7715760

Page 73: Oficina Python: Hackeando a Web com Python 3

• https://developers.facebook.com/docs/reference/api/examples/

• Objetos JSON • Links autenticados • Obs.: access_token expira

• Autenticar novamente neste caso

Graph API

Page 74: Oficina Python: Hackeando a Web com Python 3

Anote o formato!

https://developers.facebook.com/docs/reference/api/examples/

Page 75: Oficina Python: Hackeando a Web com Python 3

Copie o access token!

https://developers.facebook.com/tools/explorer

Page 76: Oficina Python: Hackeando a Web com Python 3

Copie o access token!

https://developers.facebook.com/tools/explorer

Page 77: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/4674792

Facebook Friends

https://gist.github.com/marcelcaraciolo/7715831

Page 78: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/4684752

Facebook Friends Photos

https://gist.github.com/marcelcaraciolo/7715862

Page 79: Oficina Python: Hackeando a Web com Python 3

Android Wallpaper

Page 80: Oficina Python: Hackeando a Web com Python 3

Android Wallpaper

Page 81: Oficina Python: Hackeando a Web com Python 3
Page 82: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/marcelcaraciolo/7715921

Page 83: Oficina Python: Hackeando a Web com Python 3

Maria Luiza: Como se o evento não já estivesse bom, o CITi ainda melhora !!!!!#talkabit #Euvou!!Victor Maristane: Garoto Propaganda do Talk a Bit no NE10, hehehe!!(A propósito, não deixem de se inscrever no Talk a Bit++: http://citi.org.br/talkabit :), essa edição vai conseguir ser absurdamente melhor :DD)!!Jader Anderson: Boa filosofia para um encontro: Lean, Code e Play.!!http://citi.org.br/talkabit/!!Maria Luiza: Eu não sei se te contei MAS, o Talk a Bit custa apenas R$ 16,00 e já é dia 30/11. Vai ficar de fora é ??!Se inscreve logo:!http://citi.org.br/talkabit/

Idéias para o futuro ?! Análise de Sentimentos!

Page 84: Oficina Python: Hackeando a Web com Python 3

(tribute to Aaron Swartz, cofounder of Reddit, nov-1986, jan-2013)

Reddit MongoDB Client

Page 85: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/4691077

(by 10gen)

Reddit Client

https://gist.github.com/marcelcaraciolo/7716004

Page 86: Oficina Python: Hackeando a Web com Python 3

Question: cx_freeze “zlib not avaiable” error when using multiple threads #comments: 3 http://www.reddit.com/r/Python/comments/1ro891/question_cx_freeze_zlib_not_avaiable_error_when/ !Python Selenium - Open new tab / focus tab / close tab #comments: 9 http://www.reddit.com/r/Python/comments/1rmg4n/python_selenium_open_new_tab_focus_tab_close_tab/ !Python 3 gets some credit for how it chose to handle Unicode compared to other languages #comments: 24 http://mortoray.com/2013/11/27/the-string-type-is-broken/ !I am having too much trouble installing pygame. #comments: 1 http://www.reddit.com/r/Python/comments/1rnxnq/i_am_having_too_much_trouble_installing_pygame/ !Not exclusively Python, but a nice tool to generate regex code in multiple languages. #comments: 13 http://txt2re.com/ !Setting up a (web) development environment #comments: 11 http://www.reddit.com/r/Python/comments/1rnfle/setting_up_a_web_development_environment/ !Building a Flask Blog: Part2 #comments: 2 http://pypix.com/python/building-flask-blog-part2/

Page 87: Oficina Python: Hackeando a Web com Python 3

Flexible Schema

MongoDB == JSON MongoDB == BSON

Page 88: Oficina Python: Hackeando a Web com Python 3

Banco RelacionalRelational DB

Page 89: Oficina Python: Hackeando a Web com Python 3

Reddit MongoDB Client

https://gist.github.com/marcelcaraciolo/7716030

Page 90: Oficina Python: Hackeando a Web com Python 3

Reddit MongoDB Client

Page 91: Oficina Python: Hackeando a Web com Python 3

Foursquare & TagCloud

Page 92: Oficina Python: Hackeando a Web com Python 3

Foursquare & TagCloud's

Checklist

1. Instalar pygame

2. Instalar simplejson

3. Instalar pytagcloud

Page 93: Oficina Python: Hackeando a Web com Python 3

https://developer.foursquare.com/docs/

Page 94: Oficina Python: Hackeando a Web com Python 3

https://developer.foursquare.com/docs/venues/search

Page 95: Oficina Python: Hackeando a Web com Python 3
Page 96: Oficina Python: Hackeando a Web com Python 3

https://developer.foursquare.com/docs/venues/tips

Page 97: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/marcelcaraciolo/7717945

Page 98: Oficina Python: Hackeando a Web com Python 3

Delta Expresso

Page 99: Oficina Python: Hackeando a Web com Python 3

Twitter & OpenData

Page 100: Oficina Python: Hackeando a Web com Python 3

Twitter & OpenData

Checklist

1. tweepy

Page 101: Oficina Python: Hackeando a Web com Python 3

Acesso Twitter Autenticado

• Até junho de 2013 era possível acessar várias informações do Twitter sem necessidade de autenticação

• O Twitter resolveu melhorar a segurança e utilizar OAuth (Open Authentication) até o acesso básico (search)

• Neste protocolo, recebemos uma chave e senha que permite o acesso a um recurso específico durante algum tempo

Acesso Twitter Autenticado

Page 102: Oficina Python: Hackeando a Web com Python 3

Acesso Twitter Autenticado

• O usuário do Twitter precisa autorizar um programa externo, que recebe um consumer_key e um consumer_secret

• Na posse dessa chave e senha podemos pegar uma chave e senha de acesso temporária

• Não se preocupe se você não entender o Tweepy. Ano passado era mais simples e só recentemente ficou mais complicado acessar o Twitter

Acesso Twitter Autenticado

Page 103: Oficina Python: Hackeando a Web com Python 3

Acesso Twitter AutenticadoObtendo Chave e Senha de Acesso

https://dev.twitter.com/

Page 104: Oficina Python: Hackeando a Web com Python 3

Acesso Twitter AutenticadoObtendo Chave e Senha de Acesso

Page 105: Oficina Python: Hackeando a Web com Python 3

Acesso Twitter Autenticado

Page 106: Oficina Python: Hackeando a Web com Python 3

Acesso Twitter AutenticadoEnviando mensagens

Page 107: Oficina Python: Hackeando a Web com Python 3

Enviando mensagens!

Page 108: Oficina Python: Hackeando a Web com Python 3

Lendo API do Transito Recife

Page 109: Oficina Python: Hackeando a Web com Python 3

Lendo API do Transito Recife

http://www.recife.pe.gov.br/transito/recuperarPontos.aspx

Page 110: Oficina Python: Hackeando a Web com Python 3

https://gist.github.com/marcelcaraciolo/7717717

Page 111: Oficina Python: Hackeando a Web com Python 3

Lendo API do Transito Recife

Page 112: Oficina Python: Hackeando a Web com Python 3

Material para Casa

Twitter Dev API

Facebook Dev API

Foursquare API

Portal Transparencia

Page 113: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

http://www.novatec.com.br/livros/python-cookbook/

Page 114: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

Obs.: o autor já anunciou a segunda edição, aguardem...

Page 115: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

Obs.: o autor já anunciou a segunda edição, aguardem...

Page 116: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

Page 117: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

Page 118: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

Page 119: Oficina Python: Hackeando a Web com Python 3

Material para CasaMaterial para aprofundamento

Web Scraping

http://pyvideo.org/video/609/web-scraping-reliably-and-efficiently-pull-data

Page 120: Oficina Python: Hackeando a Web com Python 3

Material para Casa

http://beta.pycursos.com/python-para-zumbis/

Python para Zumbis (gratuito) http://pycursos.com/python-para-zumbis

Page 121: Oficina Python: Hackeando a Web com Python 3
Page 122: Oficina Python: Hackeando a Web com Python 3

Hackeando a Web com Python 3

Marcel Caraciolo @marcelcaraciolo Desenvolvedor, Cientista, Instrutor, co- fundador do PyCursos, contribui com projetos open-source na área de ML, trabalha com Python há 6 anos, interessado em mobile, educação, machine learning and dadoooossss! Recife, Brazil - http://aimotion.blogspot.com