Connecting to Google Cloud SQL from App Engine: access denied - python

Trying to connect to Google Cloud SQL from App Engine. Getting an error 500 and the logs say: "Access denied for user 'root'#'cloudsqlproxy~' (using password: NO)"). The App Engine and cloud SQL are in the same project. The code I use to connect:
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
env = os.getenv('SERVER_SOFTWARE')
if (env and env.startswith('Google App Engine/')):
# Connecting from App Engine
db = MySQLdb.connect(
unix_socket='/cloudsql/<project-id>:europe-west1:<instance-name>',
user='root')
cursor = db.cursor()
cursor.execute('SELECT 1 + 1')
self.response.write('pong')
app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
As I understand, I am doing everything correctly. The code above I effectively copy-pasted a snippet that you can view in Google Dev Console. Everywhere on StackExchange it is said, that I should not pass the password, so I am not doing that either. I have changed root user password when I created the instance. I don't see why would database deny acess to App Engine, they are on the same project! Is there a way to check what are the permissions for the database?

Okay, so turns out there is some misinformation happening. Adding a password parameter solved my issue. But for some reason, there is no mention of this in Google Documentation and many posts on StackOverflow actually directly tell you the oppposite, saying that Cloud SQL will throw an error if you pass it a password when logging in from AppEngine. Maybe some recent update is a cause of this, but in my case, passing a password solved the problem. Hope that helps!

I would say this part is not well documented on Google Developer Console.
Google Cloud SQL 2nd Gen comes with a little modification required in the connection string which is not provided in your code.
Please have a look at the original code after some modifications from my side:
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
#db connection
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/<project-id>:europe-west1<instance-name>, db = 'your-db', user= 'root', passwd='your-root-password')
else:
db = MySQLdb.connect(host = '10.10.0.1', port=3306,
db = 'your-db', user='root', passwd='root-password')
cursor = db.cursor()
cursor.execute('SELECT 1 + 1')
self.response.write('pong')
app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
Regards.

Related

Flask SQLAlchemy with Postgresql, autocommit does not work without a query after inserting a record

I have configured the DB connection in my flask app this way:
app.config['SQLALCHEMY_DATABASE_URI'] = conn_url
session_options = {
'autocommit': True
}
db = SQLAlchemy(app, session_options=session_options)
In my view code,
req_body = request.json
db.session.add(XYZ(**req_body))
where XYZ is my db.Model, does not insert the record into the table.
Neither the flush() or commit() from sqlalchemy gets executed.
But, adding a query after the add flushes the session changes into the DB and inserts the record.
req_body = request.json
db.session.add(XYZ(**req_body))
XYZ.query.all()
I don't think this is the desired behaviour with autocommit enabled.
Can someone please comment on this or let me know if I'm missing something here?
Thanks in advance!

Finding name and details of a database

I am new to Flask.
I have a task to connect a PostgreSQL database to my Flask app and create some API endpoints.
All the details I have on the database are the following:
Database location: postgres://candidate.company.org/company
Username: interview
Password: cake
To connect to the database I did the following:
myproject/myapp.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://interview:cake#candidate.company.org/suade'
db = SQLAlchemy(app)
I think it is connected (how can I be sure it is connected?).
My problem is that in the task it is not written what the database contains or what the name of tables are.
How can I find out the name and content of the tables in the database if I do not know anything about it?
Try query something like: db.session.query("1").from_statement("SELECT 1").all()

how to login into the database with username, password using python code?

I have two mongodb database(Admin, dadus). In one database, i have stored database details like database name, username and password.
use Admin
db.org.insert({database : "dadus", uid : "dadus_user", pwd : "dadus_user"})
now we will use the above databasename, username and password details login into the dadus database using Python code.
My python code below:
from pymongo import MongoClient
from flask_cors import CORS
app = Flask(__name__)
cleint = MonogoClient(port = 27017)
db = client.Admin
col = db.org
CORS(app)
#app.route('/users/login', methods=['POST'])
def login:
connection = col.find_one({"database" : "dadus"})
after find the database details in JSON format, how to login into the dadus database using python?
You can login to like this:
new_client = pymongo.MongoClient("mongodb://{}:{}#localhost/dadus".format(connection.uid,connection.pwd))

How to find postgresql uri for SQLALCHEMY config

I am trying to connect my flask app to my prostgreSQL db, and i find this configuration example (below code). I just do not know how to find my postgreSQL URI
app = Flask(__name__)
#how do i know my postgresql URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/pre-registration'
db = SQLAlchemy(app)
From the documentation of SQLAlchemy (http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls):
The typical form of a database URL is:
dialect+driver://username:password#host:port/database
This means that, if you have a Postgres DB called my_db running on localhost on port 5432, accessed by username user and password pass, your URL will look like:
postgresql://user:pass#localhost:5432/my_db

Insert a document with Flask-PyMongo

I have a MongoDB database and I want to use Flask-PyMongo to work with it in my Flask app. How do I add a database and a collection so I can add user documents?
from flask import Flask, render_template, url_for
from flask.ext.pymongo import PyMongo
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'microblogdb'
app.config['MONGO_URI'] = 'mongodb://briangunsel:password#microblog:27017/microblogdb'
mongo = PyMongo(app, config_prefix='MONGO')
#app.route('/')
def home():
posts = mongo.db.posts.find({})
return render_template('users.html', posts=posts)
app.run(debug=True)
Update:
With only that code above, when I start up the server (python init.py) and I go to load the web page, it loads for about 10 seconds and then gives me this error https://gist.github.com/anonymous/62ca41e98e67b304838d. I am running the database microblogdb in another cmd prompt, and I set the mongo --dbpath to \data\, which is a folder I created in the microblog folder. Through the mongo interpreter, I added a posts collection, it is still giving me the same error.
mongo.db.users returns the users collection on the database you configured. Flask-PyMongo is using the PyMongo driver, which has extensive documentation. PyMongo's tutorial explains how to insert a document. You already have code that fetches the users who have online=True.
app.config['MONGO_URI'] = 'mongodb://username:password#host:port/db_name'
user_id = mongo.db.users.insert_one({'name': 'david'}).inserted_id

Categories