0% encontró este documento útil (0 votos)
12 vistas18 páginas

Snippets de Programación Web en Python

Este documento proporciona una introducción a varias técnicas de programación web con Python, incluyendo FTP, correo electrónico, grupos de noticias, clientes web, y servidores web. Explica cómo usar las bibliotecas ftplib, smtplib, imaplib, nntplib, urllib, y Django para acceder y manipular datos de forma remota.

Cargado por

Antonio Martinez
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
12 vistas18 páginas

Snippets de Programación Web en Python

Este documento proporciona una introducción a varias técnicas de programación web con Python, incluyendo FTP, correo electrónico, grupos de noticias, clientes web, y servidores web. Explica cómo usar las bibliotecas ftplib, smtplib, imaplib, nntplib, urllib, y Django para acceder y manipular datos de forma remota.

Cargado por

Antonio Martinez
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

Table

of Contents
Introduction 1.1
1 - FTP 1.2
2 - Email 1.3
3 - Noticias 1.4
4 - Cliente Web 1.5
Libreria urllib 1.5.1
Parsear HTML 1.5.2
5 - Servidor Web 1.6
Servidores de ayuda 1.6.1
Django 1.6.2

1
Introduction

SNIPPETS PARA PROGRAMACIN WEB


CON PYTHON
Primer experimento con Gitbook que hago

2
1 - FTP

FTP
Siempre que conectemos con un servidor, es importante que cuando acabemos
cerremos la conexin. Para usar FTP sobre Python tendremos los siguientes
pasos:

1) Importamos la librera

import ftplib

2) Conectamos con el servidor -> login

SERVER = 'nombre-del-server'
USER = 'mi-usuario'
PASSWORD = 'mi-password'

connect = [Link](SERVER)
[Link](USER, PASSWORD)

3) Si queremos ver los datos que hay en servidor

data = []
[Link]([Link])
for line in data:
print(line)

4) Descargar un archivo -> retrieve

filename = 'mi-archivo'
[Link]('RETR ' + filename)

5) Subir un archivo -> store

3
1 - FTP

filename = 'mi-archivo'
file = open(filename, 'rb')
[Link]('STOR ' + filename, file)

6) Cerrar la conexin con el servidor -> quit

[Link]()

4
2 - Email

Email

Mandar email
Los pasos para mandar emails son:

1) Importar la librera y mdulos correspondientes

import smtplib
from [Link] import MIMEMultipart
from [Link] import MIMEText

2) Creamos las variables necesarias:

SERVER = '[Link]'
REMITENTE = 'mi-correo'
DESTINATARIO = 'correo-de-mi-amigo'
ASUNTO = 'Asunto del mensaje que voy a enviar'
MENSAJE = 'El mensaje propiamente dicho'
USER = 'mi-usuario'
PASS = 'mi-contrasea'

3) Genero el mensaje:

msg = MIMEMultipart()
msg['From'] = REMITENTE
msg['To'] = DESTINATARIO
msg['Subject'] = ASUNTO
[Link](MIMEText(MENSAJE))

4) Definir el servidor con el que nos vamos a conectar y probar que funcione:

server = [Link](SERVER)
[Link]()

5
2 - Email

5) Iniciar sesin en el servidor:

[Link](USER, PASS)

6) Enviar el email:

[Link](REMITENTE, DESTINATARIO, msg.as_string())

7) Por ltimo, cerrar sesin:

[Link]()

Leer email
Los pasos para leer emails son:

1) Importar la librera y mdulos correspondientes

import imaplib

2) Crear las variables necesarias:

SERVER = '[Link]'
USER = 'mi-usuario'
PASS = 'mi-contrasea'
MAIL = 'mi-correo'

3) Conectar con en el servidor:

server = imaplib.IMAP4_SSL(SERVER, 993)

4) Iniciar sesin:

[Link](USER, PASS)

6
2 - Email

5) Seleccionar mensaje a leer:

status, count = [Link]('Inbox)


status, data = [Link](count[0], '(UID BODY[TEXT])')

print data[0][1] # Mensaje escogido

6) Por ltimo, cerrar sesin y conexin:

[Link]()
[Link]()

7
3 - Noticias

Noticias
Para leer noticias sobre seguimos los siguientes pasos:

1) Importar librera para el Newtwork News Transfer Protocol

from nntplib import *

2) Crear el servidor

URL_FREE_NETWORK_NEWS_SERVER = '[Link]'
server = NNTP( URL_FREE_NETWORK_NEWS_SERVER )

3) Definir los parmetros para conectar con el servidor

(resp, count, first, last, name) = [Link]('[Link]


n')

resp - Response del servidor


count - N de noticias cargadas
first - N de la 1 noticia
last - N de la ltima noticia
name - Nombre de la noticia

4) Pedirle al servidor que rango / tipo de noticias hay

(resp, subs) = [Link]('subject', (str(first)+'-'+str(last)


) )

subs - Gneros Por ejemplo muestro los 10 ltimos por pantalla y elijo cual
quiero ver

for subject in subs[-10:]:


print(subject)
number = input('Elija artculo')

8
3 - Noticias

5) Mostrar artculo por pantalla

(reply, num, id, list) = [Link](str(number))


for line in list:
print(line)

reply -
num -
id -
list - La noticia en s

9
4 - Cliente Web

4 - Cliente Web

10
Libreria urllib

Libreria urllib
1) Importar la librera urllib

import urllib

2) Abrir / Obtener la url de la pgina web

url = [Link]('[Link]

3) Sacar contenido de la pgina web

contents = [Link]()

Si quisiera ver todo el contenido puedo poner print(contents)

Si quisiera solo una lnea contents[1]

Si quisiera unas cuantas lneas contents[1:10]

4) Una vez con esto puedo sacar la informacin de la cabecera

headerinfo = [Link]()
date = [Link]('date')
contenttype = [Link]('content-type')

5) Para volcar el contenido a un fichero

[Link]('[Link] filename='urlconte
nt')

urlcontent - Fichero con la web volcada

11
Libreria urllib

12
Parsear HTML

Parsear HTML

Obtener contenido de la pgina


1) Importar libreras

import htmllib, urllib, formatter, sys

2) Abrir una pagina y obtener su contenido

web = [Link]('[Link]
data = [Link]()
[Link]()

3) Dar formato a la informacin

format = [Link]([Link](sys.s
tdout))

Con DumbWritter obtenemos 72 caractres por lnea


[Link] es para sacar la informacin por consola

4) Parsear la informacin HTML

ptext = [Link](format)
[Link](data)
[Link]()

Obtener links
3) No doy ningun formato

13
Parsear HTML

format = [Link]([Link]()))

4) Parsear HTML

ptext = [Link](format)
[Link](data)

5) Obtener los links de la propiedad anchorlist

for link in [Link]:


print(link)

Scrapear citas
1) Importar libreras

import urllib, re, sys

2) Definir smbolo a escrapear

symbol = [Link][1]

3) Descargar contenido de pgina

url = '[Link]
content =[Link](url+symbol).read()

4) Scrapear citas

m = [Link]('span id="ref.*>(.*)<', content)

5) Mostrar citas

14
Parsear HTML

if m:
quote = [Link](1)
else:
quote = 'no quote for symbol: ' + symbol
print(quote)

Web Crawler
1) Importar librerias

import urllib, htmllib, formatter, re, sys

2) Cargar la pgina, dar formato y parsear links

url = [Link][1]
web = [Link]('[Link] + url)
data = [Link]()
[Link]()
format = [Link]([Link]())
ptext = [Link](format)
[Link](data)
links = []
links = [Link]

3) Crawlear los dems links

15
Parsear HTML

for link in links:


if [Link]('http', link) != None:
print(link)
web = [Link](link)
data = [Link]()
[Link]()
ptext = [Link](format)
[Link](data)
morelinks = [Link]
for alink in morelinks:
if [Link]('http', alink) != None:
[Link](alink)

16
5 - Servidor Web

5 - Servidor Web

17
Django

Django

18

Common questions

Con tecnología de IA

Modular programming in Python allows for structured development of email and web client solutions. By using distinct libraries such as `smtplib` for emails, `urllib` for web clients, and `ftplib` for FTP, functionality is encapsulated in manageable sections. This modularity aids in debugging, updating, and scaling parts independently, enhancing maintainability. It enables reusability, where parts like email functions can be used across different applications without rewriting code . It also aligns with best practices for software design, supporting efficient team development and incremental enhancement.

Automating web interactions in Python should be done ethically by respecting robots.txt guidelines which indicate permissible scraping activity. Use libraries like `urllib` to collect data and `htmllib` to parse it, but do so by making requests at respectful intervals to avoid server strain. Consider using time delays between requests and limiting access to high-traffic parts of the target site. It's essential to review the site's terms of service to ensure compliance and avoid legal issues . Whenever possible, use APIs provided by the site for structured and authorized data access.

To scrape a webpage using Python's `urllib`, start by importing `urllib`. Open the webpage using `url = urllib.open('http://www.klinware.com')`. Read the page content with `contents = url.readlines()`. To access the headers, use `headerinfo = url.info()`, which allows you to retrieve specific headers, e.g., `date = headerinfo.getheader('date')` for the date header. For the content type, use `contenttype = headerinfo.getheader('content-type')` . Processing the page content involves handling the lines or converting them for further parsing or storage.

Reading an email using Python's `imaplib` involves these steps: First, import the `imaplib` module. Define the server details as `SERVER = 'imap.gmail.com'` along with the user credentials `USER` and `PASS`. Establish a connection using `server = imaplib.IMAP4_SSL(SERVER, 993)`. Login with `server.login(USER, PASS)`. To read emails, select the mailbox, typically 'Inbox', using `status, count = server.select('Inbox')`. Fetch the desired message using `server.fetch(count[0], '(UID BODY[TEXT])')`. Ensure you then logout using `server.close()` and `server.logout()` to terminate the connection . Proper handling of connections is crucial for security and resource management.

To parse HTML and extract links using Python's `htmllib`, begin with importing `htmllib`, `formatter`, and `sys`. Open the target URL with `urllib.urlopen('http://www.klinware.com')`, read its data using `data = web.read()`, and then close the connection. Format this data using `formatter.AbstractFormatter` and a `NullWriter` to handle outputs. Create an `htmllib.HTMLParser` object and pass the data to it using `ptext.feed(data)`. Finally, retrieve extracted links through the `ptext.anchorlist` property . Proper parsing ensures accurate extraction of hyperlinks embedded in HTML content.

To establish an FTP connection using Python's `ftplib` library, follow these steps: First, import the `ftplib` module. Connect to the server using `ftplib.FTP(SERVER)`, where `SERVER` is the server's name. Log in using `connect.login(USER, PASSWORD)`, providing the username and password. To ensure the connection is properly closed, use `connect.quit()` after completing operations . This ensures resources are freed and the session is terminated cleanly.

To retrieve and display news articles using Python's `nntplib`, start by importing the `nntplib` module. Connect to the news server, e.g., `URL_FREE_NETWORK_NEWS_SERVER = 'web.aioe.org'`, with `NNTP(URL_FREE_NETWORK_NEWS_SERVER)`. Subscribe to a newsgroup using `server.group('comp.lang.python')` which gives details about the group such as available articles. Use `server.xhdr('subject', (str(first)+'-'+str(last)))` to fetch article headers between a range, and display them. Prompt the user to select an article to read and fetch it with `server.body(str(number))` to print the content line by line . Handling server responses and parsing the output efficiently is critical for a smooth experience.

Creating a web crawler with Python's `urllib` and `htmllib` involves these steps: Import the necessary libraries. Initiate by loading the root page using `urllib.open()`, and read its content with `web.read()`. Apply `htmllib` for parsing by configuring a formatter instance with `formatter.NullWriter`. Parse the webpage content with `htmllib.HTMLParser` to feed the data and extract links into `ptext.anchorlist`. Collect the links, and for each link that contains 'http', print and visit it to extract more links similar to the first pass . Effectively managing the discovery of links and handling of recursion is key to scaling web crawlers efficiently.

In Python, sending files over FTP involves opening a file with `open(filename, 'rb')` and using `connect.storbinary('STOR ' + filename, file)` to upload it. For receiving files, use `connect.retrlines('RETR ' + filename)` to download. It is crucial to ensure connection and operations are securely managed to avoid unauthorized access. This includes using secure password practices and possibly transitioning to FTPs or SFTP for encrypted transfers, although `ftplib` does not natively support SSL . Properly managing credentials and connection closures with `connect.quit()` is vital for maintaining security.

To send an email using Python's `smtplib`, follow these steps: Import the `smtplib` and necessary email modules like `MIMEMultipart` and `MIMEText`. Set server information such as `SERVER = 'smtp.gmail.com:587'`. Prepare the email content by creating a `MIMEMultipart` object, setting the 'From', 'To', and 'Subject' fields, and attaching the message body with `MIMEText`. Connect to the SMTP server using `smtplib.SMTP(SERVER)`, call `server.ehlo()` to identify yourself, and initiate a session with `server.login(USER, PASS)`. Send the email using `server.sendmail(REMITENTE, DESTINATARIO, msg.as_string())` and close the session with `server.quit()` . Proper configuration ensures secure and authenticated email delivery.

También podría gustarte