How to configure Mongodb-Atlas in flask using flask_mongoalchemy? - mongodb

I did put password of that user in the field and i have tried all possible combination with dbname.I dont know which dbname it is referring to. I have searched many places, didnt get any answers. Can some one please help me how to configure.
app.config['DEBUG']=True
app.config['MONGOALCHEMY_CONNECTION_STRING']='mongodb+srv://user:
<password>#test.usvae.mongodb.net/<dbname>?retryWrites=true&w=majority'
db=MongoAlchemy(app)
This is my configeration.
This is the error i am getting
raise ImproperlyConfiguredError("You should provide a database name "
flask_mongoalchemy.ImproperlyConfiguredError: You should provide a database name (the MONGOALCHEMY_DATABASE setting)
Thanks in advance

import pymongo
## DB Connection ##
client = pymongo.MongoClient("mongodb+srv://mongouser:password#<cluster>/<db>?retryWrites=true&w=majority")
## DB Creation ##
db = client.<db>
## Collection Creation ##
col1 = db.Users
if client:
print("connected")
else:
print("not connected")
# Single Value Insert ##
Users = {"ID":"481292","Name":"DS"}
#x1 = col1.insert_one(Users)
You can try above code to connect mongodb atlas to flask.
Below code for using mongodb atlas with flask_mongoalchemy
from flask import Flask
from flask_mongoalchemy import MongoAlchemy
app = Flask(__name__)
DB_URI = 'mongodb+srv://<user>:<password>#<cluster>/<db>?retryWrites=true&w=majority'
app.config['MONGOALCHEMY_DATABASE'] = 'test'
app.config["MONGODB_HOST"] = DB_URI
db = MongoAlchemy(app)
class Users(db.document):
name = db.StringField()
age = db.IntField()
You need to insert value as well, to avoid error.

Related

Is it possible to pull data from Heroku Postgresql?

Currently I am working on a telegram bot using Heroku and Flask to deploy it. I wanted to store some data into a database then I came across Heroku PostgreSQL. I managed to store data into it but I am having trouble retrieving these data from Heroku PostgreSQL. I have research quite a bit but couldn't find much information about the process on pulling the data. Can someone enlighten me or suggest what are the steps to retrieve/pull these data from Heroku PostgreSQL with Flask?
The Telegram Bot is basically a random food generator. I have stored a list of food into the data and wanted to pull these data and random generator whenever user trigger the bot/action.
Screenshot of the current heroku postgresql database
from os import environ
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from invokes import invoke_http
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = environ.get("DB_URL") or "postgres://database-url"
app.config["SQLALCHEMY_TRACK_MODIFICATION"] = false
db = SQLAlchemy(app)
CORS(app)
class Cusine(db.Model):
__tablename__ = "cusines"
id = db.Column(db.String(255), primary_key =True)
cusine = db.Column(db.String(255), nullable=False)
def __init__(self, id, cusine):
self.id = id
self.cusine = cusine
def getId(self):
return self.id
def getCusine(self):
return self.cusine
def json(self):
return {"id": self.id,"cusine":self.cusine}
db.create_all()
#app.route("/getAllCusine")#
def getAllCusine():
try:
all_cusine = Cusine.query.all()
cusines = []
for row in all_cusine:
cusines.append(row.cusine)
return jsonify(
{
"code": 200,
"message": cusines
}
),200
except:
return jsonify(
{
"code": 500,
"message": "error in getting all course"
}
),500
So, how can I pull the data from Heroku PostgreSQL using Flask?
Thank you in advance.
I have managed to extract the data from Heroku PostgreSQL.
I have changed the above code with the following.
import os
import psycopg2
DATABASE_URL = os.environ['DATABASE_URL']
def retrieveData():
try:
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
cursor.execute("select * from table") #some sql statement
conn.commit()
result = cursor.fetchall()
cursor.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
return result
It will return a list of tuple.
Remember to pip install psycopg2-binary
It is my very first time working with Heroku and PostgreSQL, which took me quite awhile to figure out. But thanks guy for teaching me how to properly use stackoverflow, appreciate it. Hopefully this can help someone out there (like me), who is new to PostgreSQL. Cheers :)

'Cursor' object has no attribute - In pymongo

Im trying to make a web app in Flask with Pymongo and a MongoDB
Im getting that it cant find the attribute password in my db under users
elif request.method == 'POST':
login_user = request.form['username']
db_user = mongo.db.users.find({"username": "MattatMatt"})
pw = db_user.password
I know im being an idiot, please help.
This is the database:
username:"MattatMatt"
password:"..."
If you need anything else please ask.
Thank you!!!
find() returns a cursor. You likely want find_one() which returns a single record as a dict. As it's a dict and not an object, you will need to get the password using db_user['password'], e.g.
elif request.method == 'POST':
login_user = request.form['username']
db_user = mongo.db.users.find_one({"username": "MattatMatt"})
pw = db_user['password']

"Not authorized on ___ to execute command" with mLab + MongoDB ^3.0

Connects without a hitch, but on insert() throws me this error.
var MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var url = 'mongodb://____:____#ds125565.mlab.com:25565/heroku_w268n9pj';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
db = client.db('temp');
console.log("connected!");
const collection = db.collection('temp');
collection.insert([{
something: please
}
});
I saw some other answers regarding mLab accounts and credentials, but I just created a new admin account for this. Frustrating because it was working previously with v2.3.
When attempting to connect to an mlab database, you have to correctly specify the client. It's located at the end of your connection string, just after the final forward slash.
mlab_url = "mongodb://db_user_name:db_password#ds139725.mlab.com:39725/heroku_sd1fp182?retryWrites=false"
client = MongoClient(url)
db = client["heroku_sd1fp182"]
collection = db["coinHack"]
You may also get the error:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
Just add "?retryWrites=false" to your connection string, as shown above.

MongoDB Program New Database Authentication Fails

I have a remote tenant database application using MongoDB with authentication enabled. During run-time, I have to programmatically create a new tenant database, create a new tenant database user, create a new collection, and write to the new database with user metadata. My problem is that I am not setting up the tenant user authorization correctly. I am able to create the new tenant database and a database user with role credentials "readWrite". I also can correctly write the document to the "users" collection. If I use my admin credentials, I can access the Tenant database and examine the users document with no issue. However, if I try to later access the database with the newly created database user credentials I get an incorrect user credentials exception. Below is my code that creates the new tenant database,
MongoCredential adminCredentials = MongoCredential
.createCredential(adminuid, admindb, adminpw.toCharArray());
ServerAddress adminSA = new ServerAddress(mongoConnectionUri, mongoPort);
// Create the Mongo Password Vault Client & Document Template
MongoClient adminclient = new MongoClient(adminSA, Arrays.asList(adminCredtials)):
MongoClient adminclient MongoClient(adminSA,Arrays.asList(adminCredentials));
DB tenant = adminclient.getDB(tenantdb);
// Create pwvdb user
DBObject pwvdbrole = new BasicDBObject();
pwvdbrole.put("role", pwvrole);
pwvdbrole.put("db", pwvdb);
ArrayList<DBObject> pwvdbroles = new ArrayList<DBObject>();
pwvdbroles.add(pwvdbrole);
DBObject pwvaultcmd = new BasicDBObject();
pwvaultcmd.put("createUser", pwvuid);
pwvaultcmd.put("pwd", pwvpw);
pwvaultcmd.put("roles", pwvdbroles);
CommandResult result = tenant.command(pwvaultcmd);
if (result.ok()) {
System.out.println("Tenant Credentials: OK");
} else {
System.out.println("Tenant Credentials Error: " +
result.getErrorMessage());
}
// Create users Collection
DBCollection tenantCollection =
tenant.getCollection(tenantcollection);
// Create user default credentials & update user collection
BasicDBObject userdocument = new BasicDBObject();
userdocument.put("firstname", userfirstname);
userdocument.put("lastname", userlastname);
userdocument.put("email", useremail);
userdocument.put("username", username);
userdocument.put("password", pwencoder.encode(userpassword));
userdocument.put("role", Integer.parseInt(userrole));
// Create admin web portal users uid/pw
tenantCollection.insert(userdocument);
pwvclient.close();
Because the client is remote, I use my admin userid, pw, and db for the credentials. However, the MongoDB tenant client is setup using the new tenant database name. This is probably where I am going wrong but I don't know how to remotely access the database with a user I have not created yet. These databases are created at run time and I do not know the name of the tenant user when the application starts.
there are two different places for user permissions to be created, which can be confusing. Both can be done dynamically in your code.
User roles in tenant DB
The easiest option is for you to create the user you want in the tenant DB. You should use the runCommand call with the document structure for the createUser command documented here. You would create this user in the tenant DB. The role should be readWrite or any others documented.
Then later you would authenticate for the user and password for that same DB.
You can also centralize all of your user management in the Admin DB with each createUser call enumerating the roles for each DB/role pair you want. Let me know if you need that explanation. It works basically the same way to create users there and authenticate against that DB also. Then you switch to the DB you want to access on the same MongoClient.
I could not post 2 other helpful links because of strange limitation on posting more than 2 links if I am not an active enough poster (10 reputation).
Here is what I did to get it to work. The two key things I want to point out is the adminops and testops MongoDB templates. Notice that in adminops I used my MongoDB admin credentials but pointed to the testdb. In testops I used my new testdb credentials and point to testdb as well. My error was with adminops. I used the admindb which was incorrect. Also getting the roleobj and cmd was a little tricky but I eventially figured it out.
package com.belcan;
import java.util.ArrayList;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class PreConfigTestApplication implements CommandLineRunner {
public static void main(String[] args) {
// Fire off Spring Boot & Embedded Linux
SpringApplication.run(PreConfigTestApplication.class, args);
}
#Override
public void run(String...args) throws Exception {
String testdb = "testdb";
String testuid = "skm";
String testpw = "password";
// Set up credentials
MongoCredential admincredentials = MongoCredential
.createCredential(adminuid, admindb, adminpw.toCharArray());
ServerAddress adminsa = new ServerAddress(mongoConnectionUri, mongoPort);
// Create the Mongo Client & Document Template
MongoClient adminclient = new MongoClient(adminsa,Arrays.asList(admincredentials));
MongoOperations adminops = new MongoTemplate(adminclient, testdb);
// First create new user
DBObject roleobj = new BasicDBObject();
roleobj.put("role", "readWrite");
roleobj.put("db", "testdb");
ArrayList<DBObject> array = new ArrayList<DBObject>();
array.add(roleobj);
DBObject cmd = new BasicDBObject();
cmd.put("createUser", testuid);
cmd.put("pwd", testpw);
cmd.put("roles", array);
// Create new User
CommandResult result = (CommandResult) adminops.executeCommand(cmd);
// check to see if command is ok
if (result.ok()) {
System.out.println("createUser Command: OK");
} else {
System.out.println("createUser Error:" + result.getErrorMessage());
}
// switch to testdb
MongoOperations testops = new MongoTemplate(adminclient, testdb);
// Create the user object
User user = new User();
user.setFirstname("mickey");
user.setLastname("mouse");
user.setEmail("mmouse#gmail.com");
user.setUsername("mmouse");
user.setPassword("mmouse1");
user.setRole("USER");
user.setStatus("ACTIVE");
// Now save it
testops.save(user, "users");
// Close Database Connection
adminclient.close();
//
// Now see if we can open the file with the new uid/pw
//
// Set up credentials
MongoCredential testcredentials = MongoCredential
.createCredential(testuid, testdb, testpw.toCharArray());
ServerAddress testsa = new ServerAddress(mongoConnectionUri, mongoPort);
// Create the Mongo Client & Document Template
MongoClient testclient = new MongoClient(testsa,Arrays.asList(testcredentials));
MongoOperations myops = new MongoTemplate(testclient, testdb);
User myuser = new User();
myuser.setFirstname("Daffy");
myuser.setLastname("Duck");
myuser.setEmail("dduck#gmail.com");
myuser.setUsername("dduck");
myuser.setPassword("dduck1");
myuser.setRole("USER");
myuser.setStatus("ACTIVE");
// Now save it
myops.save(myuser,"users");
// Lets print it out
System.out.println("Print Results");
ArrayList<User> userout = (ArrayList<User>) myops.findAll(User.class, "users");
for (int i = 0; i < userout.size(); i++) {
System.out.println(userout.get(i));
}
System.out.println("\n\nAll Done....");
// Close the database
testclient.close();
}
// MongoDB Connection URI
#Value("${spring.data.mongodb.uri}")
private String mongoConnectionUri;
// MongoDB Connection Port
#Value("${spring.data.mongodb.port}")
private int mongoPort;
// MongoDB userid
#Value("${mongo.server.admin.db}")
private String admindb;
// MongoDB admin password
#Value("${mongo.server.admin.pw}")
private String adminpw;
// MongoDB admin userid
#Value("${mongo.server.admin.uid}")
private String adminuid;
}

'Execute failed:unauthorized' when using RockMongo with MongoLab

I can't use RockMongo(v1.1.2) to connect MongoLab, what did i do wrong?
In my MDb.php file
$MONGO["servers"][$i]["mongo_name"] = "MongoLab";
$MONGO["servers"][$i]["mongo_host"] = "ds053xx.mongolab.com";
$MONGO["servers"][$i]["mongo_port"] = "53818";
$MONGO["servers"][$i]["mongo_timeout"] = 0;
$MONGO["servers"][$i]["mongo_auth"] = true;
and when I log in with my username, password, db_name
It can log in but I can't do anything with it
on the left side of the screen it show
Execute failed:unauthorized
function (){ return db.getCollectionNames(); }
I have no problem when connect to local database.
And also can use the same url,port,username,etc. with MongoVUE
This doesn't appear to be anything you're doing wrong. It looks like RockMongo requires admin access because it's trying to list collections for databases other than your own (such as the admin and local databases), which is not possible w/ MongoLab's Sandbox databases.
https://github.com/iwind/rockmongo/issues/35
If you want to access only your own database, you can change the following line 31 inside rockmongo/apps/models/MDb.php listCollections(MongoDB $db) function:
from
$names = self::exec($db, 'function () {
return db.getCollectionNames();
}');
to
$names = $db->getCollectionNames();