I successfully went through this tutorial: https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04 Now I’m stuck. Trying to also install SQLalchemy and then connect to a managed PostgreSQL DB. I’d love to see a part two to the above tutorial. An extra bonus would show pulling data from DB and displaying it via a Flask/Ninja2 template. Thanks!
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi there,
Here’s a rough guide on how to install SQLAlchemy and connect it to a DigitalOcean Managed PostgreSQL database in a Flask application.
1. Install SQLAlchemy
First, you need to install SQLAlchemy in your Flask environment. You can do that with pip:
pip install SQLAlchemy
2. Install psycopg2-binary
SQLAlchemy uses a driver to talk with your PostgreSQL database. The most common one is psycopg2. However, compiling psycopg2 from source can be a bit of a hassle, so we’ll use psycopg2-binary, which is a stand-alone package and easy to install:
pip install psycopg2-binary
3. Create your SQLAlchemy engine
Now you can create your SQLAlchemy engine. The engine is what SQLAlchemy uses to interface with your database. Here’s an example of how you might set up the engine in your Flask app:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# replace the user, password, host and dbname with your actual credentials
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@host:port/dbname?sslmode=require&sslrootcert=/path/to/ca-certificate.crt'
db = SQLAlchemy(app)
In this connection string, sslmode=require tells PostgreSQL to use SSL, and sslrootcert is used to specify the path to the CA certificate file. Replace /path/to/ca-certificate.crt with the actual path to your certificate file. This should allow you to connect to your DigitalOcean Managed PostgreSQL database using SQLAlchemy with SSL.
4. Define your database models
Now you can define your database models. Here’s an example of a simple User model:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
5. Create your database tables
With your models defined, you can create the tables in your database:
db.create_all()
You usually only want to run this once, when you first set up your application.
6. Pulling data from DB and displaying it via a Flask/Jinja2 template
Firstly, make sure you’ve imported your models at the top of your file:
from models import User
Then, you can query the database for users like so:
users = User.query.all()
And you can pass these users to your template:
@app.route('/users')
def users():
users = User.query.all()
return render_template('users.html', users=users)
And in your users.html template, you could display the users with something like this:
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
This is a very basic example and SQLAlchemy can do much more, but hopefully, this will help you get started.
Remember to always secure your database credentials. Do not hardcode them in your application. Consider using environment variables or secure secrets management systems.
Also, keep in mind that SQLAlchemy provides a Pythonic way to interact with your database. You’ll still need to understand SQL and your database system to make effective use of it.
For more detailed information, I recommend checking out the SQLAlchemy documentation.
Best,
Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.