Megacurso programación en Python3 | 5. Conexión con base de datos MongoDB en la nube con mLab.com

in mlab •  4 months ago

Esta vez aprenderemos a conectar con una base de datos MongoDB en la nube. Para ello utilizaremos la web mLab.com, que nos provee de 500 MB de almacenamiento gratuito, así que créate una cuenta allí si aún no la tienes.

Todo el código mostrado a continuación se encuentra en este archivo.

En la carpeta del curso encontrarás el índice con las clases publicadas.

¿Qué es Mlab.com?

MLab es un servicio de base de datos en la nube completamente administrado que incluye el aprovisionamiento automatizado y la ampliación de bases de datos MongoDB, copia de seguridad y recuperación, supervisión y alerta 24/7, herramientas de administración basadas en web y soporte experto. La plataforma Database-as-a-Service de mLab potencia cientos de miles de bases de datos a través de AWS, Azure y Google y permite a los desarrolladores centrar su atención en el desarrollo de productos en lugar de en las operaciones.

mLab.com

Instalando dependencias

Para poder operar con MongoDB en Python debemos instalar la biblioteca pymongo. En la mayoría de los casos debería funcionar con:

pip3 install pymongo

Si deseas conocer el funcionamiento básico de pymongo puedes ver este tutorial.

Si tienes algún problema con la instalación de la biblioteca puedes acceder a su documentación.

Creando la base de datos

Para crear una base de datos simplemente le damos a 'create new', dentro de nuestro panel de usuario en mLab, y seguimos todos los pasos. Si tienes dudas puedes ver el siguiente vídeo:

Conectando con la base de datos

Si accedemos en mLab a nuestra base de datos, esta nos mostrará un URI con la cual podremos acceder a la base de datos desde nuestro cliente de pymongo. Para ello vamos a crear el siguiente código:

from pymongo import MongoClient
from os import environ

DATABASE_USERNAME = environ.get('DATABASE_USERNAME', '')
DATABASE_PASSWORD = environ.get('DATABASE_PASSWORD', '')

DATABASE_NAME = ''
BASE_URI = ''

DATABASE_URI = 'mongodb://{}:{}' + BASE_URI.format(DATABASE_USERNAME, 
                                                   DATABASE_PASSWORD)
mongo = MongoClient(DATABASE_URI)
db = mongo[DATABASE_NAME]

En DATABASE_NAME debemos indicar el nombre de la base de datos que hemos creado y en BASE_URI tenemos que introducir desde el símbolo @ hasta el final de la URI que nos ofrece mLab para nuestra base.

Si quieres saber más sobre cuando utilizar MongoDB y cuando no en tus proyectos puedes leer este artículo.

Crear una colección

Si le indicamos a MongoDB que se conecte a una colección que no existe, se creará automáticamente.

Para saber más sobre colecciones en MongoDB puedes leer este artículo.

Por lo tanto, si añadimos las siguientes líneas al código y lo ejecutamos...

db.users

...se creará una colección en la base de datos con el nombre users.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  trending

Nice post

·

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by 343301095524925440 from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, and someguy123. The goal is to help Steemit grow by supporting Minnows and creating a social network. Please find us in the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you like what we're doing please upvote this comment so we can continue to build the community account that's supporting all members.

·
·

I go to create a bot that says "Nice post" in all posts in Steemit and I will create a lot of value for the community.

·
·
·

Hola Mondeja.... Que bueno descubrirte por aquí. Jeje te sigo.

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Your post is nice and useful may you increase success in steemit and do, i will be successful as you become famous and useful for many people, sekalo lagoli gratitude with me read your post I am inspired.
Please pay attention to me and visit my post thank you

·

Your comment is spam, if I go to your comments https://steemit.com/@mnur/comments I can see that is repeated more times so you are fake. Fakes thanks!

Thank you ! Mondeja

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Congratulations @mondeja! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!