diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..90b8c50 --- /dev/null +++ b/.gitignore @@ -0,0 +1,132 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# MacOS +.DS_Store \ No newline at end of file diff --git a/Backend/FastAPI/README.md b/Backend/FastAPI/README.md new file mode 100644 index 0000000..dc6a83f --- /dev/null +++ b/Backend/FastAPI/README.md @@ -0,0 +1,324 @@ + +<!-- Improved compatibility of back to top link: See: https://github.com/molro/backend/pull/73 --> +<a name="readme-top"></a> +<!-- +*** Thanks for checking out the Best-README-Template. If you have a suggestion +*** that would make this better, please fork the repo and create a pull request +*** or simply open an issue with the tag "enhancement". +*** Don't forget to give the project a star! +*** Thanks again! Now go create something AMAZING! :D +--> + + + +<!-- PROJECT SHIELDS --> +<!-- +*** I'm using markdown "reference style" links for readability. +*** Reference links are enclosed in brackets [ ] instead of parentheses ( ). +*** See the bottom of this document for the declaration of the reference variables +*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use. +*** https://www.markdownguide.org/basic-syntax/#reference-style-links +--> +<!-- PROJECT LOGO --> +<br /> +<div align="center"> + + <h3 align="center">FastAPI - Ejemplo de Uso con Entornos virtuales de Python</h3> + + <p align="center"> + 🎯 Desarrollo de Python con entornos virtuales + <br /> + <a href="https://github.com/mouredev/Hello-Python/"><strong>Archivos »</strong></a> + <br /> + <a href="https://github.com/mouredev/Hello-Python/issues">Reportar un bug</a> + · + <a href="https://github.com/mouredev/Hello-Python/issues">Asignar una feature</a> + </p> +</div> + + + +<!-- TABLE OF CONTENTS --> +<details> + <summary>Table of Contents</summary> + <ol> + <li> + <a href="#intro">Introducción</a> + <ul> + <li><a href="#backend">Backend</a></li> + </ul> + </li> + <li> + <a href="#entornos">Entornos virtuales</a> + <ul> + <li><a href="#ventajas">Ventajas</a></li> + <li><a href="#versus">Global versus Virtual</a></li> + </ul> + </li> + <li><a href="#first-steps">Primeros Pasos</a></li> + <ul> + <li><a href="#ventajas">Prerequisitos</a></li> + <li><a href="#creating">Creando un EV</a></li> + <li><a href="#instalando">Instalanado LibrerÃas</a></li> + </ul> + <li><a href="#license">Licencia</a></li> + <li><a href="#contact">Contacto</a></li> + </ol> +</details> + + + +<!-- INTRO --> +## Introducción + +Por defecto la instalación de Python, incluye una gran cantidad de librerÃas de manera nativa y por defecto en la instalación de Python. Sin embargo es habitual el uso de liberÃas de terceros, como en este caso FastAPI. + +Para instalar y manejar paquetes, el módulo pip es la herramienta que nos permite instalar estas librerÃas de terceros, sin embargo esto lo realiza de manera global. + +Cuando compartimos el código, mediante un repositorio en GitHub por ejemplo, para poder ejecutar la aplicación deberemos instalar todas aquellas librerÃas de terceros que hemos instalado previamente de manera manual, con el riesgo que eso conlleva. + +Para ello existen dos alternativas: +* Usar contenedores (Docker por ejemplo) +* Usar Entornos virtuales + +Porqué? +* Tu tiempo es valioso y debes enfocarte en crear soluciones para resolver problemas que ayuden a otros. +* No deberÃas pasar tiempo instalando y desinstalando versiones de Python una y otra vez por cada proyecto. +* DeberÃas implementar el principio KISS para el resto de tu vida y esto es parte de ello :smile: + + +En este tutorial nos enfocaremos en el uso y desarrollo con entornos virtuales. +<p align="right">(<a href="#readme-top">back to top</a>)</p> + +<!-- BACKEND --> +### Backend + +Para comenzar el backend esta creado con: + +- [![Python][python-shield]][python-url] +- [![FastApi][fastAPI-shield]][fastAPI-url] + +<p align="right">(<a href="#readme-top">back to top</a>)</p> + +<!-- ENTORNOS --> +## Qué es un entorno virtual? + +Es un directorio autocontenido, que en su interior contiene una instalación de python con la versión particular para ese proyecto. Nos permite instalar además librerÃa de terceros. + +Es decir, permite ejecutar un proyecto con python y sus librerÃas, al mismo tiempo que tenemos otro proyecto con versiones de python y/o librerÃas distintas, sin necesidad de instalar y desinstalar cada vez que cambiemos de proyecto. + +<!-- VENTAJAS --> +### Ventajas + +La principal ventaja que nos encontramos es que nos permiten la portabilidad de nuestras aplicaciones. Imagina que escribes código, subes al repositorio y un compañero continúa con el proyecto desde su ordenador. El deberá instalar las liberÃas necesarias, pero puede ocurrir que existan diferentes versiones disponibles, esto lo podemos simplificar con una técnica similar al package.json de NodeJs, técnica que veremos mas adelante. + +Otra ventaja es la estandarización, tu y todos los desarrolladores que trabajéis sobre la aplicación utilizaréis las mismas versiones tanto del lenguaje y de las librerÃas. + +<!-- VERSUS --> +### Global vs Entorno Virtual + +Para poder explicar las diferencias, podemos apreciar la comparación entre ambas imagenes + +Global</br> +<img src="https://github.com/molro/Hello-Python/blob/Python-venv/Backend/FastAPI/img_Readme/global.png" /> +Virtual</br> +<img src="https://github.com/molro/Hello-Python/blob/Python-venv/Backend/FastAPI/img_Readme/env_virtual.png" /> + + + +<p align="right">(<a href="#readme-top">back to top</a>)</p> + +<!-- FIRST-STEPS--> +## Primeros pasos + +Crear un entorno virtual es relativamente sencillo, para ello necesitaremos tener instalado: +* [![Python][python-shield]][python-url] +* [![Git][git-shield]][git-url] +* Tu IDE Favorito +<!-- PRE-REQUISITOS --> +### Pre requisitos + +Cómo instalar alguna de las herramientas +* Git + * macOS -> Homebrew package manager -> [Learn more here][gitMac] + ```sh + brew install git + ``` + * Linux + * Para distribuciones basadas en Debian/Ubuntu + ```sh + apt-get install git + ``` + * Basadas en Fedora + ```sh + yum install git + ``` + Otras distribuciones [Download Git for Linux/Unix][gitLinux] + + * Windows + + La última versión de 32bit se puede descargar [Click Here][gitWindows32bit]<br/> + Para otras descargas, puedes hacerlo desde [Dowload git for Windows][gitWindows] + +* Python + * macOS + + * Última versión [here][pylatestmacos] + * Otras versiones [here][pymacos] + + * Windows + * Última versión [here][pylatestwin] + * Otras versiones [here][pywin] + + * Linux/Unix + + * GZipped source tarball [here][pygzip] + * XZ source tarball [here][pyxz] +<!-- CREATING --> +### Creando Entornos Virtuales + +IMPORTANTE!!! Trabajaremos sobre la terminal. + +1. Clonamos el repositorio + ```sh + git clone https://github.com/mouredev/Hello-Python.git + ``` + +2. Nos ubicamos en el directorio donde esta el backend + + ``` sh + cd /Hello-Python/Backend/FasAPI/ + ``` +3. Comprobamos la versión de Python, en mi caso tengo la versión 3.10 + + ``` sh + python3 --version + ``` +4. Comprobamos las liberÃas y versiones instaladas, con alguno de los comandos. + + ``` sh + python3 -m pip list + ``` + ``` sh + pip list + ``` + ``` sh + pip freeze + ``` + Veremos como resultado todas las librerÃas instaladas y sus respectivas versiones. + +5. Creamos nuestro entorno virtual, para ello utilizaremos la siguiente sintaxis + + ``` sh + python3 -m venv NOMBRE_DIRECTORIO_VIRTUAL + ``` + Ejecutamos el comando para crear un directorio llamado venv (De esta manera automáticamente se incluira en el git ignore, puedes llamarlo como desees, pero deberás incluir el directorio manualmente dentro del archivo .gitignore) + + ``` sh + python3 -m venv venv + ``` + Esto nos creará un directorio donde se instalará todo lo que necesitemos para el proyecto. +6. Para activar el entorno virtual necesitaremos activarlo mediante el siguiente comando: + ```sh + source NOMBRE_DIRECTORIO_VIRTUAL/bin/activate + ``` + En nuestro caso utilizaremos el siguiente comando + ```sh + source venv/bin/activate + ``` + + Para desactivar utilizamos + ``` sh + deactivate + ``` + + IMPORTANTE Veremos delante de nuestro prontuario el nombre del directorio donde hemos creado el entorno virutal. Asà sabremos siempre si esta activado o no. ```(venv) âžœ Hello-Python git:(Python-venv) ✗```. +7. Repetimos el paso 4 y comprobamos las versiones instaladas (Dentro del entorno virtual). +8. Instalamos las librerÃas utilizadas en el proyecto (Dentro del entorno virtual): + + ``` sh + pip install "fastapi[all]" + ``` +9. Volvemos a repetir el paso 4 y comprobamos las versiones instaladas (Dentro del entorno virtual). + + Podemos ver las diferencias revisando los archivos requirements-global.txt versus requirements.txt + +<!-- INSTALANDO --> +### Manejando e instalando librerÃas + +En este caso puede parecer sencillo instalar todas las librerÃas que necesitamos, ya que solo nos bastarÃa con el comando ```pip install "fastapi[all]" ```, pero sin embargo es probable que otros proyectos mas grandes requieran mas librerÃas y trabajar con versiones especÃficas. + +A diferencia de otras tecnologÃas como NodeJS, que maneja sus paquetes y versiones mediante el archivo ```package.json``` que se crea una vez que inicializamos un proyecto. En python deberemos hacerlo de manera manual, lo haremos mediante la creación del archivo ```requirements.txt``` lo haremos siempre dentro del entorno virtual, podemos hacerlo en los siguientes pasos: + +#### Crear requirements.txt +1. Para crear el archivo ```requirements.txt``` + ```sh + python3 -m pip freeze > requirements.txt + ``` + Si recordamos ```pip freeze``` nos permitÃa ver todas las librerÃas instaladas. Al utilizar ```>``` le estamos diciendo, el resultado de ```python3 -m pip freeze``` sácalo en ```requirements.txt```. + +2. Si abrimos el archivo ```requirements.txt``` veremos todas librerÃas y versiones de python utilizadas en el proyecto. + +* IMPORTANTE!!!! Si ejecutamos estos comandos, fuera del entorno virtual nos recopilará <b>todas</b> las librerÃas en nuestro ordenador de manera global. +Puedes probarlo para ver las diferencias entre instalación *Global vs Entorno Virtual* + +#### Instalar con requirements.txt +1. Para instalar necesitaremos tener el archivo ```requirements.txt```en la raÃz del proyecto y tener activado el entorno virtual. + ```sh + python3 -m pip install -r requirements.txt + ``` + Este comenzará a instalar todas las dependencias dentro de nuestro entorno virtual. +2. Una vez finalizada podemos comprobar, con + ``` sh + python3 -m pip list + ``` +<p align="right">(<a href="#readme-top">back to top</a>)</p> + + +<!-- LICENSE --> +## License + +Creado bajo licencia Apache-2.0 visita aquà para mas información [licencia][license-url]. + +<p align="right">(<a href="#readme-top">back to top</a>)</p> + + + +<!-- CONTACT --> +## Contact + +[![Twitter][twitter-shield]][twitter-url] [![GitHub][github-shield]][github-url]<br/> +Project Link: [Hello-Python](https://github.com/mouredev/Hello-Python/tree/main/Backend/FastAPI) + +<p align="right">(<a href="#readme-top">back to top</a>)</p> + +<!-- MARKDOWN LINKS & IMAGES --> +<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> + +<!-- Python Tools --> +[python-shield]:https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54 +[python-url]: https://www.python.org + +[fastAPI-shield]:https://img.shields.io/badge/FastAPI-005571?style=for-the-badge&logo=fastapi +[fastAPI-url]:https://fastapi.tiangolo.com +<!-- Git --> +[git-shield]:https://img.shields.io/badge/git-%23F05033.svg?style=for-the-badge&logo=git&logoColor=white +[git-url]: https://git-scm.com +<!-- Python --> +[pylatestmacos]:https://www.python.org/downloads/release/python-3111/ +[pymacos]:https://www.python.org/downloads/macos/ + +[pylatestwin]:https://www.python.org/downloads/release/python-3111/ +[pywin]:https://www.python.org/downloads/windows/ + +[pygzip]:https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tgz +[pyxz]:https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tar.xz + +[pywindowsdockermac-url]:https://docs.docker.com/desktop/install/mac-install/ +<!-- Redes --> +[twitter-shield]:https://img.shields.io/twitter/follow/molro?style=social +[twitter-url]:https://www.twitter.com/molro +[github-shield]:https://img.shields.io/github/followers/molro?style=social +[github-url]: https://github.com/molro/ + +[license-url]:https://github.com/mouredev/Hello-Python/blob/main/LICENSE diff --git a/Backend/FastAPI/__pycache__/main.cpython-310.pyc b/Backend/FastAPI/__pycache__/main.cpython-310.pyc deleted file mode 100644 index a539fac..0000000 Binary files a/Backend/FastAPI/__pycache__/main.cpython-310.pyc and /dev/null differ diff --git a/Backend/FastAPI/__pycache__/users.cpython-310.pyc b/Backend/FastAPI/__pycache__/users.cpython-310.pyc deleted file mode 100644 index 2e90b4e..0000000 Binary files a/Backend/FastAPI/__pycache__/users.cpython-310.pyc and /dev/null differ diff --git a/Backend/FastAPI/enlaces.txt b/Backend/FastAPI/enlaces.txt new file mode 100644 index 0000000..6b506cd --- /dev/null +++ b/Backend/FastAPI/enlaces.txt @@ -0,0 +1,3 @@ +Interprete VSCODE - https://bobbyhadz.com/blog/python-no-module-named-fastapi +Entornos virtuales python - https://docs.python.org/es/3/tutorial/venv.html +Venv Gitignore - https://stackoverflow.com/questions/42306410/gitignore-syntax-how-to-exclude-virtualenv-sub-directories diff --git a/Backend/FastAPI/img_Readme/env_virtual.png b/Backend/FastAPI/img_Readme/env_virtual.png new file mode 100644 index 0000000..b778b73 Binary files /dev/null and b/Backend/FastAPI/img_Readme/env_virtual.png differ diff --git a/Backend/FastAPI/img_Readme/global.png b/Backend/FastAPI/img_Readme/global.png new file mode 100644 index 0000000..6f01878 Binary files /dev/null and b/Backend/FastAPI/img_Readme/global.png differ diff --git a/Backend/FastAPI/main.py b/Backend/FastAPI/main.py index 7b9c125..dff93f0 100644 --- a/Backend/FastAPI/main.py +++ b/Backend/FastAPI/main.py @@ -6,7 +6,11 @@ # Instala FastAPI: pip install "fastapi[all]" -from fastapi import FastAPI +from fastapi import FastAPI +## Probablemente esto de error o parezca que no importa fastapi - +# Se debe a que el interprete de VSCODE esta seleccionado de manera global. +# Se puede corregir, seleccionado el interprete ubicado en la ruta venv/bin/python (La ruta de nuestro entorno virtual) + app = FastAPI() diff --git a/Backend/FastAPI/requirements-global.txt b/Backend/FastAPI/requirements-global.txt new file mode 100644 index 0000000..2281ab1 --- /dev/null +++ b/Backend/FastAPI/requirements-global.txt @@ -0,0 +1,57 @@ +anyio==3.6.2 +async-generator==1.10 +attrs==22.1.0 +beautifulsoup4==4.11.1 +certifi==2022.6.15 +charset-normalizer==2.1.0 +click==8.1.3 +exceptiongroup==1.0.1 +Flask==2.2.2 +Flask-SQLAlchemy==3.0.2 +gcloud==0.18.3 +googleapis-common-protos==1.56.4 +greenlet==2.0.1 +h11==0.14.0 +httplib2==0.20.4 +idna==3.3 +iniconfig==1.1.1 +itsdangerous==2.1.2 +Jinja2==3.1.2 +jws==0.1.3 +MarkupSafe==2.1.1 +oauth2client==4.1.3 +outcome==1.2.0 +packaging==21.3 +pluggy==1.0.0 +protobuf==4.21.3 +pyasn1==0.4.8 +pyasn1-modules==0.2.8 +pycryptodome==3.15.0 +pydantic==1.10.2 +PyJWT==2.6.0 +pyparsing==3.0.9 +Pyrebase==3.0.27 +Pyrebase4==4.5.0 +PySocks==1.7.1 +pytest==7.2.0 +python-firebase==1.2 +python-jwt==2.0.1 +pytz==2022.6 +requests==2.28.1 +requests-toolbelt==0.9.1 +rsa==4.9 +selenium==4.6.0 +six==1.16.0 +sniffio==1.3.0 +sortedcontainers==2.4.0 +soupsieve==2.3.2.post1 +SQLAlchemy==1.4.43 +starlette==0.22.0 +tomli==2.0.1 +trio==0.22.0 +trio-websocket==0.9.2 +twilio==7.15.4 +typing_extensions==4.4.0 +urllib3==1.26.10 +Werkzeug==2.2.2 +wsproto==1.2.0 diff --git a/Backend/FastAPI/requirements-preinstall.txt b/Backend/FastAPI/requirements-preinstall.txt new file mode 100644 index 0000000..e69de29 diff --git a/Backend/FastAPI/requirements.txt b/Backend/FastAPI/requirements.txt new file mode 100644 index 0000000..555fc38 --- /dev/null +++ b/Backend/FastAPI/requirements.txt @@ -0,0 +1,16 @@ +anyio==3.6.2 +click==8.1.3 +fastapi==0.88.0 +h11==0.14.0 +httptools==0.5.0 +idna==3.4 +pydantic==1.10.2 +python-dotenv==0.21.0 +PyYAML==6.0 +sniffio==1.3.0 +starlette==0.22.0 +typing_extensions==4.4.0 +uvicorn==0.20.0 +uvloop==0.17.0 +watchfiles==0.18.1 +websockets==10.4 diff --git a/Intermediate/mypackage/__pycache__/__init__.cpython-310.pyc b/Intermediate/mypackage/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index e220697..0000000 Binary files a/Intermediate/mypackage/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/Intermediate/mypackage/__pycache__/arithmetics.cpython-310.pyc b/Intermediate/mypackage/__pycache__/arithmetics.cpython-310.pyc deleted file mode 100644 index 6e2cf79..0000000 Binary files a/Intermediate/mypackage/__pycache__/arithmetics.cpython-310.pyc and /dev/null differ diff --git a/__pycache__/module.cpython-310.pyc b/__pycache__/module.cpython-310.pyc deleted file mode 100644 index 0d63bb6..0000000 Binary files a/__pycache__/module.cpython-310.pyc and /dev/null differ diff --git a/__pycache__/my_module.cpython-310.pyc b/__pycache__/my_module.cpython-310.pyc deleted file mode 100644 index ca5d74d..0000000 Binary files a/__pycache__/my_module.cpython-310.pyc and /dev/null differ