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
Related
I have created my own Flask app locally and I am trying to host it now on Heroku. I have created the database, but I still miss the tables in it.
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://{username}:{password}#{hostname}:{port}/{databasename}".format(
username="username_given_by_heroku",
password="password_from_heroku",
hostname="hostname",
port="xxxx",
databasename="name",
I have tried adding the tables the following way in the Heroku python console:
import psycopg2
from Website.__init__ import app, db
db.create_all()
This gives the following error:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "ec2-34-230-153-41.compute-1.amazonaws.com" (34.230.153.41), port 5432 failed: FATAL: password authentication failed for user "username"
connection to server at "hostname" (34.230.153.41), port xxxx failed: FATAL: no pg_hba.conf entry for host "34.205.2.34", user "username", database "database", no encryption
I have found the following link and gave the psql user a password in the PSQL shell, with no success.
Flask & Alchemy - (psycopg2.OperationalError) FATAL: password authentication failed
Requirements.txt:
Flask==2.1.1
Flask_Login==0.6.0
Flask_SQLAlchemy==2.5.1
Werkzeug==2.1.1
gunicorn==20.0.4
psycopg2==2.9.3
Models.py:
from . import db
class User(db.Model):
columns...
class otherTable(db.Model):
...
I also don't seem to have a pg_hba.conf or I can't find it.
How can I create the tables in my Heroku database?
In Heroku, you can add the PostgreSQL database as an Add-on. Just go to the resources tab on your application page in Heroku. In the Add-on search bar, search for "postgres" and select "Heroku Postgres". After selecting, click on "Attach as database". This will add the "DATABSE_URL" as a config variable in Heroku.
In your python app write the following code:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
if SQLALCHEMY_DATABASE_URI.startswith("postgres://"):
SQLALCHEMY_DATABASE_URI = SQLALCHEMY_DATABASE_URI.replace(
"postgres://", "postgresql://", 1)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
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()
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.
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
Is there a standard set of privileges that should be given to the user used to access a Flask SQLAlchemy database. For example with
application.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://app#127.0.0.1/test'
db = flask.ext.sqlalchemy.SQLAlchemy(application)
what privileges should app be given?