SlideShare una empresa de Scribd logo
http://creativecommons.org/licenses/by-nc-sa/3.0/
Leganés, 11 y 12 de
febrero
José Manuel Ortega
Leganés, 11 y 12 de febrero
José Manuel Ortega
@jmortegac
Python para desarrolladores web
2 Python para desarrolladores web
https://speakerdeck.com/jmortega
 Stack,Django,Flask,Pyramid
 Requests
 Scraping(BeautifulSoap,Scrapy)
 Bokeh
 API Rest (Django-Rest-Framework)
 Twitter API
3 Python para desarrolladores web
Agenda
4 Python para desarrolladores web
Python Zen
Stack
5 Python para desarrolladores web
Django
6 Python para desarrolladores web
Django
7
 Most popular Python web framework
 Full stack web framework
 Django-ORM
 Template Engine
 HTTP Request/Response
 URL Routing Mechanism
 Testing
 Dev Server (WSGI)
Python para desarrolladores web
Django
8
 Model TemplateView
 Model → modelo de datos (models.py)
 View →vistas de datos (views.py): qué datos se presentan
 Template → plantillas HTML:cómo se presentan los datos
Python para desarrolladores web
Django
9
 django.contrib.auth Un sistema de autenticación
 django.contrib.contenttypes  Un framework para
tipos de contenidos
 django.contrib.sessions  Un framework para
manejar sesiones
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mysite.db',
}
}
Python para desarrolladores web
Django ORM
10 Python para desarrolladores web
Django Templates
11
 Templates are composed by Blocks
Python para desarrolladores web
Django example project
12 Python para desarrolladores web
Django example project
13 Python para desarrolladores web
Django-oscar
14
http://oscarcommerce.com
https://github.com/django-oscar/django-oscar
Python para desarrolladores web
Flask
15
 Microframework
 Built in development server and debugger
 Oriented to small applications with simpler
requirements.
Python para desarrolladores web
Flask example
16 Python para desarrolladores web
Flask
17 Python para desarrolladores web
Flask
18 Python para desarrolladores web
http://httpbin.org
Pyramid
19
 Python3 compatible
 Templates with Chamaleon
 Like django has his own bootstraping
toolpcreate
Python para desarrolladores web
Pyramid
20
pcreate -s starter hello_pyramid
├── CHANGES.txt
├── development.ini
├── MANIFEST.in
├── production.ini
├── hello_pyramid
│ ├── __init__.py
│ ├── static
│ │ ├── pyramid-16x16.png
│ │ ├── pyramid.png
│ │ ├── theme.css
│ │ └── theme.min.css
│ ├── templates
│ │ └── mytemplate.pt
│ ├── tests.py
│ └── views.py
├── README.txt
└── setup.py
Python para desarrolladores web
Pyramid
Learn REST API with Python in 90 minutes21
Pyramid
22 Python para desarrolladores web
Pserve development.ini
Pyramid
23
https://badges.fedoraproject.org
https://github.com/fedora-infra/tahrir
Python para desarrolladores web
Comparing web frameworks
24
Django Pyramid Flask
ORM Django-
ORM
Bootstrapping django-
admin
pcreate
Templates Chameleon
Migrations
Admin
interface
Visual debug
Python para desarrolladores web
Requests Module
 Python’s standard urllib2,httplib module provides most
of the HTTP capabilities you need, but the API is
thoroughly broken.
 Python HTTP: Requests. Beautiful, simple, Pythonic.
25
http://www.python-requests.org
Python para desarrolladores web
Use requests module
 Install requests module (pip install requests)
http://docs.python-requests.org/en/latest/user/install/#install
 Use it interactive mode
$ python
>>> import requests
>>> r = requests.get("http://httpbin.org/get")
26 Python para desarrolladores web
Use requests module
27 Python para desarrolladores web
Use requests module
28 Python para desarrolladores web
Beautiful Soup
29
 Librería que permite el parseo de páginas web
 Soporta parsers como lxml,html5lib
 Instalación
 pip install lxml
 pip instlal html5lib
 pip install beautifulsoup4
Python para desarrolladores web
Obtain links with bs4
30 Python para desarrolladores web
Obtain links with bs4
31 Python para desarrolladores web
Extract images with lxml
32
import requests
from lxml import html
Python para desarrolladores web
Extract program
33 Python para desarrolladores web
JSON in python
34
 import json
 json_dumps(data, sort_keys=True)
 Maybe allow human readable output
 json_dumps(data, sort_keys=True, indent=4)
Python para desarrolladores web
Scrapy
35 Python para desarrolladores web
Scrapy / pip install scrapy
Learn REST API with Python in 90 minutes36
Scrapy shell
37
scrapy shell <url>
from scrapy. import Selector
hxs = Selector(response)
Info = hxs.select(‘//div[@class=“slot-inner”]’)
Python para desarrolladores web
Scrapy shell
38 Python para desarrolladores web
Scrapy spiders
39 Python para desarrolladores web
Scrapy spiders
40
$ scrapy crawl <spider_name>
$ scrapy crawl <spider_name> -o items.json -t json
$ scrapy crawl <spider_name> -o items.csv -t csv
$ scrapy crawl <spider_name> -o items.xml -t xml
Python para desarrolladores web
Twisted
41
 Event-driven networking engine
 Procesar eventos de forma asíncrona
 https://twistedmatrix.com
Python para desarrolladores web
Bokeh
42
 Interactive, browser-based visualization for big
data, driven from Python
 http://bokeh.pydata.org
 Rich interactivity over large datasets
 HTML5 Canvas
 Integration with Google Maps
 http://bokeh.pydata.org/en/latest/docs/gallery.html
Python para desarrolladores web
Bokeh
43 Python para desarrolladores web
Bokeh Google maps
44 Python para desarrolladores web
Bokeh Google maps
45 Python para desarrolladores web
Javascript code generation
46 Python para desarrolladores web
Bokeh charts
47 Python para desarrolladores web
API Rest in Python
48
 Django Rest Framework (DRF)
pip install djangorestframework
Python para desarrolladores web
Django Rest Framework
49
Serializers &Views
Python para desarrolladores web
class PostSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Post
fields = ('author', 'title', 'text', 'created_date','published_date')
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
from rest_framework import routers, serializers, viewsets
Django Rest Framework
50
Urls
Python para desarrolladores web
Django Rest Framework
51 Python para desarrolladores web
Twitter API
52
 https://apps.twitter.com
 Oauth2
 Consumer API (API KEY)
 Consumer Secret (API Secret)
 Access Token
 Access Token Secret
Python para desarrolladores web
Twitter API
53
 Python-twitter
 https://github.com/bear/python-twitter
 Tweepy
 https://github.com/tweepy/tweepy
Python para desarrolladores web
Tweepy
54
import tweepy
from tweepy import OAuthHandler
consumer_key = 'YOUR-CONSUMER-KEY'
consumer_secret = 'YOUR-CONSUMER-SECRET'
access_token = 'YOUR-ACCESS-TOKEN'
access_secret = 'YOUR-ACCESS-SECRET'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
 api = tweepy.API(auth)
Python para desarrolladores web
Tweepy
Learn REST API with Python in 90 minutes55
 Timeline
 Tweet list
 Trending topic
for status in tweepy.Cursor(api.home_timeline).items(10):
print(status.text)
for tweet in tweepy.Cursor(api.user_timeline).items():
process_or_store(tweet._json)
def getTrends():
trends = api.trends_place(1)[0]['trends']
return trends
Python-twitter
56
import twitter
apiTwitter = twitter.Api(consumer_key="xxx", consumer_secret="xxx",
access_token_key="xxx", access_token_secret="xxx")
query = apiTwitter.GetSearch("#T3chFest2016“,count=50)
for result in query:
tweet = {}
tweet['text'] = result.text.encode('utf-8')
tweet['date'] = result.created_at.encode('utf-8')
tweet['favorite_count'] = result.favorite_count
tweet['lang'] = result.lang.encode('utf-8')
tweet['retweet_count'] = result.retweet_count
tweet['account'] = result.user.screen_name.encode('utf-8')
twitter_results.append(tweet)
Python para desarrolladores web
57 Python para desarrolladores web
Python-twitter
Python-twitter
58
outfile = open('twitter.json','wb')
for twitter_result in twitter_results:
line = json.dumps(twitter_result) + "n"
outfile.write(line)
Python para desarrolladores web
Python in the cloud
59 Python para desarrolladores web
Python in the cloud
60 Python para desarrolladores web
Python in the cloud
61 Python para desarrolladores web
Git
 https://github.com/jmortega/t3chfest_python_examples
62 Python para desarrolladores web
References
 Django project: http://www.djangoproject.com
 Flask: http://flask.pocoo.org
 Pyramid: http://www.pylonsproject.org
 Requests python module: http://www.python-requests.org
 BeautifulSoup: http://www.crummy.com/software/BeautifulSoup
 Bokeh:http://bokeh.pydata.org
 Django Rest:http://www.django-rest-framework.org
 https://www.pythonanywhere.com
63 Python para desarrolladores web
Thank you!
José Manuel Ortega <@jmortegac>

Más contenido relacionado

PDF
Scraping the web with python
PDF
Tz2014 workshop rundeck
PDF
Composer: Gestionando dependencias en PHP
DOCX
Individual analysis
PPTX
Shakespeare's comedy books
PPTX
Sneak Peak: Careers in Oil + Gas Online Tool (Nov. 2015)
DOC
Esquema hardware
PDF
No Matter Where You Ride
Scraping the web with python
Tz2014 workshop rundeck
Composer: Gestionando dependencias en PHP
Individual analysis
Shakespeare's comedy books
Sneak Peak: Careers in Oil + Gas Online Tool (Nov. 2015)
Esquema hardware
No Matter Where You Ride

Destacado (6)

PDF
08a BusinessPlanFV_IngAleViotti
PDF
Life Perú | Cinco atributos que necesitas para lograr un liderazgo empresaria...
PDF
SocialMedia_Identity_Acculturation_and_TheMilitarySpouse
PPTX
Kiran Mazumdar Shaw
PDF
Publication Design
PPTX
Lakme Absolute Brand Extension Analysis
08a BusinessPlanFV_IngAleViotti
Life Perú | Cinco atributos que necesitas para lograr un liderazgo empresaria...
SocialMedia_Identity_Acculturation_and_TheMilitarySpouse
Kiran Mazumdar Shaw
Publication Design
Lakme Absolute Brand Extension Analysis
Publicidad

Similar a Python para desarrolladores web (20)

PDF
PPT
Django - Plataforma de sitios web
PDF
Taller de Django betabeers
PDF
APIs REST: Django y Go
PDF
App engine
PPTX
Django - Curso Básico - Principales Conceptos
PPTX
Django - Curso Básico - Principales Conceptos
PDF
OpenAPI 3.0.2
ODP
Welcome to Django
PPTX
Pycon es 17 noviembre 2014
ODP
PPTX
Turbogears
PDF
Primeros pasos Symfony PHPVigo
PDF
Qué puede aprender Drupal de Plone
PPTX
Introducción a Android y conexión con SharePoint
PPT
Corp. In. Tec. S.A. - Capacitaciones en Informática - Programación con CodeIg...
PDF
1.- INTRO-PHP-POO OK 2025___________.pdf
PDF
A little bit of jazz with Django
PDF
Desarrollo aplicaciones web con python de forma nativa
PPTX
POO Y CONFIGURACION API REST FRAMEWORK DJANGO.pptx
Django - Plataforma de sitios web
Taller de Django betabeers
APIs REST: Django y Go
App engine
Django - Curso Básico - Principales Conceptos
Django - Curso Básico - Principales Conceptos
OpenAPI 3.0.2
Welcome to Django
Pycon es 17 noviembre 2014
Turbogears
Primeros pasos Symfony PHPVigo
Qué puede aprender Drupal de Plone
Introducción a Android y conexión con SharePoint
Corp. In. Tec. S.A. - Capacitaciones en Informática - Programación con CodeIg...
1.- INTRO-PHP-POO OK 2025___________.pdf
A little bit of jazz with Django
Desarrollo aplicaciones web con python de forma nativa
POO Y CONFIGURACION API REST FRAMEWORK DJANGO.pptx
Publicidad

Más de Jose Manuel Ortega Candel (20)

PDF
Seguridad y auditorías en Modelos grandes del lenguaje (LLM)
PDF
Seguridad y auditorías en Modelos grandes del lenguaje (LLM).pdf
PDF
Beyond the hype: The reality of AI security.pdf
PDF
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
PDF
Security and auditing tools in Large Language Models (LLM).pdf
PDF
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...
PDF
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
PDF
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PDF
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
PDF
Evolution of security strategies in K8s environments- All day devops
PDF
Evolution of security strategies in K8s environments.pdf
PDF
Implementing Observability for Kubernetes.pdf
PDF
Computación distribuida usando Python
PDF
Seguridad en arquitecturas serverless y entornos cloud
PDF
Construyendo arquitecturas zero trust sobre entornos cloud
PDF
Tips and tricks for data science projects with Python
PDF
Sharing secret keys in Docker containers and K8s
PDF
Implementing cert-manager in K8s
PDF
Python para equipos de ciberseguridad(pycones)
PDF
Python para equipos de ciberseguridad
Seguridad y auditorías en Modelos grandes del lenguaje (LLM)
Seguridad y auditorías en Modelos grandes del lenguaje (LLM).pdf
Beyond the hype: The reality of AI security.pdf
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
Security and auditing tools in Large Language Models (LLM).pdf
Herramientas de benchmarks para evaluar el rendimiento en máquinas y aplicaci...
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdf
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments.pdf
Implementing Observability for Kubernetes.pdf
Computación distribuida usando Python
Seguridad en arquitecturas serverless y entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud
Tips and tricks for data science projects with Python
Sharing secret keys in Docker containers and K8s
Implementing cert-manager in K8s
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad

Último (8)

PPTX
sistemas de informacion.................
PDF
DIMENSIONADO DE UNA INSTALACION FOTOVOLTAICA.pdf
PDF
modelos de control para sistemas digitales
PPTX
Derechos_de_Autor_y_Creative_Commons.pptx
PDF
AutoCAD Herramientas para el futuro, Juan Fandiño
PDF
simulacion de teoria de control para maquinas
DOCX
trabajo programacion.docxxdxxxddxdxxdxdxxxdxxdxdxd
PDF
Su punto de partida en la IA: Microsoft 365 Copilot Chat
sistemas de informacion.................
DIMENSIONADO DE UNA INSTALACION FOTOVOLTAICA.pdf
modelos de control para sistemas digitales
Derechos_de_Autor_y_Creative_Commons.pptx
AutoCAD Herramientas para el futuro, Juan Fandiño
simulacion de teoria de control para maquinas
trabajo programacion.docxxdxxxddxdxxdxdxxxdxxdxdxd
Su punto de partida en la IA: Microsoft 365 Copilot Chat

Python para desarrolladores web