We will introduce it using the sample application (Feedback).
`Although it is an article on Mac environment, the procedure is the same for Windows environment. Please read and try the environment-dependent part. ``
After reading this article to the end, you will be able to:
No. | Overview | keyword |
---|---|---|
1 | Flask-SQLAlchemy development | Flask-SQLAlchemy, psycopg2 |
2 | PostgreSQL settings | psql, Flask-Migrate |
environment | Ver. |
---|---|
macOS Catalina | 10.15.2 |
Python | 3.7.3 |
Flask-Migrate | 2.5.2 |
Flask-SQLAlchemy | 2.4.1 |
Flask | 1.1.1 |
psycopg2 | 2.8.4 |
requests | 2.22.0 |
I think that understanding will deepen if you read while actually following the implementation contents and source code. Please use it by all means.
-Create a RESTful web service in Flask
tree.sh
/
├── app
│ ├── __init__.py
│ ├── config.py
│ ├── feedback
│ │ ├── __init__.py
│ │ ├── common/
│ │ ├── models
│ │ │ ├── __init__.py
│ │ │ └── feedback.py
│ │ ├── static/
│ │ ├── templates/
│ │ └── views/
│ ├── run.py
│ └── tests/
└── instance
├── postgresql.py
├── sqlite3.py
└── config.py
Install the package.
~$ pip install Flask-Migrate
~$ pip install Flask-SQLAlchemy
~$ pip install Flask
~$ pip install psycopg2
If you get an error when installing psycopg2
, run the command with environment variables (macOS + venv environment).
~$ xcode-select --install
~$ env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2
Set the config of the development environment.
"""instance/config.py
"""
from instance.postgresql import SQLALCHEMY_DATABASE_URI as DATABASE_URI
DEBUG = True
# SECRET_KEY is generated by os.urandom(24).
SECRET_KEY = '\xf7\xf4\x9bb\xd7\xa8\xdb\xee\x9f\xe3\x98SR\xda\xb0@\xb7\x12\xa4uB\xda\xa3\x1b'
STRIPE_API_KEY = ''
SQLALCHEMY_DATABASE_URI = DATABASE_URI
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_ECHO = True
Set up PostgreSQL.
"""instance/postgresql.py
"""
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://{user}:{password}@{host}/{name}'.format(**{
'user': 'nsuhara',
'password': 'nsuhara',
'host': '127.0.0.1',
'name': 'db.postgresql'
})
Set up SQLite3 (bonus).
"""instance/sqlite3.py
"""
import os
SQLALCHEMY_DATABASE_URI = 'sqlite:///{host}/{name}'.format(**{
'host': os.path.dirname(os.path.abspath(__file__)),
'name': 'db.sqlite3'
})
Create an instance of SQLAlchemy.
"""app/feedback/models/__init__.py
"""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init():
"""init
"""
db.create_all()
Create a Model by inheriting the SQLAlchemy class (db.Model
).
"""app/feedback/models/feedback.py
"""
from datetime import datetime
from feedback.models import db
class Feedback(db.Model):
"""Feedback
"""
__tablename__ = 'feedback'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
service = db.Column(db.String(255), nullable=False)
title = db.Column(db.String(255), nullable=False)
detail = db.Column(db.String(255), nullable=False)
created_date = db.Column(
db.DateTime, nullable=False, default=datetime.utcnow)
def __init__(self, service, title, detail):
self.service = service
self.title = title
self.detail = detail
def to_dict(self):
"""to_dict
"""
return {
'id': self.id,
'service': self.service,
'title': self.title,
'detail': self.detail,
'created_date': self.created_date
}
This is an example of executing Homebrew
.
Check the service.
~$ brew services list
Name Status User Plist
postgresql started nsuhara /Users/nsuhara/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Start the service.
~$ brew services start postgresql
End the service.
~$ brew services stop postgresql
`Three databases are created by default. Also, the Mac username is set as Owner. ``
```procedure.sh
~$ psql -l
```
```result.sh
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
--------------+---------+----------+---------+-------+---------------------
postgres | nsuhara | UTF8 | C | C |
template0 | nsuhara | UTF8 | C | C | =c/nsuhara +
| | | | | nsuhara=CTc/nsuhara
template1 | nsuhara | UTF8 | C | C | =c/nsuhara +
| | | | | nsuhara=CTc/nsuhara
```
Connect to the database.
~$ psql -h "<host_name>" -p <port_number> -U "<role_name>" -d "<database_name>"
~$ psql -h "127.0.0.1" -p 5432 -U "nsuhara" -d "postgres"
Disconnect the database.
postgresql=# \q
Connect to the database.
Confirm the role (user).
postgresql=# \du
List of roles
Role name | Attributes | Member of
----------+------------------------------------------------------------+-----------
nsuhara | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
Create a role (user).
postgresql=# CREATE ROLE "<role_name>" LOGIN PASSWORD "password";
postgresql=# CREATE ROLE "nsuhara" LOGIN PASSWORD "nsuhara";
Delete the role (user).
postgresql=# DROP ROLE "<role_name>";
postgresql=# DROP ROLE "nsuhara";
Connect to the database.
Check the database.
postgresql=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
--------------+---------+----------+---------+-------+---------------------
db.postgresql | nsuhara | UTF8 | C | C |
postgres | nsuhara | UTF8 | C | C |
template0 | nsuhara | UTF8 | C | C | =c/nsuhara +
| | | | | nsuhara=CTc/nsuhara
template1 | nsuhara | UTF8 | C | C | =c/nsuhara +
| | | | | nsuhara=CTc/nsuhara
Create a database.
postgresql=# CREATE DATABASE "<database_name>" OWNER "<role_ name>";
postgresql=# CREATE DATABASE "db.postgresql" OWNER "nsuhara";
Delete the database.
postgresql=# DROP DATABASE "<database_name>";
postgresql=# DROP DATABASE "db.postgresql";
Set Flask environment variables.
Migrate the database.
~$ flask db init
~$ flask db migrate
~$ flask db upgrade
Connect to the database.
Delete the record.
postgresql=# delete from <table_name>;
Initialize automatic numbering.
postgresql=# select setval ('<table_name>_id_seq', 1, false);
Recommended Posts