Saltar a contenido

30. Tutoriales sobre el lenguaje Python

[ Tutorial básico]

  • Tutorial básico en github
  • (https://cplus.vikas.eu/user/asuarez/notebooks/workspace/Documentos/Python/python-basics-tutorial.ipynb) por Kuleshov

30.1 Documentación dePython

Seguir estos enlaces: * coroutinas

30.1.1 pydoc y docstring

El sistema más sencillo para documentar el código en python.

30.1.1.1 Docstring

Añadimos comentarios a fichero, función o clase y luego poder procesarlos

30.1.1.2 pydoc

La herramienta pydoc simple para generar (extraer y formatear) la documentación docstring. La documentación puede presentarse como páginas de texto en la consola, enviarse a un navegador web o guardarse en archivos HTML.

Ejemplo de uso

python -m pydoc .\eje2.py
Nota: es importante añadir .\ al nombre para obtener la documentación del fichero indicado
# ayuda
python -m pyocs -h
pydoc - the Python documentation tool

pydoc <name> ...
    Show text documentation on something.  <name> may be the name of a
    Python keyword, topic, function, module, or package, or a dotted
    reference to a class or function within a module or module in a
    package.  If <name> contains a '\', it is used as the path to a
    Python source file to document. If name is 'keywords', 'topics',
    or 'modules', a listing of these things is displayed.

pydoc -k <keyword>
    Search for a keyword in the synopsis lines of all available modules.

pydoc -n <hostname>
    Start an HTTP server with the given hostname (default: localhost).

pydoc -p <port>
    Start an HTTP server on the given port on the local machine.  Port
    number 0 can be used to get an arbitrary unused port.

pydoc -b
    Start an HTTP server on an arbitrary unused port and open a web browser
    to interactively browse documentation.  This option can be used in
    combination with -n and/or -p.

pydoc -w <name> ...
    Write out the HTML documentation for a module to a file in the current
    directory.  If <name> contains a '\', it is treated as a filename; if
    it names a directory, documentation is written for all the contents.

30.1.1.3 docstring con mkdocs

30.2 Instalación y actualizacón Python

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.10

sudo apt install python3.10-distutils

30.3 Instalar virtualenv

https://help.dreamhost.com/hc/es/articles/115000695551-Instalar-y-usar-virtualenv-con-Python-3

En Linux necesitamos instalar el paquete python-venv

 sudo apt-get install python3.11-venv
 ``` 


## Lenguaje Python
Lo menos frecuente:
### Métodos de instancia, de clase y estáticos.  
Esté [artículo](https://realpython.com/instance-class-and-static-methods-demystified/) explica las diferencias y ejemplos.
* Métodos de instancia: tiene acceso a las instancias con **self**
* **@classmethod** de clase, tiene acceso a la clase con **cls** pero no a la instancia. Se suele usar como una factoria de instancias para la clase
* **@staticmethod** estático, no tiene acceso ni a la clase ni a la instancia.  

Ejemplo:  
```python
class Pizza:
    def __init__(self, ingredients):
        self.ingredients = ingredients

    def __repr__(self):
        return f'Pizza({self.ingredients!r})'

    @classmethod
    def margherita(cls):
        return cls(['mozzarella', 'tomatoes'])

    @classmethod
    def prosciutto(cls):
        return cls(['mozzarella', 'tomatoes', 'ham'])

Podemos crear Pizzas con mipiza= Piza(['queso','jamon'])
También con:

>>> Pizza.margherita()
Pizza(['mozzarella', 'tomatoes'])

>>> Pizza.prosciutto()
Pizza(['mozzarella', 'tomatoes', 'ham'])

30.4 Modulos incluidos en las distribuciones

30.4.1 Servidor web mínimo SimpleHTTPServer

Se inicia con:

python3 -m http.server  <puerto>
Sirve el directorio de arranque como contenido de la web
Un paso más para crear un servidor personalizado usando el mismo módulo http.server (documentación)

No está recomendado para producción, solamente pruebas y desarrollo

from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
        self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("<body>", "utf-8"))
        self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
        self.wfile.write(bytes("</body></html>", "utf-8"))

if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

30.5 Python Framework

Empe Enlace al artículo los diez mejores framework Python.

Vamos a explorar algunos:

30.5.1 Bottle

Ligero WSGI (Web Server Gateway Interface) micro framework. Para desarrollo simple. Portal bottle
Características:

  • Routing: Requests to function-call mapping with support for clean and dynamic URLs.
  • Templates: Fast and pythonic built-in template engine and support for mako, jinja2 and cheetah templates.
  • Utilities: Convenient access to form data, file uploads, cookies, headers and other HTTP-related metadata. *Server: Built-in HTTP development server and support for paste, bjoern, gae, cherrypy or any other WSGI capable HTTP server. Ejemplo:
    from bottle import route, run, template
    
    @route('/hello/<name>')
    def index(name):
        return template('<b>Hello {{name}}</b>!', name=name)
    
    run(host='localhost', port=8080)
    

30.5.1.1 Instalación

pip install bottle

30.5.1.2 Tutoriales

Aqui

30.5.2 WebPy

web.py es un framework Python simple y poderoso (opensource).

30.5.2.1 Instalación

pip3 install web.py

30.5.2.2 Ejemplo de app

import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

30.5.2.3 Tutorial

Aqui
Contiene librerias para formularios y bases de datos (necesita las librerias de la BD)

30.5.3 CubicWeb

Cubicweb se anuncia como un framework semántico.

Its main features are:

  • an engine driven by the explicit data model of the application,
  • a query language named RQL similar to W3C’s SPARQL,
  • a selection+view mechanism for semi-automatic XHTML/XML/JSON/text generation,
  • a library of reusable components (data model and views) that fulfill common needs,
  • the power and flexibility of the Python programming language,
  • the reliability of SQL databases, LDAP directories, Subversion and Mercurial for storage backends.

30.5.3.1 Instalación

Instalamos las dependencias: lxml y libgcode

En Linux:

apt-get install gcc python3-pip python3-dev python3-lxml
apt-get install gcc python3-pip python3-dev libxslt1-dev libxml2-dev
Y además:
pip install cubicweb

30.5.3.2 Conceptos básicos cubicweb

Ver esta intro

30.5.3.3 Tutorial.

tutorial

30.5.4 DASH by plotly

Framework para desarrollo de app de datos de forma rápida. Está construida sobre React.js y Plotly.js

30.5.4.1 Instalación

pip install dash
Se recomienda instalar pandas:

pip install pandas

30.5.4.2 Tutorial

30.5.4.2.1 Layout

Ejemplo:

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for your data.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

30.5.5 AIOHTTP

Entorno asincrono en Python asyncio.

Incluye framework en el cliente y servidor.

30.6 Librerías Python

30.6.1 Librerías científicas

30.6.2 Librerias gráficas

En este documento de tutorial de visualización se repasan las librerias para mostrar gráficos

30.6.3 Machine Learning (ML)

https://scikit-learn.org/stable/

30.6.4 Libreria y framework TORNADO

Librería asincrona no bloqueante para llamadas web : tornado.

Tornado está compuesta por cuatro componentes principales:

  • Un framework web, incluyento RequestHandler
  • Implementación HTTP tanto de cliente como de servidor.
  • Librería asíncrona de red, incluyento clases IOLoop y IOStream .
  • Librería de corutinas (tornado.gen) . Es similar a las corutinas introducidad a partir de Python 3.5 ( async def). Se recomienda usar las corutinas nativas en lugar de las de tornado.
    Continua en notas locales

30.6.5 Librerias DOM

Procesamiento html xml:

  • https://lxml.de/tutorial.html
  • https://www.crummy.com/software/BeautifulSoup/bs4/doc/

30.7 PRUEBAS VARIAS

test jupyter nb