Python Functions Master Class 2023

Python Functions Master Class 2023

entonces la idea con las funciones de python y puedo hacer un poco de texto aquí por las funciones es que realmente el bloque de construcción para la lógica y una vez que entiendas que son el bloque de construcción para la lógica puede hacer muchas cosas con una función de python y, en particular, una de las cosas que puede hacer con una función de python es obtener la lógica correcta para que pueda entrar y construir algo de lógica y luego en el centro de esto es su capacidad para controlar muchas cosas diferentes desde las funciones de python, por lo que lo que voy a hacer es enumerar algunas de esas cosas aquí y podemos decir, por ejemplo , que puede construir una pieza como una pieza de adición, por ejemplo, bien, puede decir sumar, restar, bien, eso podría ser eso podría ser una cosa que puede hacer, podría construir, eh, tal vez una herramienta de línea de comandos, ahí hay otra cosa que puede hacer con la función python, también puede construir lógica de GPU así que si querías saber hacer trabajo altamente paralizado, en realidad es solo una función de python si desea crear un microservicio, podría ser una función de python y, además, si desea crear una nueva forma sin servidor, es solo una función , por lo que una vez que vea este patrón en todas partes con eh, con las funciones de python, comienzas a darte cuenta de que , en muchos escenarios, el sueño es construir una función de python para experimentar si deseas seguir un determinado flujo de trabajo y, en mi opinión, probablemente puedas gastar el ochenta por ciento de tu tiempo tal vez el 90 por ciento tal vez en algunos casos el 100 de su tiempo solo escribiendo funciones de python y si necesita hacer programación orientada a objetos, hay muchas cosas geniales que puede hacer con python pero en general si quiere construir la lógica o construir una solución lo más rápido posible, literalmente no hay sustituto para construir primero una función de python, por lo que lo que puedo hacer para jugar con una función de python primero es ir a uh aa coll ab notebook y comenzaré con algunas de las ideas para una función de python, así que voy a colaborar aquí para obtener una solución alojada y luego voy a decir new notebook, sí, y lo que puedo hacer aquí es simplemente llamar a esto funciones 101. bien, entonces una de las cosas que me gusta del entorno del cuaderno de colaboración es que es fácil de usar, si primero casi lo usa como un bloc de dibujo solo para probar algunas ideas y entonces , ¿qué haré? aquí pondré un bloque que diga, por ejemplo, funciones de python funciones de python hola y luego, si hago una devolución, podemos ver que aparecerá en esta tabla de contenido, así que si fuera a construir una función de hola mundo la más simple sería simplemente esta es que podríamos simplemente decir hola y pasar a la derecha esa es la función de Python más simple posible, hay ventajas y desventajas , la ventaja es que es una línea, el conducto es que en realidad no hace nada cierto, esa es la desventaja de una función de python, ¡vaya!, déjame olvidé esta parte si lo ejecutas en una línea como esta porque el pasado no hace nada si quiero que haga algo un poco más complejo podemos hacer esto podemos saludar aquí y luego ahora ¿Podemos hacer algo? Podemos simplemente decir como imprime alto y esto es un poco más complicado, pero es esencialmente solo mantener una parte de la lógica y pasamos por aquí y solo saludamos bien y podemos realmente ponlo en marcha ahora si quiero que sea un poco más complicado lo que puedo hacer y lo llamaremos hola dos solo para que no me confunda, también podemos devolver algo para que podamos ir aquí y podemos decir definitivamente hola tres y luego podemos decir volver alto y luego, en este caso, si escribo hola tres , podemos ver que devuelve alto, lo que esto realmente significa es que si vuelvo a esto , eh, nosotros en realidad vamos a ponerlo aquí si voy a digo uh valor de retorno de hola dos es igual a hola a y luego si digo que el valor de retorno de hola tres es igual a hola tres podremos capturar ambos valores de retorno y si observo este, ¿qué hacemos? ¿qué tenemos? No hay nada dentro de hello2 porque no devuelve nada. y de forma predeterminada con python, el valor predeterminado no es correcto, por lo que no hay nada que se devuelva, es esencialmente equivalente a este valor de retorno, pero si miro el tercero aquí, podemos ver que hay un valor de retorno y es alto a la derecha, así que eso es esa es realmente la esencia es que puedes tener una función que hace algo dentro que es una unidad de trabajo eh o puedes tener una función que devuelve algo o incluso podrías hacer ambas cosas bien podrías hacer algún trabajo y luego podrías volver atrás Personalmente, creo que este estilo aquí es generalmente el camino a seguir para que no haya necesariamente algún efecto secundario en la función, está haciendo algo de trabajo y luego devolviendo los resultados, así que sigamos construyendo sobre esto y construyamos. d a a hola cuatro así que vamos a hola cuatro pero este va a tomar un parámetro en este caso será nombrado y luego podemos decir regresar y podemos hacer uh básicamente una cadena F aquí y podemos decir hola y ahora esto es esencialmente tomando una entrada haciendo algo con ella y luego devolviéndola y ahora si digo valor de retorno de hola cuatro lo que tenemos es algo un poco diferente y llamaremos a esto John aquí vamos y pongamos eso ahí, hola John, cierto, así que este patrón, aunque es intencionalmente extremadamente simple, es esencialmente lo que está sucediendo con una función de python es que vas a aceptar algún trabajo en la mayoría de los casos que vas a hacer. algo de trabajo y luego va a devolver los resultados de ese trabajo para que pueda encadenarlo y hacer otras cosas y una vez que tenga eso , hace que sea muy simple construir cosas cada vez más complejas, pero esto es realmente en la raíz lo que está involucrado con una función de python entonces lo que voy a hacer ahora es mostrar este repositorio aquí mismo, que es uno nuevo que estoy construyendo y lo pondré en el chat aquí para que otras personas puedan invocarlo y un par de cosas que señalaré es que voy a usar una función llamada espacios de código de GitHub en espacios de código de GitHub es gratis para cualquiera, puede simplemente iniciarlo, pero una de las cosas que voy a hacer en este entorno particular es que haré un poco de cosas con la GPU, así que es algo que no tienes que usar , pero quería mostrar algunas cosas geniales que puedes hacer con la GPU con funciones también, pero de nuevo va para ser este repositorio que acabo de poner en el chat grupal y lo que puedo hacer ahora es tomar este cuaderno de colaboración y puedo registrarlo en ese repositorio en particular que aparecerá en un segundo y entonces, periódicamente, si necesito volver a referirme a este cuaderno en particular, el Cuaderno se verificará allí, así que iremos aquí, lo haremos simplemente baje a esto y verificaré que allí creo que necesito agregar, bueno, es un poco más complejo , simplemente lo descargaré y lo pondré, será un poco más fácil , así que uno de lo divertido es que puedes simplemente agregar un archivo directamente dentro de aquí, puedes decir agregar archivo, cargar un archivo y luego puedo arrastrar ese cuaderno dentro de este repositorio y luego simplemente se mostrará arriba para que otras personas puedan jugar con él allí está, um, lo que voy a hacer aquí es ir al código y si está usando la versión gratuita, puede iniciar su propio espacio de código simplemente haga clic en este botón y creará un espacio de código. Una cosa que mencionaré sobre este entorno en particular es que estoy usando um también me gusta este concepto de compilaciones previas y la idea con esto es que uh si yo configurar mis entornos tendrá todas estas instalaciones y sucederán cosas realmente complicadas y luego todo sucederá detrás de escena si quieres t para usar precompilaciones de espacio de código que es un buen enfoque para usar , pero la esencia es que dentro de este archivo contenedor Dev tengo algunos pasos de instalación en este caso, esto en realidad me permite ejecutar contenedores que están habilitados para GPU en el interior y luego también hay algunas extensiones aquí como, por ejemplo, copilot y otras herramientas que me ayudan a construir mi interfaz, pero puede copiar esto de manera idéntica, solo ejecútelo y juegue al mismo tiempo, así que ya he lanzado uno que está aquí y voy para ajustarlo ligeramente en función de lo que estamos haciendo hoy, así que primero haré un get pull ya que hice un pequeño cambio aquí. Diré get pull así y luego iré al archivo Léame. y voy a modificar el archivo Léame un poco para que sea más como un archivo Léame para este proyecto en particular que estamos usando, así que esta es una buena idea cuando estás cuando estás construyendo, uh, las cosas se usan esencialmente como una plantilla y te mostraré usted que también si vuelvo aquí, observe que esto se genera a partir de esta plantilla uh mlops y, por lo tanto, si crea una plantilla y volveré a la plantilla dentro de este entorno, entonces otras personas pueden usar su plantilla, así que eso es esencialmente lo que Estoy haciendo. Paso muchas semanas de trabajo y semanas construyendo este entorno y luego puedo hacer un nuevo repositorio a partir de esta plantilla y eso es exactamente lo que es este entorno, así que me desharé de todo. en el archivo Léame esencialmente y lo pondré en la parte superior digamos que conoce las funciones de python domina las funciones de python y diremos diciembre de 2023. ahí vamos y lo que puedo hacer es documentar lentamente las cosas que estoy haciendo y podemos decir el paso un paso uno use notebook use use notebook y lo que podemos hacer es simplemente apuntar un enlace a ese cuaderno que agregué que está justo aquí, también podemos ejecutarlo dentro de esto entorno un cuaderno pero pero voy a poner un enlace a él aquí voy a digamos, básicamente, revise este cuaderno , póngalo como referencia de documentación, ahí lo tiene, así que revise ese cuaderno ahora, lo siguiente que creo que sería importante resaltar es que para escribir cosas realmente, muy rápido , es una buena idea establecer crear una infraestructura para que pueda crear funciones muy, muy rápidamente y lo que describiría para hacer eso es que llamaría a esto devops en el ciclo, así que sigamos adelante y hablemos sobre lo que realmente son los devops en el ciclo, así que los devops en el ciclo es esencialmente la capacidad de usar devops para acelerar su capacidad de escribir código y, de hecho, lo que puedo hacer es que voy a verificar esto muy rápido para obtener el estado, agreguemos esto al archivo Léame y diremos más pasos aquí y luego voy a volver a este otro enlace aquí porque lo que puedo hacer es soltar una imagen justo dentro de aquí y de hecho tengo una imagen genial que habla de devops en el bucle justo en mi escritorio y voy a seguir adelante y dejar esto en el bucle aquí, así que de hecho tenemos desarrolladores en el bucle aquí vamos, así que sigamos adelante y hagamos esto, así que aquí hay uno del que podemos hablar y también podemos hablar sobre el concepto de sobres para GitHub, por lo que estos serán dos temas muy divertidos de los que hablar, por lo que el primero es a lo que me refiero en términos de devops en el ciclo . lo que quiere hacer para obtener la productividad más rápida de un entorno como este y esto es algo nuevo debido a la capacidad de usar herramientas como GitHub copilot es que desea usar las mejores prácticas tradicionales de desarrollo y qué eso significa que tiene un archivo make dentro de su proyecto que revisaré en un segundo que le permite hacer pasos reproducibles que hará el sistema de compilación y, por lo tanto, esto sería make lint make format make test una vez que configure realmente no tienes que hacer mucho para modificarlo en el futuro bu Lo que esto hace es permitirle usar herramientas de desarrollo de software tradicionales como las pruebas de formato de LinkedIn para limpiar las sugerencias que provienen de un asistente de programación de compañeros de IA y veremos esto también con otras herramientas, así que si desea usar código susurrar lo que demostraré un poco más tarde hoy código susurro es lo mismo que desea crear herramientas que realmente le permitan formatear para limpiar para probar las sugerencias para que pueda obtener lo mejor de en ambos mundos obtienes la nueva generación de herramientas que creo que prevalecerá en 2023 además de que quieres usar las herramientas tradicionales de desarrollo de software y quieres hacer todo esto dentro de un entorno reproducible y esto es lo que permite un espacio de código usted tiene un entorno reproducible reprodu AWS Cloud9 es muy similar y luego tiene una herramienta como el código de Visual Studio ahora lo que hace es que le permite usar las mejores prácticas de desarrollo de LinkedIn formateo te Sting para acelerar su productividad localmente y luego, en lugar de las acciones de GitHub y el sistema de compilación, en realidad probará el código y la razón por la que menciono esto es que una vez que comprende este proceso localmente, hace que sea trivial implementarlo . producción y creo que muchas personas están interesadas en implementar en producción implementar herramientas de tipo de operaciones de aprendizaje automático implementar microservicios implementar herramientas de línea de comando implementar contenedores todo esto es asistido por devops en el ciclo y, de manera similar, hablemos un poco sobre este concepto de bi -ecosistema direccional para mlops y lo bueno de esto es que todavía corresponde a lo que hablé anteriormente con funciones, cada cosa aquí es esencialmente una función y lo que esto significa es que dentro de GitHub puedes obtener estas sugerencias para escribir una función tú puede probar las funciones, tiene esta mentalidad de producción primero, también puede tener infraestructura como código para que pueda usar herramientas como AWS cdk para construir realmente la infraestructura para implementar sus funciones y luego, dentro de un entorno basado en la nube, puede implementarlo en una plataforma ml Ops, puede implementarlo en una plataforma sin servidor como AWS Lambda, puede trabajar con servicios de contenedores con los que puede trabajar calcular todas estas cosas están habilitadas por este entorno basado en la nube, por lo que esta es realmente la etapa aquí que vamos a establecer y luego voy a trabajar de manera iterativa, así que volvamos a este entorno si hago un get tire, veremos que esas nuevas imágenes que vamos están dentro de este entorno devops en el bucle y ahora echemos un vistazo a los componentes necesarios para los devops en el bucle, por lo que el primer componente es esta es la herramienta de instalación, ¿cuál de los siguientes? las cosas que en realidad han sido un tema candente de discusión para mí personalmente son estas como Herramientas de instalación avanzadas hay muchas herramientas de instalación avanzadas conda poesía Etc. pero en realidad no necesita ninguna herramienta avanzada, solo necesita la biblioteca estándar de python y, de hecho, si usa un entorno virtual de python que estoy usando, que está justo aquí , todo lo que necesita hacer es usar las herramientas pip predeterminadas, en realidad no hay ninguna situación en la que necesite una herramienta avanzada si desea usar un avanzado excelente herramienta siga adelante y use una herramienta avanzada no es necesario que use un entorno virtual de herramienta avanzada y pip están instalados de forma predeterminada con python en este escenario lo que hago es cada vez que hago un cambio en mi instalación o hago una compilación en el servidor de compilación, realmente pasa y actualiza el instalador predeterminado de python uh, que es pip y mira dentro de estos requisitos, echemos un vistazo a este archivo de requisitos, todo esto es que no tiene nada de especial, es solo la versión de un paquete que instalé en mi sistema y capturé cuál es el nombre del archivo o el número de versión y lo puse dentro de aquí y lo que significa es que es reproducible significa que puedo reproducir exactamente lo que hice antes porque esa versión en particular está anclada dentro de aquí y puede ver que hay toneladas y toneladas de bibliotecas, conoce algunas de estas que podemos usar hoy en día, algunas de estas tal vez no, pero haciendo la instalación localmente de forma interactiva y ejecutándola dentro del sistema de compilación, en realidad podemos obtener constantemente un ciclo de retroalimentación que me dice si algo funciona, de hecho, intentemos esto muy rápido si solo escribo make install aquí vamos, podemos ver que, de hecho, funcionará y lo hará intente hacer todas las instalaciones, debería encontrar los requisitos almacenados en caché, puede ver que ya se cumplieron, por lo que no hay nada que hacer más que verificar y ver si hay uno nuevo para instalar ahora, una cosa que señalaré toda esta configuración es que esto es parte del ciclo de retroalimentación para construir la producción para el software constantemente probando su método de instalación eh y también para mantenerlo muy, muy simple y echemos un vistazo a cómo hice esto también adentro este contenedor Dev aquí tenemos un Dev container.json aviso aquí que en la parte inferior tengo algo llamado bash setup todo esto significa que cuando se inicia el contenedor ejecuta este archivo llamado setup.py y no hay nada en él todo lo que hago es buscar en la fuente el entorno virtual que se creó y, nuevamente , estas son las herramientas estándar de la biblioteca de python. No hay otra compañía. Necesito usar ningún otro software de terceros. Necesito usar. Esta es la biblioteca estándar de python. Luego hago eco de que dentro de mi bashrc lo que esto significa es que generará el entorno virtual cuando se configure el entorno, eso es todo, literalmente, no hay nada que hacer para python que no sea usar esto y si vamos al archivo acoplable en sí y le echamos un vistazo esto es lo que está construyendo este entorno no está pasando mucho aquí lo que hago es usar el contenedor Dev recomendado por GitHub instalar un par de otros paquetes en este caso esto me permite usar este ngs como abrir AI susurro Instalo python de nuevo el python de la biblioteca estándar predeterminado Puse un par de otras utilidades aquí todo lo que hace es habilitar el gpus de Nvidia dentro de Docker y luego creo un entorno virtual de python y lo copié allí mismo así que esto es completamente reproducible No necesito nada más de ningún otro proveedor, eso es todo, estas son las herramientas estándar de python ahora que tengo eso, si volvemos al archivo make aquí, puedo hacer las otras cosas que son mejores para los desarrolladores. prácticas, entonces lo que esto significa es que, en mi opinión, lo que debería estar haciendo cuando recibe estas sugerencias es formatear su código y estoy usando una herramienta llamada python black y si solo escribimos esto muy rápido, simplemente ingresamos haga que el formato simplemente pase y asegúrese de que si el código está en mal estado, simplemente lo limpiará y luego, si digo hacer lo mismo con lint , solo verificará los errores de sintaxis y si hay algún tipo de problema de sintaxis lo haré lo haré yo Me dará una advertencia, ya sabes lo que hago normalmente, ya que hago esto con tanta frecuencia, es que en realidad solo hago refactor, así que recibo sugerencias del copiloto, haz que refactor mire lo que hace. pasa y ejecuta una pelusa y una prueba. Descubrí que esto es extremadamente productivo cuando estás construyendo cosas muy, muy rápido, así que solo quería preparar el escenario para todas las herramientas que voy a usar. las próximas horas para que pueda entender bajo el capó desde los primeros principios todo lo que está pasando y , sorprendentemente, incluso las personas con mucha experiencia con python no están haciendo algo tan simple, pero en mi recomendación, el ochenta por ciento de las personas en Python que usa el lenguaje Python debería usar este tipo de configuración y solo volverse más complejo y usar otras herramientas complejas si esas herramientas complejas son necesarias por cualquier motivo, pero esta es la base en mi opinión de lo que alguien debería construir cuando estas construyendo Saque una estructura de python, así que ahora lo que podemos hacer es comenzar a escribir código, así que lo que voy a hacer es tener todos estos directorios diferentes aquí y otra vez, si miramos el archivo make aquí, lo estoy abrazando . face repository eh, pero voy a seguir adelante y construir cosas a partir de un nuevo directorio potencialmente nuevo y llamaremos a este um uh lógica de función, así que llamaremos a este uh funk Funk Lodge, ¿qué tal ese funk Lodge y dentro de este directorio, puedo poner un código de biblioteca, así que continuaré e iré aquí y diremos funk Lodge así y pondré un archivo de punto aquí, así que la idea es que pueda comenzar a construir piezas de lógica y código de biblioteca que puedo usar para múltiples propósitos y si volvemos a este bloc de bocetos aquí, puedo reutilizarlo bien, así que una vez que construyo una función de python, digamos incluso en la raíz de si tenemos como una función de agregar, esta sería quizás una buena para demostrar en el centro aquí , podría agregar una GPU o podría agregar una la herramienta camaleón o podría agregar un microservicio o podría agregar sin servidor justo en el corazón es la lógica y luego puedo redirigir a estas otras herramientas y puedo hacer un dónde está esta herramienta Flecha aquí que creo que es esto ir a la arrow ahí vamos y entonces sería así una vez que tengas esto, puedes construir, de hecho, construir una vez, disfrutar de mini, ese es realmente el concepto con uh, con las funciones de python, así que vamos a mover todas estas cosas aquí, así que ahora. lo que voy a hacer es agregar este directorio a mi bucle de formato y, debajo de aquí, lo que puedo hacer es agregar esto, probablemente podamos hacer eso y podemos decir funk Lodge allí mismo asterisco Dot py y luego, de manera similar , puedo agregar una estrofa aquí exactamente y ahora, si digo que sabe hacer refactorizar , también debería mirar esta sección en particular. Supongo que si quisiera estar más limpio, incluso podría eliminar esas otras cosas y probablemente no una idea horrible en realidad para hacer eso, sigamos adelante y hagamos que vamos a hacerlo simple usemos solo las cosas que estamos construyendo hoy otras cosas a las que puedo llegar o no, así que puedo limpiar esto y pueden ver aquí cómo es fácil construir un nuevo estructura para pelusa o prueba, eso es correcto y así, incluso podríamos modificar esto en el futuro, también hacer refactorización y dice por pelusa aquí, intentemos que ahí vamos para que podamos limitar el formato, así que ahora pongamos algo. ahí , así que diría que lo primero que hay que hacer dentro de una función como esta es crear un fragmento de código y creo que probablemente una especie de función matemática es una de las más fáciles de jugar, así que vamos. adelante y hagamos eso primero vamos aquí y llamaremos a este um código matemático matemático así y luego puedo hacer clic aquí y comenzar a construir mi código matemático ahora aquí es donde comienza la diversión es que si aprovechas una herramienta de programación de IA como copilot, en realidad puedes codificar mucho más rápido y ¿Tiene una red de seguridad porque la herramienta de refactorización captará algunas de las cosas? Probemos esto. Si voy aquí , necesito cebar la bomba. Básicamente, necesito decirle a mi herramienta de programación de pares qué es lo que estoy haciendo. para hacerlo, puede obtener las indicaciones correctamente y voy a decir que sabe construir varias, varias funciones que realizarán operaciones matemáticas comunes exactamente ahí vamos, así que, ¿qué hacemos bien primero, solo eh? y ahí vamos, es lo suficientemente inteligente como para saber que probablemente quiero algo como un anuncio correcto y lo crea para mí ahora si quiero y creo que es una buena idea de inmediato. Comenzaría a refactorizar esto , así que diremos hacer refactor. ahí vamos, mira, ya lo limpió bien, así que este es realmente el gran ciclo de retroalimentación, supongamos que hizo un error aquí así, ¿qué debería hacer para ver si ya detecta el error, así que esta es la razón por la cual es tan crítico ? usar estas herramientas simultáneamente con una herramienta de programación de pares y si quiero puede agregar más cosas, podemos decir um y a, y puede prepararlo agregando un comentario en la parte superior, puede decir que sabe construir una función de resta, ahí vamos, así que esto es realmente un código repetitivo, ¿realmente lo necesita ? o no sabes que es como si realmente necesitas escribir este código o no Yo diría que probablemente no um y luego si queremos construir una multiplicación ahí vamos y luego tal vez una división y potencialmente um eso es lo suficientemente bueno, creo sigamos con eso y ahora solo puedo decir hacer refactorizar, así que aquí está el siguiente truco cuando construyes algo como esto está bien, ¿qué hago con eso? ¿Cómo construyo otras cosas? Diría uno Una de las primeras cosas que recomendaría es interrogarlo mediante el uso de python interactivo, de modo que si vamos aquí y escribo IPython ahora, puedo comenzar a dar forma a la API correctamente para poder ir a la API de python y decir, ¿de acuerdo? ¿Estoy construyendo aquí ? Probemos esta lógica, así que lo que hago es digamos desde Funk logic import add y ahora funk vamos a verificar dos veces por qué um oh porque lo importé mal, así que este es exactamente el error que eliminaríamos correctamente es que en realidad no es el nombre del archivo, agregue entonces lo que queremos hacer es decir decir de Funk Lodge dot código matemático importar anuncio ahí vamos, así que ya he desarrollado un error potencial y luego solo digo agregar dos y dos cuatro a la derecha, así que creo que esta es una de las formas más divertidas . una vez que comienzas a construir una gran biblioteca para ejecutarla es hacer eso y ahora todo lo que tengo que hacer es poner esto en algo y yo recomendaría cuando estés construyendo lógica que el primer paso sería después de probarlo y tener todo limpio es construir una herramienta camaleónica y lo que podemos hacer a continuación es que podemos construir una herramienta camaleónica para esto, así que voy a seguir adelante y decir tocar y yo Comenzaré a usar una convención porque las cosas son así que voy a construir tantos comandos l ine tools, voy a decir CLI y llamaremos a este um código matemático, eh, así que podemos enumerar que proviene de este directorio y luego desde aquí puedo agregar esto a mi archivo make para Solo puedo decir Está bien, vamos a hacer algunas cosas más aquí, así que sigamos y hagamos esto y podemos decir woo, no quiero esa sugerencia , voy a decir que es un poco molesto que me esté obligando a haga esa sugerencia, voy a decir el código matemático CLI mathcode.py, ahí vamos, aunque creo que ya cubrirá eso, así que no necesito hacer eso, no importa y luego, además, para formatear, cubrirá todo lo que funciona actualmente. directorio por lo que estamos listos, por lo que siempre es bueno verificar que ahora puedo ir a este código matemático aquí y también puedo configurar el mismo mensaje para que en la parte superior aquí podamos decir crear una CLI basada en clics que use la lógica en eh, el um mathcode.py y esto es realmente bueno porque puede, en realidad puede configurar el indicador correctamente y ahora lo que puedo lo que puedo hacer es decir, uh, la línea shebang que le dice a este script que use cosas desde la línea de comando, uh, uh, el intérprete automáticamente y luego también puedo hacerlo ejecutable de esta manera y ahora todo lo que tengo que hacer es extraer esa lógica y muy construya muy rápidamente una herramienta camaleónica y esto será extremadamente rápido porque , eh, estoy usando copiloto y sabe cómo construir bibliotecas que funcionan con herramientas camaleónicas, así que aquí vamos, podemos decir desde Funk Lodge dot math code import add reste, multiplique, divida perfecto y esto va a ser bastante simple porque voy a usar algo en Click llamado grupo y lo que hace un grupo de clic es que en realidad crea subcomandos para mí, así que podemos seguir las sugerencias y aquí tenemos diré que sabe crear una aplicación que use funciones de código matemático e incluso podríamos poner un poco, podemos decir que una aplicación no se compila porque es una aplicación CLI, las funciones de código matemático e incluso ponemos un pequeño ejemplo de documentación como ese y podemos incluso un pídele que me dé una invocación de cómo probablemente funcionaría bien, se vería así y ahora simplemente pasaría por aquí y agregaría y esto es tan simple que, eh, esencialmente debería escribir el código debería escribirse bien porque esto es realmente reductivo, no hay ninguna habilidad involucrada en esto, esto es solo un código repetitivo y mira, dice que los anuncios agregan dos números ahora y, si quiero, puedo hacerlo. como alguien con quien estás trabajando, dices, oye, gracias por darme eso, pero me gustaría un poco más, así que todo lo que haces es decir, está bien, démosle un poco más y luego puede pasar por aquí y puede decir un particular. sugerencia y, de hecho, incluso podríamos hacer eso aquí, podríamos decir allí, vamos a la derecha, podríamos, podríamos esencialmente incitarlo y decir Oye, quiero, quiero que se hagan otras cosas aquí, así que en este caso va a dar todo de la documentación y luego esta herramienta en particular da algunos de la documentación correcta y lo hice porque se lo dije ahora que hemos estado escribiendo mucho código, este es probablemente un buen punto de control para hacer el formato make, así que si paso por aquí y digo make o lo siento, make refactor podemos ver si falta algo, dice oh mira, no hemos usado restar aún no hemos usado multiplicar aún no hemos usado dividir está bien, así que necesito construir tres subcomandos más, no hay problema, sigamos adelante y hagámoslo así podemos decir en restar y nuevamente esto debería construirse restar dos números y mira, es lo suficientemente inteligente como para saber lo que voy a hacer en función de lo que hizo antes, eso es exactamente lo que yo haría multiplicar lo mismo que nosotros podemos pasar por aquí y podemos construir esto y podemos decir multiplicar allí podemos ir a dividir y construir esto y ahí vamos a dividir dos números perfectos y ahora podemos construir una herramienta de línea de comando eso es todo y porque ya hizo el uh el chamont más X debería ser trivial probar I pasaría por aquí, bueno, primero vamos a refactorizar, verifique dos veces si todo mi código está limpio, es perfecto, genial, ahora solo puedo decir hacer, puedo, puedo ejecutarlo, así que puedo decir limpiar el código matemático, ayuda, ahí vamos , vemos todas las diferentes opciones en De hecho, si levanto esto, incluso me muestra estas diferentes opciones. Podría limpiar eso si fuera necesario. ¿Por qué no? Hagamos esto un poco más limpio. Hagamos eso y ahí vamos. Eso es un poco más limpio y ahora puedo probarlo. solo puedo decir sumar dos y dos cuatro dividir qué tal 100 por 2. ahí lo tienes y también podríamos hacer una prueba de multiplicación para aplicar dos y cinco diez y luego podríamos restar para ver si arreglará una resta bug give us a negative number it does not bad so we have a nice little calculator here and I'm going to go ahead and check it in so get status get add and because I have a build system that is is checking all this stuff it should also build this uh that it should also do the test of the system and that's what this uh p articular piece of code is right here get up actions if we look at this is doing all the things same things that I did locally here and we can go back to this repo and we can look at this actions here and it's going to build out in fact a uh a test here and and verify that actually things work and what we could do as well is we could go to this CI pipeline here and we could say create status badge and we can actually just get some insight into into this build process uh in our in our readme file in fact I'll just put this at the very top and so that other people can see hey my code actually has been validated so this is really the essence of the building blocks in my opinion of python best practices that will just supercharge people's productivity and it's a new type of a workflow that's emerging in 2023. so the next thing that I'm going to do in our journey is go back to this environment and take a look at what else you can do so if if we again look at this function logic here it's in side of a directory called init.py we have math code here but you can build more than one kind of chameleon tool and if we scroll down here we see that in fact we have the CLI math code which which was actually very easy to build but we could try to build another chameleon tool that is slightly different uses a different framework and so let's go ahead and try that let's go ahead and build one called um with python fire which I don't know if I have it loaded but it's easy to to load if I if I go through here and I look for fire yes so it's not loaded so I'm going to go ahead and search uh for it uh python fire here we go so this is made by Google this is also kind of a cool little tool and so pythonfire is a simple way to to commit to create a chameleon tool so what does this say Okay python install fire okay let's do that so let's go ahead and put this over here and we'll put fire inside now take a look at this uh I'm going to go ahead and put this into devops section of my of my requ irements file there we go fire now how would I install this let me just show you how I personally do it I just say make make install and what it'll do is it'll it'll look through all my requirements and I'll find like the new one in this case it'll be pythonfire and then it's pretty easy there we go so it's it's installing zero five now how do I pin this I just say pip freeze grab fire and I just put this inside right so we know that in the future I should be able to use this that's it pretty pretty simple process that's why I don't understand people using really complex tools this is this is very simple so next I'm going to just create a file that will be similar to this other CLI so let's go ahead and do that we'll say touch um and we'll call this one CLI math or CLI fire math code.pi so this will be just a little bit different but close and so we can uh go ahead and refresh this there we go and we can put the prompt as well so we can say build out a commitment interface for the math functions in math code and we can put uses python fire to build a CLI and this will hopefully allow the pair programming tool to to to help us build out suggestions and I'm pretty confident I've actually not used it with the pair programming tool before but I'm pretty confident it'll it'll be very good and so I can say from uh there we go so it helped me do this prompt and then we can do Main and look at this this is not a lot of code here to to to build out a chameleon tool uh and that's what's kind of cool about python fire is that if you have the logic already created it can just uh essentially ingest it with probably the lowest amount of code possible uh and so how would we I believe this is correct we have this fired up fire Main it's possible that there's bugs but let's go ahead and refactor first and let's make sure that that that actually works it looks like it's potentially going to work and I'm also going to chamat it here and now let's do fire help whoa that's pretty cool h uh so you can see here that it it like it essentially just builds the the logic for us and now what I can do is I just um Can can say add two and two there we go so if you wanted to build the world's simplest command line tool that that uses the least amount of code from logic that you built this is pretty tough to beat there's pros and cons of both approaches but if you're going to be building let's say you know I don't know maybe like an SDK for something you know you're just you know coding really really fast this might be the tool to use to document an API for example so so really really cool tool here so now let's um go back again to to to to uh refactor so double check looking good and let's go ahead and uh check this in so we'll say get status get add okay commit adding python fire version now there is something that we're missing here that is probably something you should do in most projects is have a little bit of tests it's and so it's it's you know debatable whether you need to to invoke the chameleon tool to test you can or whether you just focus on the logic I would say that that's the most efficient way to test and so what we can do is I can build a test out really quick so if we say make tests for example notice that I'm not I'm not testing that other tool here right and so um II need to actually add it to my to my file so if I go to to test here notice that uh we're we're running these tests for these two libraries I'm going to add another one which is the um the funk logic right which is coverage equals and it's going to be funclogfunclog Funk Lodge okay let's make a test and it should say zero right so there's no testing at all inside of this so to fix this we can just create a test I'm going to say touch test and we can get into writing a test for this and we can say in fact funk lodge.py and here's again where copilot is is pretty amazing is if we go to our our test function here which is right here this is one of the best use cases for a tool li ke copilot is in that what it does is it actually can build out the test for us so build out tests for Funk logic math code funklogic and we'll say about all of them so we don't we we probably don't need Pi test uh we we could but I'm going to say from Funk Lodge and then basically the tests essentially get written for me so why would I not do this right this is great right and so we can actually get full test coverage just by doing that and then I can again say make refactor here which I think it might clean up the test function a little bit and then we can actually say make test now and so we can we can see that in fact I've now got 100 test coverage which is which is awesome right so so this this is a very robust way to to build things out and and I would say you can test the commanding tools as well but the the biggest bang for your buck is gonna gonna build out the test for the functions that you build out inside of uh your library so let's go ahead and add this again we'll say ge t status get add all this git commit adding make file or adding uh testing for logic so where where can we go from here so we've we've built out some some really neat little chameleon tools I think the next step would be to to go a little bit further and actually take the same style of code and build a web service out of it and so it's pretty easy to build a web service for for something using uh some kind of a framework and in fact there's a couple different ways that we could approach this the the first thing I'll do is I'll just make one called Web we'll call this web math code uh like that and let's see let's just use the same style uh yeah web webmath code let's try that and then again I can refresh this and we can close all these things to make it a little bit cleaner and let's take a look at what we have installed inside of the requirements do we have a web framework here I believe we let's look for fast API we do so we have fast API now since I'm working on Fast API and I haven 't there's nothing necessarily new in here might as well just just unpin it for a second and actually get the latest version here fast API and UV corn and let's actually install again let's just say make install perfect it's going to go out reach into fast API and uvcorn whatever the latest versions are and then I'm going to get those latest versions and then I'm going to put them in so let's go ahead and try that let's say pip freeze grip past DPI here we go perfect that I don't know if that was the same version I was using or not but who cares we're just double checking here you've UV corn there we go and we'll also grab that and put it in there Perfect Since now we can build out our our tool so let's go to web math code and we can just say at the at the top here we can say a small micro service well look how smart a copilot is so we but we don't want to use flask uses fast API so we have to in UV corn there we go so so we really do have to to be to be to be good about the um uh abou t the uh the things that we're building so all I need to do is import the logic and we can go here and uh from Fast API import fast API and then we can import as well we can say from math code we have these Library functions and now we can actually really quickly build out aa microservice using fast API and so one of the things that we can do is we have to to help it prompt a little bit and so we can say like you know build route build out routes for each import right imported function pretty pretty smart right so now now it's going to know oh that's all I got to do and we and look it there's not one of the nice things about fast API is is that it's just so simple to to take logic and put it into a piece of code look at this trivial to do this right and we do that trivial we do that divide and now we just have to invoke the app which should be the if under under name there we go and we can say hosts would be we can just say 0.0.0 uh zero and we should probably say Port 8000 I like port 8080 personally uh because it it works with a lot of defaults and now we just say python web math code SSO no module in the math code so we we have one problem which I could have figured out by looking at refactor because refactor the the nice thing about this is that it it can catch a lot of problems for us that were suggested so this is not perfect if you remember so what we need to do is we need to say from funk a lib um dot math code I believe that's the way that we want to do that and we can save this wait okay and we can do this make refactor and what did I oh func logic funklogic funk logic there we go yeah not sure why that thing is acting weird like that I'm going to just close it and open it back up again there we go that looks good now let's go ahead and refactor this and so now we see there's only a few more bugs and we can just say well yeah so what What's Happening Here is that we we should we should we should add something to the top of this like you know like maybe we can just say add route or subtract route or multiply routes or the you know divide route right that could that could be a good way to do it and yeah not sure why that's acting strange like that but uh we can do this there we go so now everything's clean and now if I just go through and I say Pi python web look at this now I can preview it and here's the beauty of using the um the the tool fast API or the framework fast API is if I go to Docs check this out I don't have to do anything I can test out my application and we can go right in here and just start playing around right two to execute look at this and if I want to I could even get this curl command and invoke it all you know really really simple way to test out your your code uh and your API so the tools that we have available for us are truly amazing um you know basic basically they're they're really um shocking how well uh we're able to actually build stuff out all using uh really this logic uh scenario where we we put stuff in side and then we we use these high level tools to to do all the heavy lifting for us and then it's not that much more difficult to then deploy this to a production environment which I'll do a little bit later so let's go ahead and uh check all this in and we can say get status here we say git ADD web web math code and we can say fast API service there we go so so pretty cool that we're able to do that much stuff that quickly so this is a simple example though let's let's actually build something a little more fun that will be less about um kind of toy apps and let's try to build something that's a little bit more realistic and so what we would need to do is go back to this funk logic here and actually try to build out some other kind of thing so one of the ways that we could do this is we could go first to the python uh the Pi Pi location here Logan says find install and publish python packages with the python package index you could look at like trending projects so we could see thing s like you know there's an API high energy physics you can kind of go through here play around look for projects like the one I like to play around with a little bit is Wikipedia here we go Wikipedia API you know you could you could search for things there's other ones that are kind of fun like geopi is another one so you just have to you know use use your imagination a little bit to to play around with uh with different things here um I would say the the Wikipedia could be a good one to to play around with because it's a nice uh it's a it's a nice place to to start in terms of prototyping stuff and so what we could do is is we could um look for key words uh inside of Wikipedia and I think that would be a good one to play around with and so I'm going to go ahead and say uh we'll say funk logic and we'll we'll call this uh like uh Wiki Wiki news keywords like that so Wiki news keywords and if we go into here we can refresh this wiki wiki news keywords so what what we could build out her e is something that can find news from Wikipedia and then get us some keywords as a result uh maybe even hashtags and so let's let's go ahead and do that so we'll say we're going to build out a library that finds news from Wikipedia and Returns the top keywords from the article yeah this looks pretty good so to start with we would say import Wikipedia and let's double check that I've got it installed and let's go to requirements let's look for Wikipedia Wikipedia Joe is not installed so I need to install it so let's let's go to we can call this section we can call this like a you know like text tools here so you can see yake is a keyword extractor and we could also put Wikipedia in here and so again really simple process what do I do the same thing I've been doing the whole time make install it's going to go ahead and grab the latest version of Wikipedia and put it inside of here and let's go ahead and find it okay now what we can do is we can say pip freeze grip Wikipedia and we've go t Wikipedia version and we just throw it in there right so that's nice and now the only other thing we need to do is start using this Library so we can actually say import Wikipedia and now we can say get Wiki so get the top 10 keywords from a Wikipedia article now does it do that I don't know if Wikipedia does that um let's let's try it out though so this is where it's it's good to use IPython to to to toy with something you have and also to do refactor so I'm gonna I'm gonna say make refactor just first does anything work and uh looks like there's a problem so look it so we already it gave us a bogus suggestion um and so what we what we need to do is is fix this a little bit and we we need to actually uh be a little bit better at directing it so we can say build a uh what what I don't know actually is does does Wikipedia have an issue or not now it is looking like this environment something's acting a little bit strange here so one of the things I'm going to do real quick is I'm goin g to just reboot this so this is a good thing to know about if you ever have issues inside of your environment is you can always just close it in this case uh it because it's a code space I can I can actually go to this environment here and I can look at my code space there we go and I can actually go ahead if I wanted to I could even stop it because it was acting weird and then I can actually um launch it again and it should just basically reboot itself so so you can control it and stop it and and if it's acting a little bit weird you know you can always like even destroy it if you want to because all of my code and my logic is inside of another environment so so I shouldn't really need to do anything for this this to uh to work so if we go back here we can um we can actually look at the pre-builds so if I go to code space pre-built here uh I believe that it was successful at one point so I should be able to I could even completely destroy this environment if I wanted to um if it's ac ting weird which which is great this is one of the the strong use cases for this so it's let's let's see if this works restart there we go so it stopped it and look restart is immediate because it's already been pre-built which is II think one of the really cool features of this and if this still had problems I would just delete the entire code space and because one is pre-built it'll just launch it again so you know sometimes you get weird bugs like that overriding bug who cares we can we can reproduce it because of a reproducible environment so let's double check whether that's um happens again or not I don't think it will but if it does we're prepared for it um let's see what happens if I just save it it doesn't doesn't look like it's acting weird anymore it just looks like it just needed to be rebooted so what I need to do is get a better prompt here I'm going to say build a well first let's let's look at let's look at Pi Pi and let's go to Wikipedia and let's see if there's like a news feature some somewhere inside of here so we can say Quick Start Wikipedia documentation and is there anything for for let's see get a Wikipedia search suggestion for a query if no oh that's interesting and search I guess we need to just play around with this right so look at this geosearch do do a geosearch for latitude longitude so it is important to get random get a random list of Wikipedia article titles huh that's interesting I like so I think we can work with this so I think the first thing I need to play around with is that I should look at search and if true returns results and suggestions if any so so let's let's compare the difference between these two in fact I don't even need to build anything out yet I can just use IPython so this is where I python is a is a huge tool for for trying new ideas out so I just want to say import Wikipedia look I can play around with this and the doc said Wikipedia search query so let's do a query and we can say I know the hot thing in the news right now is FTX right like are they going to indict or they have indicted are they going to do something with that founder and and and let's see if we can find some stuff about it and we can do this we can say Wikipedia search query results suggestion false what do we get ah there we go look we have all these suggestions here no what I don't know what happens if I say suggestions true what does that do uh so it just puts like some extra suggestions that are GTX I don't even know what that is but this let's sure let's let's uh I don't know the difference here is it that the suggestion is the last one maybe that's too tricky for me to handle I want to keep it simple and I'm gonna I'm gonna start with search and so we we can we can we can start with that so we can say like uh um here's the search but what I want to get the page now so we'll we'll say uh bankruptcy of FDX for example so we can say uh page equals and let's just grab one of these results here something like that and w e can say Wikipedia Dot Page I I'm assuming this is how it works Wikipedia Dot page and we just put in page oh there we go dot content there we go so we we can get the entire content of a page very very very easily so we can just build out several functions so build out uh return build a function that Returns the results of Wikipedia search right so that's that's easy right there's there's not much there's there's not much to do uh and in fact we're just almost wrapping something that that we don't even need to wrap but for the for the sake of building function let's do that and then we can build a function build a function that Returns the the entire content their content of a Wikipedia article and so in this case search term we we should be able to that looks that looks good and then let's let's get the um the top keywords from an article but but what we need to do is import this yake tool because yake can do this and so it Returns the top 10 keywords from from using using yake and s o is it smart enough yeah so so this yake tool can can get the the keywords out of here so the the way to try this out since we know that this term is is actually good the bankruptcy of FTX what we should be able to do is just pass that in there so let's um let's just copy that and let's get out of here let's say exit and we'll go to a python and we'll say um the import here so from uh funk logic dots Wiki Wiki news keywords import all we say who that shows us what's important and now we can just say page is is equal to which we can get the syn the the Auto completion from IPython here and then I can say result is equal to uh Wiki keywords and then that page page and we look at results there we go we've got the keywords out of here so kind of a cool little service um inside of here that we that we've been able to to find and we could do we could do all kinds of all kinds of fun things with it and I don't know build out um other natural language processing things like uh you know sentim ent analysis or you know entity extraction and all kinds of really cool stuff but we can start off we can start off with with this first and it looks pretty good and we can go back now to to this and just say make tests that looks good we can add some tests in the future we could say make refactor and so now uh it would be pretty easy to just build this into a chameleon tool so what we can do is is build this out into a kind of the same style that I did before we'll say CLI and we'll call this Wiki Wiki news or wiki wiki keywords Wiki keywords Dot py and then uh we can go into here we can do the same prompts we can say from now now it's a good question if we want to move quickly the the quickest possible way to build this out would probably be python fire but if we want to build something that's a little more like nice and pretty we can also use uh The Click so what we'll just say you know you use click to build out a CLI for Wiki Wikipedia Wiki news keywords okay and so we'll do the s ame thing we'll add a shebang line here like that and we can say chamat plus X here and we can say import click we don't need to import Wikipedia we just need to say from this I like I like that it's shortened it as a good suggestion actually let's go ahead and do that and then we can just build out a click group to build a click group so you got to prompt it and we could do example we can say search for keywords words in a Wikipedia article and then we'll do example here like this and Wiki keywords search python or we know that there's another one we could do Wiki keyword search FTX bankruptcy there you go like that and let's go ahead and do this so we'll build out search so this will be the first one so we can just search anything in Wikipedia and by Def we should uh I would say do a default which we so type would be string default would be um FTX bankruptcy because we know that there's a result for that and we can put it inside of here there we go that looks good and then we can als o build out a uh we can do keyword keywords that for the keywords keyword s there we go here we go search term FTX bankruptcy looks good and we can say return now now here's where I would want to prompt it a little bit so so first uh I'm going to add some documentation for this real quick we're going to say example here right so that there we go and then I also can add an example here example there we go but I'm going to actually I'm gonna actually make it a little bit fancier and I'm gonna I'm gonna do a limit and so I want to say I want to limit the amount of keywords exactly default but let's just do three three keywords and um could could we even tweak it a little bit and say you know return the top limit keywords in color green sure so there's the there's the the keywords for keyword and keywords limit and we can do that and we can we can build out and basically invoke it and there we go so we don't need to do it like that we we could oh that is interesting though the way that the y invoke it like that sure let's let's do that um and let's go ahead and uh I think I already to modded it but just in case Wiki keywords let's run it quickly Wiki keywords help there we go that looks good we can also do a make refactor real quick just double check I didn't put any bugs in there cleans it up oh we we see like we see some warnings which in an error look we do have some problems so let's fix this real quick so we have live 41 is keywords we just changed this to CLI whoops CLI like that and then also limit 42 uh uh because this needs to be passed into to this limit there we go right so refactor again helped us find bugs undefined variable keywords um which is on line 49 oh because it's now keyword CLI there we go make refactor perfect and now I can say get status it looks good let's check all this in git commit adding CLI push that and now let's test out our tool help that works if we look for keywords by default it'll do the FTX bankruptcy there we go so the three top ke ywords are are FTX November and Alameda research so at least the first two make a lot of sense or the the first and the third like FTX and Alameda research those are the two places that were invoked in there now if I did wanted to put a new keyword we could we could put in uh Enron for example and so Enron didn't match so we we could probably you know clean things up uh I don't know fraud or we we we're we we could add new things in here there we go so this this is showing us kind of results of different things that we could search for um straight out of Oz I don't know what that is let's put that in there the three keywords there we go II don't know exactly it must be some kind of musical or something but basically we're able to actually use this pretty quickly to to build out uh Solutions here so the tool for using cloud-based environments for AWS is something called Cloud9 and that's actually kind of a fun one to to play around with if you want to build out things in a cloud-based e nvironment another option for building out serverless based things is to just directly use the console in AWS but let's let's go ahead and use both so the first thing that I'm going to do is I'm going to create a new environment and we'll call this um python functions and we can put a documentation here that says you know python functions using Cloud9 and code whisper so AWS does have their own code pair programming tool as well called code whisper and we can actually play around with it and I'm gonna I'm gonna go ahead and select the large this looks like a good good machine to use and just say create so it's going to go through and it's going to create this large environment um and while this is is running uh what I can do as well is uh click it which is python functions and it will it will show me this this preview window so if I want to use some of my same code here I would have to actually do only a very very tiny amount of changes one of the things I'll have to do is actually add oh field oh this so this environment is not available so this particular um machine was not available which does happen sometimes which is kind of weird but uh what I could do instead is is create a new one we'll call this one python functions 20 2022 and we'll call this Cloud9 Plus Code whisper do it again yeah sometimes I you you get this there could be a there could be like a an issue with a lot of people using a particular type of instance it would be it would be great if they told you that beforehand but one of the ways you can get around that is to just pick a different one and probably I don't think a lot of people are using one of these large ones so I'm going to grab I don't know like a 16 gig four core machine let's try that M4 XL large and let's see if that one works if if it doesn't work II doubt it it won't work but if it doesn't I could always just use one I've already got created so we'll let this thing spin up for a second I will need to go to GitHub to add the keys so that I can actually build out in this environment uh and we can actually do that by opening up another window to go to my GitHub account while that's spinning up and I'm going to go to settings SSH and gpg keys and create a new one and we'll call This Cloud nine functions and if we go to this sorry to this environment uh we'll close that one there we go successfully created it so great great it was able to create it so we're we're all I need to do now to to Port my code over here is just type in SSH Keygen Dash T RSA and it will print out this key let's go ahead and do that and let's go ahead and put this into this environment here it's going to ask me to put in some codes here so I'm going to go ahead and do that uh and we've got let's see here uh let's try it again add this I'm going to go ahead and add this in here for some reason my my GitHub is not not exactly working so I'm gonna I'm just gonna pull this into another screen for a second and I'm gonna just do like aa two Factor o ff version and we'll do it we'll do it that way okay I was able to get that in and that that the keys in there so so now uh all I have to do is go to this repo say go to repository it'll open up a new one go to code go to the SSH section here and copy that and now if I go into this environment I can just say git clone and we just clone this into this environment so so pretty straightforward actually to use Cloud9 that's the only thing there's only one other thing we need to do which is which is pretty simple which is create a virtual environment so again this is where I know there's a lot of I think misinformation out there about the python standard Library python standard Library includes every single tool you need to install packages to work on things here's a great example if I just type in python3 dash mve and V and I create a virtual environment this is included in Python you don't need to download some other tool from some company or from some other open source project if you wan t to do that great but at least understand how it actually works which is it comes with python we create python virtual environment now if I want to invoke that python virtual environment over and over again what do I do pretty straightforward all you have to do is you could actually copy this into your bashrc so let's go ahead and go to bashrc here and we'll go to the bottom and we just put in you know each time I open the shell Source virtual EnV right so really simple process here Source tilde.vnv then activate never again don't have to worry about it I'm all set there's a one-to-one mapping for this particular cloud-based environment and what it is I'm doing how can we how can we verify all I have to do is this new terminal right and inside of this terminal look what we have virtual environments and if I say which python we can see this is in installed if I say which pip pip is installed there's nothing to do there's no other tool we need if you want to use other tools great you do not need other tools other than the python standard Library I'm trying to evangelize this as much as I can because there's a lot of misinformation out there about you you need some other tool like conda like poetry if you want to use those tools go for it you do not need them okay so next I'm going to go into here and I'm going to say make make all so what would make all will do is that we can go to the make file and look at this what does all do installs lens test format deployed not deployed there's nothing yet we will we will get to that in a second but there's no there's no deploy step let's just save me a call what happens is it's going to go through it's going to install those packages so this is the other a really amazing thing about this particular environment is that it should be pretty straightforward to to to figure out what's going on here unless there is a bug with aa installation we can debug this very simply though because it does see that there's an error here it says look ignore the following versions blah blah blah blah no matching distribution pound found for python one five right so there's some kind of weird problem with a dependency that we don't even care about so pretty easy to fix this though let's go ahead and fix this so it's seen pandas it looks like it came from Jupiter 1.0 so how do we fix this we just go here and we find pandas and we just take this out right so and we take this out so so far I haven't even used these libraries and I may not even need to use them so I could just punt but for fun let's put these back in how do I fix this I just say make install make install and this should grab whatever the latest version is of these two libraries now in this case it says no matching distribution file for numpy so these three libraries are I call them I call this the JC Penney's Suite which is uh which is Jupiter pandas and conda those are typically packaged together they can really cause a lot of problems because of weird things that they do but in this case I should be able to get through this by just unpinning it picking up the latest versions there we go now second learn has got a problem we can just fix all these in fact probably all the data science libraries are all jacked up and we can just fix all of them very simply by just re-running this particular installation right here so it's actually kind of a good exercise to to see this of course I haven't even used these libraries yet so I could just if there's a problem just dump them because we don't here we go ml flow right we have another one so so you do get this sometimes and this is the advantage though of using uh like pinning and unpinning and all that kind of stuff is that you can get feedback right the feedback tells you exactly what it is that you're doing in fact I'm gonna just maybe get rid of ml flow because I know for a fact I'm not going to use it right now but let's see if this builds real quick though case collecting torch looking good here it' s installing this what this could also highlight is that it may be a good idea to remove some of these dependencies because I'm not really using them uh for for now and so that's what I probably will do um if there's continued to be issues I mean we're installing a lot of things that I haven't yet used um but let's see if this finishes here like Nvidia stuff for example which I think is coming from I don't know where that's coming from actually maybe that's maybe that's coming from pytorch or something like that look so I installed so much software there's no space left on the device so this is fortunately a pretty easy one to fix if we just go to um uh resize uh resize Cloud9 here we we can find this script that one of my friends wrote and we could just copy it and and uh we just go here and we just resize it whoops we can do this so so the script essentially just runs A bash command that will will resize our environments which is right here there you go now we can resize this thing p erfect and and then if we just do DF Dash h we see that there's tons of room right 50 53 gigs now available because I think it resized it to 60. just go again make install so it's actually great to see little weird issues happen in a different environment because it shows you how you again you don't need specialized tools you just need the python standard library to fix uh I would say 99.999999 of problems you don't need other tools start with a standard Library start with requirements start with a virtual environment and you can fix almost everything and uh here we are we're able to install just a ton and ton of above tools here this is probably one of the most complex setups for different collection of libraries you could even consider and in fact we have we have we have no issues and let's just leave this uh going here and and we can see that looks like it's getting close now it's installing some Nvidia stuff it would be kind of neat if Cloud9 was able to do GPU I it does not have t hat capability yet which is something that would be will be would be nice to do okay now it's doing tensorflow again we have just an amazing amount of libraries here and we're able to get through even weird complex dependency Problems by using the python standard Library okay installing installing installing there we go and perfect looks like uh every single thing was was able to to be installed here with pin dependencies uh that we're able to to fix now it's doing this last thing installing a few other things there are some warnings here which we don't necessarily care about and here we go I think it's getting to the end right because I think it's Wikipedia is maybe the last installation so we installed 47 ish you know in the late the late 40s packages that which it's unlikely that most python projects would even have this much and these are very exotic tools some of them and still we don't have problems I think that's the amazing thing about about uh just the regular python standard library and why it is a great tool and one of the things you can do to debug things you know if you can say um top and just see what's happening look we see pip is still cranking right here and it's and it's setup is installing Wikipedia I'm not sure why Wikipedia is taking that long but you can always if you're having issues just do the top command and take a look at it and see why it's hanging which it is strange that it's taking that much time for just Wikipedia we could also double check oh there we go looks like it's diminishing it's getting done um now oh there we go whisper installing this the other thing you can do that's kind of fun when you're when you're looking at like a huge install like this is that you can also double check the version of python so it's three seven so three seven is kind of an old version that could be I think it's actually being deprecated so that could could be an issue here why why the the installation is is taking there were some issues earlier that newer versions of the Python probably would be better but regardless we're able to it appears get everything working right so we got it we got everything working now one tool I do like to install that that might as well install in here is pseudo uh yum install h-top and H top is kind of fun because it it's just like a slightly fancier version of top right so you just get a little bit better view of like the different cores and how much memory is available and things like that and it depending on what it is you're doing building containers Etc it can be it can be useful to build so we're all set we got everything installed just as I expected now let's take a quick tour of this cloud-based environment and show why it's so helpful for building out functions in Python uh so one of the things we can do is go over here to AWS if we select AWS it actually has surprisingly a lot of of little tools available so one of them is this see this right here code whisper so it's a it's essentially equi valent to AWS co-pilot although it's in preview it's not fully baked out so there could be some weird issues with Copilot um but but we can use it there there's also developer tools so if we wanted to deploy our application to like like a Oedipus Lambda using cdk we could do that in fact we may have time to to cover that and then as well we can go to other parts of AWS like Lambda and we can just make a function right here we could create a Lambda Sam application and edit it locally if we wanted to which is which is actually pretty cool so maybe we should start there let's go ahead and do that let's go ahead and say create Sam application and it's going to ask us what runtime to use now here because we're already inside of a 37 environment my recommendation would be to use three seven and you can choose image here and we can just say a basic hello world application and it's going to say well where do you want to put that we can select right here and we can call this thing something so we can we can just say like Lambda let's just call this um functions or or funk Funk Lambda how about that funk Lambda let's do that all right and so this will now build this out locally here inside of my application and look we can see here that it will include some documentation as well about how to actually deal with this uh in terms of deploying it documentation Etc and this is all in the readme so great thanks for for doing that for me let's go back to our Explorer here and let's look here we go Funk Lambda we have another application here and what we can do is see that there is a whole environment here for us to play around with let's go ahead and read the readme here so let's go ahead and take that first and we can see here that it says this project contains source code there's a hello world that has the Lambda function and the project Docker file there's the events here that allows us to invoke it there's unit tests also inside of here and there's a template dot yaml as well an d so it even walks us through step by step all the different things that we would need to do so it says to build and deploy for the first time we'll just do Sam build Sam deploy guided and then it will it will basically use infrastructure as code as well for us to to build this out which is which is really really cool um and sort of build your application with Sam build you just say sam build and uh we can we can do all the stuff and you can even invoke it locally so this is kind of cool so one thing I'm going to change though is that because I'm going to be building out this inside of this environment um I should potentially tweak things a little bit here because we have a separate set of requirements right um and so I believe it will talk about that in the toolkit here it will say something about that it will say about the virtual environments here we go it says it says the PIP install Pi test the tests are defined in the test use pip to install it you can find more information so so it does give us some Clues here that you know depending on what it is we want to do now because this is a specialized environment I probably would want to deactivate my virtual environment if I'm going to work in this one which is pretty easy to do we can just do this we can say deactivate to to to deactivate a virtual environment and then I can CD into this funk Lambda and from here I could more treat this like an isolated environment and in fact inside of the hello world here this is really the the gist of everything that we have and what I can do is actually look at this requirements to see what's what's in here it's just request if we look at the app here we can see actually the the the the function so we're again to the point where a function is all that's necessary and you can see that the event is a dictionary the context is is shows you like the runtime uh methods and attributes and and you can actually return this with an API Gateway if you want but this is essentially just a hello world uh type function so I'm gonna I'm gonna clean this up a little bit because I don't want this to be a lot of code so I'm going to just delete that and we're just going to say we're going to make a Marco Polo function and we'll just give Marco Polo Lambda which is kind of a fun one to play around with is all I need to do to to play around with this one is I just need to say if the event name is equal to Marco return back Polo otherwise just return back no right so we can keep it really simple right like this is a very very simple Lambda function um and I don't even know if we need requests but we we can we can we can put in here I don't I don't know why we would need that um I'm actually not going to import that let's let's just do this but but basically uh now in order to invoke this what I should do is uh I should actually do a do a pip install the way that they're telling me to do the PIP install so let's let's just close a bunch of things up here and let's let's actually follow the the guide that they're going to tell me and uh and and so the guide that they're going to tell me is we can do this it says this project contains source code blah blah blah blah the code for this will base differ based on the runtime now I guess I could I could activate I could actually activate my virtual environment because I don't think that's going to hurt me to to activate it so I'm going to go go ahead and do that again all I need to do to reactivate is just say um just type in bash right and then we're back um and so you can see here that we can go to this one this readme and we'll just follow step by step what it wants us to do so first step we're going to type in Sam build like that there we go so it says template not found so I need to go up one level Sam build and there we go so it's going to go down it's going to pull a docker uh container image it's going to pull a Docker image that will allow us to to invoke this within this particular environment and that is one of the cool things about using containers is it lets you do the essentially in invoke things in this particular environment and we see that it's actually pulling these requirements there so I can use this requirements file here as the thing that's going to get installed right there's there's not a lot actually that's going to go on there and now the next thing look it says the commands you can use next it even tells us we could invoke it if we wanted to and let's let's do that let's let's let's what happens if we do that we can validate the Sam function so we could say sam validate looks good right and then we could do Sam local invoke uh so it's going to go ahead and invoke this thing and it says now we would need to pass in a payload here let's see if we can copy a payload here we go you would do I see you need to give it the events that live in here this events.json right and you could you could actually pass in a payload here now this is this is like the complexity around that is a little more than I want to deal with I don't I don't want to deal with that thing if you needed to you can but um I'm just going to deploy it then test it um although you so so we we could curl it right we could do it that way but I think it would be easier to just deploy it because it's not very complicated so let's just do this we'll do Sam deploy guided and we can we can do this thing there we go and um setting the default arguments we can call this one a Marco Polo December 13th and we just go through it says confirm the changes yes we want to deploy yes we want to give it permission no we'll just yes we don't care it doesn't need to to have argumentation save the config file create managed repositories for all functions there you go so it should it did have one issue here which it says managed repositories will be depleted looking for resources needed a different default S3 bucket can be said image repository is not found Management Properties will depleted create managed for all functions so maybe we could do it one more time and this time don't say yes so we'll just say Marco Polo 13. 2022 and we can just say I think I can just actually say default may not have no oh you have to just play around with these real quick Marco Polo 13202 let's go through here confirm changes before deploy allow I am roll disable roll back no and we can say yes it's okay save arguments yes yes no so we'll just we'll try that maybe that will fix it ECI repository for hello world function so maybe because that was an issue before what I could do to hack this is I could go to ECR real quick and we could go to this and make a new one real quick and call this Marco Polo 2022 let's see if that works there we go and we can go back to our vermints and say Marco polo two zero to two does that work oh it needs a different you it needs the actual URI here which is annoying which is this one which is the URI hold on Marco Polo that one that it's going to need that URI so go back one more time go Marco Polo two zero two two or two three there confirmed changes yes okay last time created no let's try that there we go so it took a little bit of back and forth here to get this working so it's it should be pushing this to to this container registry and so if we go to this here it once it's deployed and it should be fast because it's in the same data center as AWS Lambda it should be able to to push this into this environment you don't have to use this method I mean you could just go to the console and just play around with it the advantage of building it like this is that it's that it's actually reproducible and that you could put in all of the dependencies all your code in here and build in a container and test it out locally now this did have one problem failed to create update the error occurred so anyway there's some there's some issue in doing deploying it this way not not 100 sure why that that issue is there but you don't need to to even do this because you can also just go to Lambda and do it yourself so we can even just look at the code here and we can just steal this code basically we just grab this and let's go to the console real quick and go to Lambda Lambda here yeah deployment always has weird stuff that happens and who knows what the issues are we'll call this m P 2023 let's try to do that and just make this function I find myself if I do need to write lambdas a little bit gravatory towards the console for prototyping just because those weird issues with like setting everything up are lessened a little bit in in first playing around with this so again I just do this right it's go Marco Polo and I could deploy it it's trivial a lot quicker than what I was just doing to figure test events we'll call this uh Marco and uh I could just put in the name here Marco and if we save it we we test it out there we go Marco Polo right so we we got this thing working no what is cool is I can go back now to to this environment um and let's just close al l this stuff and this is maybe like kind of a fun thing to do is if I go back to this here uh one of the things that I can do is I go back to AWS and if we look in fact for what did I call this thing I call it mp20 3 I think I might need to to refresh this and I don't remember how you refresh it but let's just do that let's just refresh this thing go back to this Explorer find Lambda and we should be able to see that Lambda right and I can just invoke on AWS you don't have to create it locally inside of your you can actually just play with it here and you could just say hello world like that's and we can do the same thing we're going to say name here Marco and we can invoke it right there we go and if we put in a different name we can see that actually so so you I think personally that's one of the quickest ways to just really really quickly build something no one of the things you can do though as well to to play around with this that's kind of fun is if you go here you can actually d ownload it which might be a quicker way to to build it actually as we saw the the default way is a little clumsy if we go to this uh look is downloading it into my environment now which which is pretty cool look at this MP there we go and so I can actually just play around with it right here so there's there's you know pros and cons to each approach to building functions but a trivial way to to build it out is to actually use the the default you know tools that are available now the other thing that you can do that's kind of fun with functions once you start going into the cloud is there's another service called Step functions and with step functions you actually can very easily create a state machine and actually invoke that function that I just did earlier so if I go here and I just grab this invoke we we could actually like wrap it all up into aa nice little system here we can just say like you know basically call call Marco Polo here we can go to the Lambda which would show up righ t here we can say mp2023 and that's it we can just invoke it and now this is kind of even a cleaner way to do this because uh we we could actually just say next we could even check this into our project if we wanted to we'll just say next year and we just call this MP two zero two three uh step whatever I want to call it create the state machine and now it's trivial to actually just put a payload inside of here and we can just try this real quick we can say name and we could just say Marco and this will invoke it there we go and if we look at the details we we actually can see that it was able to be successfully called and we can look at the the task was successful right so we have really good instrumentation here that's that's the reason why this is kind of fun is that we can actually see everything the step details uh inside of here let's refresh it real quick it's acting weird if I click on this here we should be able to say start finish execution succeeded there you go there's the output and we could say execution started and look here's the input right so we we can completely 100 reproduce this even further what we can do that's that's pretty cool is that we can I believe invoke it from here let's see if we see step functions inside of here step functions yep there we go and we can look at the um let's again refresh this page real quick and then let's go back to AWS and let's go to set functions and what do we call mp220223 let's go ahead and say start execution again trivial to to do we just do this right we just say name Marco and you could obviously chain lots of lambdas together and there we go execution started and we could go back to the Lambda uh or back to the step function and it should show us there we go another one has actually just been invoked and if we go to the input it might even tell us where it came from I'm not sure if it will tell us that but anyway we did we did a different one inside of here the other thing that we can do that's kind of c ool is we can also just do it from the CLI so we could say AWS step step functions and do Dash's help and can we even invoke it I believe step functions let's look at the docs real quick here let's go to this documentation let's go over here and installation we're updating the latest versions of the CLI and we can do a search for step functions CLI see if we can find some docs on this using the examples there should be AWS step functions command line sometimes Google is is better and we can say list State machines and let's see which version is this you're viewing older so let's look at the to view the page for the version two we'll go here so list State machines so we should I think be able to just do that first so we we can do we can do list State machines there we go so we can list all the different state machines available and then to invoke it if we want to invoke it let's go back here and we want to say available commands I think it would be start execution State machine start ex ecution and the name of the execution or the RN I think it's just going to need that and then the input the string that contains so so we can we can we can essentially create this so we can say uh step function and we can do the the first part which is the Steep machine iron which is that which should be this one right here MP the steam machine orange so it should be that here and then we have to do the payload which we know should be Marco Polo which should be that so something like this would be Dash input the string that contains adjacent for the execution I think it's going to be something like this we would say um name Marco and we would do Dash input something like this if I don't get it right not too worried about it I think is it this air invalid choice anyway it's it's something similar you can also invoke it I always have to Google it and debug it a little bit but the nutshell is that you can completely build out functions in a chameleon environment using AWS Cloud9 all right so this is a good place for a break when I get back what I will do is then do shift over to deploying microservices using uh what we built earlier and so I'll show how you can actually package this up with a Docker container build out your whole environments using a cloud-based tool and then push that into production then you have full working continuous deployment for your system all right let's take a 15 minute break and be back then foreign foreign foreign okay thank you wait we're up to 14 000. my second house called 81 wow foreign laughs oh oh God yo man hilarious stuff here yeah so I would say basically a lot of the principles the the staff covering the the principles of devops is included a lot of these same deeply the same kind of artifact ever foreign okay we have some questions here that I'm going to push to the slide area first one is I'm new to Python and I was unsure of how the bracket colon limit worked so the idea here is that with python lists you can slice them and so you can basically pull the front of it off or the back of it off or you can slice a range from a list and so since the items were coming back as a list it's an easy way to get the limit is to just do a slice of that right so the first you know five items would be the the limit of five or the first ten items would be a limit of of 10. and so that's a nice little trick to know about in Python you can read about the slicing of lists in the python documentation okay so next question here how much of what you're showing today is in the book we're reviewed for prep so the um a lot of the the build script type things are actually covered so if you go to python for devops book or if you go to the um the Practical mlops books that I've written for O'Reilly those I Do cover quite a bit this concept of reprodu reproducible environments the current book that I'm writing which is implementing Emma lops in the Enterprise is also going to heavily cover code spaces and some of the things that I'm cov ering now and so I do have a little bit of that actually built into the um the rough drafts that are that are put on to the O'Reilly platform so yeah I would say the last several books I've written for O'Reilly all have variations of this inside of there okay next question here is that it looks like you're using visual code on Linux from within a Google Chrome tab is that correct yeah so that's exactly the point in my opinion of why this environment is so amazing is that you only need a Chrome tab so you could have a very low powered computer you could have a Chromebook right you could have you know extremely weak computer but the cloud-based resource itself is running uh very powerful things like five thousand dollar gpus or 16 core machines whatever it is that you need to do so this is really the advantage of using the cloud-based development environments and of course you can do it from anywhere right you can be in a coffee shop you can be the library you can be a school you can be at work you and you can just quickly bring up your environment so I think there's just so many advantages to using a web-based browser to develop and you can see things are just getting better and better and it really is the standard I think that a lot of people are are using for for doing development all right um great questions here and keep them coming I'm gonna I'm Gonna Keep moving down with functions here and so what I also wanted to cover is that you know we built the the function with the AWS Lambda but you can do the same thing with the other Cloud platforms you can do it with Azure you can do it with gcp right they're all great places to develop in fact let's start with gcp because it's it's got one of the more fun ones to to build functions with and so all I need to do is just type in Cloud functions instead of gcp and it's very similar process we can go to create functions here and inside of here we can choose between the first generation or the second generation I guess I' m always a sucker for the latest version so let's let's build on the second generation and we can just call this whatever it is we want to call it now what I could do is actually reuse a lot of the code I already wrote so why don't we do that let's let's remember what we called our other function over here and let's actually just essentially crib this code from this environment I think it was like Wiki keywords so let's do that let's build this we'll call this Wiki um keywords oh they must be lowercase and hyphens okay so we'll do that we'll say Wiki key words there we go so wiki wiki keywords in fact we don't need a hyphen there that looks good enough Wiki keywords and we're going to do unauthenticated notifications and we're going to go to next here we have to pick the runtime so we can pick anything from.net go Java python PHP Ruby a lot of stuff here we're going to pick a python the latest version python 10 and here's where things get a little bit more fun in some sense in that thi s environment is I think a little more straightforward for building things with dependencies and notice again here look there's just requirements so you don't need fancy tools we don't need to so install some super fancy like third-party installer you just put the requirements inside of here and look this has this particular setup here now a couple things to point out is that I can actually run this and edit it within Visual Studio code as well and we could try that that actually might be kind of fun but first let's get something working and so this is going to use the functions framework here so let's just get rid of this stuff which I just don't want um and we we actually can um tweak this a little bit here's the entry point hello http I guess that'll work and so now I just need to copy some of this code some of this logic here so I would just need to go to this thing and go to the wiki keywords here and we could just put all these in there like that we could just do that so this wil l definitely make things more complex and uh let's throw that all in there so we got that we got that we get that no requirements I need to then follow my requirements so let's go to that requirements file and we can go to these two tools here we can put those like that and we go back to this and so I think all we would need to do is we would just we could keep it the same if request in Json we do that and so we would just take that payload and that would be the search term essentially now this will be a little bit trickier because when you're in an environment like this it's just it's not great to to build out code because of spacing it's it's a it's a clumsy environment but we could look again at our our example here and we could do something like that and we could say I think some something like this could could work so if we go back here we could say keyword so it's going to be something like this I mean this code is so convoluted that I might even need to just build like aa um lik e a like a gcp example or something like that here local example just just so I can get a proper editor because it it could really be tricky to debug and so if here we go gcp example so at least in so you can see it's like just a mess right so I could say uh you know make refactor here in fact I could even get some ideas here so it says cannot parse line 35 yeah just as I suspected like there's all kinds of weird formatting issues with all this stuff like definitely annoying to deal with this kind of stuff see this is super annoying here we can go there we can delete this we can delete that and then we can say for keyword and keywords um I don't know like what is what do they typically want you to do inside of this they want you to maybe like return keywords maybe or just return keywords how about that just return keywords that so if I do a format we'll format it for me so still got a formatting error online um line 29 which is this one so is the issue that looks better make refactor t here we go uh uh undefined functions undefined variable so and so this would be Wiki keywords we don't need that that was not helpful but we are able to to figure out some bugs here and then the name would be this would be search term right so so this does help us quite a bit to to build this out now again I can't actually install this and and do it locally as well which I've done in the past but uh function Frameworks request unused request args so yeah I don't think we need that we can get rid of that and we can do one more time so it's only missing the this functions framework which I guess I could install um and I if we go to this I think it will tell us if we go to the the functions framework gcp I think it'll show us how to pip install it Cloud functions here go to Quick Start and they should tell you how to do local development there we go so local development local developments and we go to python there we go we just installed that so we can go to this real quick to the require ments file and we can put this maybe web we'll call it web and we can just say make install so we can test it in both locations we can test it on here and we can test it out inside of gcp they both seem fun and I guess we can pin it once I've got it installed so pip freeze grip functions framework there we go so we just put this pinned version here rights into that there we go looks good so now that I've got this example looks like it probably works if I do a make it or actually make lints sorry a kill that and make refactor there should be no bugs yeah no bugs in this code so I can just grab this entire example here paste it into here in theory this should work in theory let's see here so I'm going to deploy now while that's deploying why don't we also test out the local version so I can read the documentation again which is going to be where was that documentation running functions here it is let's go to this documentation and so it tells me all this tells me all this so it says do y ou replace this with your method's name so functions framework Dash Target hmm calling the local function so calling the function directly running functions framework so it looks like it's something like this it looks like coin local functions hmm II don't 100 understand how to do it maybe I don't need it let's let's first see if it'll deploy and if I need to run it locally I will but I probably do not need to to run this locally so it's going to build this cloud service and once it is deployed which it is in theory we should be able to test it by clicking on testing and we can pass in a payload which in this case I think we we knew that FTX was was a search term look it even gives us this curl command and so we can test it out in Cloud shell which is which is pretty cool so it lets us test this out just using a curl Command right here oh it already did that whoops let's close it let's test it again so I guess it injects it there you go automatically I would be surprised if this works I'm always skeptical of my code but we're about to find out yeah didn't work so so we can debug this thing by going to the logs and we should be able to see why there was an issue with it um unknown error so text payload so it's hard to unsupported system call is it very likely you can safely ignore this Wiki keywords so it says Wiki keywords labels air detected and Wiki keywords Jason payload air events here we go what does it say s resource hard to know air detected air events it's it's not giving me good logs here it's a little bit tricky to to to figure out so maybe this is too complex this might be too complex of a of a script to just throw in there um we we could download it though and I'm just curious if I download it what it will give me I can probably throw that into our I just downloads the the file so let's try to get it ready locally then so so I had some issues and according to this you can do this you can say Frameworks function Target with your functions method name now what I don't see here is before running a function using Frameworks you need to specify both the type and the name of the function that that you want to to to call so let's see if we can figure out how to do this it says Cloud functions running Frameworks hcp functions here we go here's our code here next steps here's a tutorial and deploying you can deploy it there triggering the function so you can also trigger it with Gen 2 here and you can and you can format it so yeah we I mean I guess I guess there's a bunch of different things we could do to to debug this I mean we could start with if request and name is equal to we could we could we could basically um either either do a Hello World or or just start again let's start again for a second let's just make it a new one that's just a hello world and we'll do generation two and we'll call this hw2 unauthenticated and let's pick python 310. and in this case we should just be like again it'll just take a payload called hello world let's let's just get that working that's how I typically would debug something as does anything work I should just take a second to to invoke it the um and we can look at the details here look at the source code which is which is kind of nice we can look at the variables see if there's anything inside of here the trigger in this case to be web the logs and the testing so while that's deploying I could just really quickly try to run that other command here really quick II know for sure I could look at the if it would be nice if the um if they showed me the documentation in GitHub and that's what I'm going to try to find out real quick is GitHub here we go so we've got Cloud functions framework python this is what I'm caring about so okay we do this it says this quick start so here's a hello world oh so create a main dot file with the following content so let's try this out locally inside of our environment let's let's literally copy this example so I'm going to say make their gcp funk like th is and I'm a CD into there and now I'm going to say touch main.py so it looks like it does need to be called um mean.py and then if we just copy this example here into that like that's we should be able to do that right so we should be able to say functions Target hello debug and does it work so yeah it does work that's pretty pretty simple right not bad and then what else does it say to debug it is that you can curl Quick Start yeah they're really easy and you can curl like that as well so where things get a little bit more complex is if you if you need to post which is what which we would need to do so um in this chart Cloud events function you you as a cloud event parameter and so that's another way to call it air handling Pub sub so this is this has got a lot of really cool stuff for you to build it uh inside of here but let's go back to this thing really quick to test it out so we can say test out on cloud shell and it's going to do hello world and not sure why that's not showing up here post method huh interesting how it didn't it actually didn't um it didn't put the commands in here inside to actually test it out I can refresh it real quick and see if that fixes it but but you you can invoke it in this console here as well you should be able to there we go so finally I did it I don't know why that wasn't showing up and if we invoke it there you go hello world that works so we know we know how the world Works where it gets more complex and we and we see that that's the the payload so you we we could probably get our other version running locally let's let's are we if I'm brave I can try it so we know that it looked like this so let's let's grab this here let's kill this and then let's go back to this main here and let's just throw it all in there and what do we got import functions framework and and then if we run it again Target would be hello http here we go so what's wrong with this there's some bug in this code we might be able to figure it out well local variable search term reference before an assignment there we go so that might be the issue so search term oh so if request.json well in that case though that's because we're not sending it at a payload uh and so we would need to do another terminal here and if we if we copied the other example like this and we just tweak it a little bit should look kind of kind of like this so let's go to this um environment here we'll just call it like curl curl it dot sh like that and we just tweak it a little bit so so we we know it's going to be instead it's going to be um localhost 8080 right so it would be curl post local local hosts and I think the framework told us this I think it told us right I think it said yeah local hosts 8080 like that so we can go back to this localhost 8080 we don't need the authorization um and we can just tweak this to be FTX so in theory this should smoke out the bug if if there is one inside of here so um let's go back to this and let's type in bash curl it the page GTX does not uh so so there's some internal bug here in the Wikipedia call and I and I think we can figure this out by what did we put in our command line tool here which was a CLI we need to fix the the default query there we go FTS bankruptcy that's the issue instead of just FTX we need to to do FDX bankruptcy so let's try that okay now let's run this there we go so so we just had a bad query so in fact this what this is telling me is that the deployed version would probably work and so all I would need to do is grab this go back to my deployed function inside of the gcp cloud which we go to Cloud functions we grab the Wiki keywords right here and we go to testing and all we need to change is this is we need to pass in FTX bankruptcy it's going to give us this curl command we test it in the cloud shell fingers crossed and boom we're able to deploy so you can see how the cloud once once you start building the the logic for a cloud function or sorry building functions you can deploy t o all these different kinds of environments so that was actually pretty cool now all I need to do is check in this code so other people can see it so I can just do this status check all this in now probably the funnest thing to do adding gcp versions from here would be to also show how to do it with Azure right so we can also do with Azure so how would we do this well one of the ways that that we can actually do this is by going to function inside of azure so it's got the same kind of a you know capability and if we go to function app we can just go through here and we can just say hey let's make a new thing let's go ahead and create a new function app and we can take a look at some of the things that you can do so we can create a name we can call this keywords and keywords December 13. and now we can either do code or we can do Docker container for code I'm going to select python and operating system Linux let's go to to review and create here we go now here's where the visual studio code is also our friend because what we can do here is actually pull this in to our environments inside of code spaces so this thing's actually you know triggering all this stuff while this is running I'm going to go back to code spaces I'm going to get this in the same shell here and I'm going to go to extensions and uh so this one says reload required sure let's reload this but we're going to install azure and so notice that instead of here this is azure app service or Azure functions and Azure functions extension I believe it's this one and let's double check here what it does so to create debug manage and deploy so you create it HTTP triggers you attach it yeah I think this is the one that lets you invoke it all locally so let's let's install this one and I believe what will happen is that it will um it will ask me what I want to do once it once it appears so this looks like it's it's enabled let's refresh real quick let's just make sure that that appears it should should appear do wn here there we go so we see it now we have uh should be Azure there we go azure so we would want to sign in to azure it's going to ask me to sign in you can close this window now I can go to this environment and I can find my functions app and we should once it once it's done okay go to resource I believe we just go to functions now and you say create and we can say where we want to develop we want to develop in vs code and so um let's go ahead and close that and let's go back here so I think I can right click create function app in Azure that's what I I believe that's what I want to do let's refresh here real quick there should be another one there we go keywords that's the one here we go and now here's the functions and so I forget here there's there's this might not be the right tool to do this installation there's another extension that might be better I'm not 100 sure yet though let's see if we say plus create function app and azure for serverless I don't know if it's that one o r whether you created here in in um in Portal or here we go http I guess I could just start with this and I could always pull it back in there we go so we I deployed a HTTP trigger and then we've got code and test and then you could go in here and you could actually uh build it build it out so we we see we've got this kind of a similar environment than the gcp and if I do go back again here and I refresh so let's just escape this and refresh this there's our trigger and we and we can actually see everything that is inside of this and I think as well it should have the code if I wanted to go through through there and if I wanted to to build it out and test it all and do the same thing so really in a nutshell this the concept of once you build a function you can easily take the logic and and actually deploy it to many different kinds of environments uh and it's actually pretty pretty trivial one other thing that I'll show you that's that's similar to this if we go back to the gcp cloud r eally quick is in addition to the cloud functions there's there's kind of like the next rev up which would be something called Cloud run and it's also kind of identical to this in that you can build out you know a containerized service that again uses similar logic so there's a couple ways to to do this one I could just create a new service a second one is if I go to Cloud shell this is kind of a neater one is they they've really been working on this editor here is that I could basically use their fancy interface that has a cloud native environment and also build out a containerized microservice so let's go ahead and see how that would work if I click on this notice what happens is it's got Cloud run right here and if I click on plus create a new Cloud run app It'll ask me what kind of service to build let's build a flask app for example and it'll say like where do you want to create this we'll we'll go ahead and do this create a new application and what it does is it creates an entire environment for me to do the the customized development now they don't yet have the the pair Programming type tool II would be curious when they're going to get something like this like either code whisper or co-pilot but it shows you exactly how to actually build this out look look what they've got here so they've got an app file right really really easy here they also have um a Docker file right here and notice the docker file that they use is very simple you know we have some simple things that we go through here and we and we build so what I could do if I'm brave is I could see if I could Port my code over here and see if I could get it to work really quickly or I could just deploy this either one um probably I'll just deploy it because the time is running short so if I go through here to run this you just say run you go to here and you just I think it says um the emulator so you say click on the cloud run status bar and select run on cloud run emulator so I believe it's status ba r here where is it here we go start start with out debugging and I believe it will just run it locally for us if I if I remember correctly launch and debug this one there we go so we're we're able to go and go inside of here and we see us running etc etc etc right so the other thing that we can do that's pretty simple is that once we go here I believe it created those files yeah hello world one that if we go inside of here one of the nice things about this style like if I just look at the docker file is that to to deploy it I believe it is just called gcp Cloud run deploy if I remember correctly and let's look at the documentation real quick Cloud run I think it's just one line so quick start let's look at the documentation quick start build and deploy if I remember correctly that's all you got to do that cloud space or gcloud space run space deploy so if we go back here if I just do that command and again it's not a lot of code and notice this does highlight what I talked about earlie r which is that functions right what is this a function right so we're just deploying a function into production so let's go ahead and do that command gcloud run deploy and it's going to say source code sure service name sure ask for a numeric number how about US east one let's do that and um we can say that I know we just deploy this thing into production so once you once you've got some logic as a function put it into either some kind of microservice framework like flask or fast API you have a Docker file the whole world opens up to you there's just really a ton of different places that you can deploy your code to uh and that's really the advantage of using python functions right is is the ability to to take logic and make it go live and we've been able to do that in four different environments uh ews we've been able to do it in GitHub we've been able to do it in gcp you've been able to do it in Azure we've also been able to do it in slightly different versions you know in this case we're not only using Cloud functions but also using Cloud run there's a lot of really cool things that you get by by actually doing this so we can see it's in action here and it's doing uh a deploy I mean it's it's really amazing actually when you think about it it's just one command there we go hello world is up we can just uh go to that URL and there we go and we can see successfully running uh deployed a container now I believe we can debug this thing on the fly if I remember correctly it's pretty trivial to make a change so let's try that let's um go into the app here and let's just tweak this a little bit and we can say the message is it's running and I changed it right and now if I say deploy it it should do it should let us redeploy easily let me Google the docs here listen so you can deploy to Cloud run I believe the redeploy it should be simple wait let me redeploy redeploy Cloud run should be should be easy Cloud build Cloud run app lying to Cloud run build again well I don't need to necessarily Google it I'll just run it right let's go back to where is it here it is let's just go back to us East 128. let's see what it says hopefully it's a pretty easy process oh to make this the default region we can do that right so we could say gee so I will do that that might make it easier is equivalent to doing this this command is equivalent to doing Cloud run deploy so there's probably a like a way to to make this oh the source code next time you use to deploy the current directory so we could do that we could say gcloud deploy source and let's just see how quickly it is able to make a change so pretty pretty fast actually so let's run this command to so it remembers that let's um go to this and it says it's running and I change it right so you can see it's trivial to to redeploy so I mean I guess I'm a few minutes in theory I could get really wild here and I could go to the editor and let's just make all the smaller and I'm curious how far I could go so if I went to my my code here and I grab one of my other microservices like the this this web one that I had this one like this yeah this would be a good one this should be let's build one in flask real quick and let's just copy it over um go to function log so let's just grab all this let's put this in here so we can do this and we could just make a quick little add function here and we could just say you know app dot routes and we could do add it would be a and I always forget how you build out the routes instead of flask we could be lazy and we could just ask our friend here co-pilot touch web ad flask let's see how fast it can build it out and we just say this build out the yeah and we could say from this um from so so first though I need to just paste in this stuff from flask there we go and then we can say build out the flask Gap there we go add the routes let's see what we can come up with post method what if I want to say I don't want to do a post I want to do this and we can just we can say add and I say a forget if it's like this syntax and we want to say again we want to do a get method kit method build and add route with a get method let's try that let's see if that'll help us that takes both numbers as parameters uh no as a URL URL parameters I don't know why this is I'm struggling with it's not giving me the the best we can just say flask URL parameters let's see what we got here requests flask there we go that's what I'm curing about we want something like that that's what I thought Okay so we'll go to to this and we'll just say a and B some something like that we'll go back to our our code here we'll just say a and B there we go that looks good Add A and B There we go so that's all you need we need that so if I go back to this I threw this inside of here we can get rid of the other stuff we don't need it whoops delete this delete this delete this in theory this should work we stop this Ctrl C to kill this we don't even need to preview it I just go back to the t erminal and I can go to the command that it told me earlier which was this and this should take at least some of it away if I remember it's going to be deployed to 20 28. so we'll go here service name that's good well didn't have to do anything I just needed to so it should be picking up that change that I just made and fingers crossed it'll give us the new routes that are available and that should allow me to make a third deployment of this service all right we're fingers crossed here this will work I guess you could also look at the logs and and see how it's doing in production by looking at the logs as well okay building the container creating revision deploying revision routing traffic should be next because it just checked the health all right doesn't work it does work and if I say add two and two it works four

Noticias relacionadas