Как подключить postgresql к flask

Flask PostgreSQL – SQLAlchemy

Как подключить postgresql к flask

In this article, we will learn to connect our Flask Application with PostgreSQL Database systems using an ORM – Object Relational Mapper, called Flask SQLAlchemy.

What is PostgreSQL?

Similar to the MySQL Database management system, PostgreSQL is another type of RDBMS used for accessing, storing, and handling the data in the form of database tables.

PostgreSQL also uses SQL- Structured Query Language to access and handle databases and also perform various Tasks in PostgreSQL

The Basic Structure of PostgreSQL

Data is stored inside Postgres DB in the form of Table. A typical Postgres Table looks like this:

IdNameClassGrade
1AliaIXB
2SnippyXA
3RayVIIID
4KimVIA
5JenniferXIIB
6GinnyXA

PostgreSQL Table

The rows are called records and the columns are called fields. Therefore, in the above table we have 6 records and 4 fields.

Difference between MySQL and PostgreSQL

Though both MySQL and PostgreSQL belong to RDBMS, there are some key differences between both.

Why SQLAlchemy to Connect PostgreSQL to a Flask Application?

SQLAlchemy is an ORM-Objects Relational Mapper written in Python. It gives away around to interact with the Databases without using SQL statements.

It provides an extra layer on top of SQL which allows us to use Databases and Tables just like Python Class Objects. We just have to create a Class Object and SQLAlchemy will take care of the rest!

In Flask, unlike Django, which comes with a pre-built ORM in the form of Django Models, it does not have a pre-built ORM.

Hence we need to install the Flask-SQLAlchemy ORM library to use models in this web framework

Setting-up PostgreSQL in your system

In this section, we will download and set-up all the necessary packages for our Flask- SQLAlchemy-Postgres project.

1. Installing PostgreSQL shell

To install PostgreSQL, visit the link here. Once PostgreSQL is installed, open the SQL shell and set up your DB connection Username and password.

Run the below command to open shell in Terminal:

In case of Windows, directly search for SQL shell in the search menu.

I have kept my Connection details default (shown in bracket).

After you enter the password, you will be prompted into the PostgreSQL DB by default.

Now let’s create a new DB with the name Flask to store our data.

Here we are using SQL syntax only. Do check out our SQL tutorial on the JournalDev website to gain more knowledge about the query language.

To change the current Db to Flask DB use the command:

That’s it now you are in the new Flask DB.

Как подключить postgresql к flaskPostgres

2. Installing psycopg2 adapter tool

We also need pyscopg2, which is the PostgreSQL database adapter for Python. Let’s run the pip command:

3. Installing ORM packages for Flask

First we need to install Flask-SQLAlchemy ORM.

To install the package, simply run the code:

Also we need to install Flask-Migrate.

Flask-Migrate, uses Alembic which is a light Database migration tool. It helps us to Create/Update Databases and Tables. It also allows us to update an existing Table incase you delete or create new Table Fields.

To install Flask-Migrate, run:

Implementing a PostgreSQL database connection in Flask with SQLAlchemy

In this section, we will create a simple Flask application that stores user information in the Database.

1. Creating a Flask Model

A Model is a Python Class that represents a table in the Database. It contains information regarding the Table structure.

In Flask, it is more systematic to save all the DB information and the models in a separate file called – models.py situated right beside our main application file.

A typical models.py file looks like:

This is similar to a classic Python Class. These indicate the Fields of the Table and their representation.

Therefore, let us build a small InfoModel Table to store user information:

models.py:

2. Coding our Main Flask Application

Now we will connect Postgres with our Flask Application. The syntax is :

Also add the below Views in the app.py file.

apps.py:

We can interact with the Table just like a Class Object. We use:

3. Implementing the Flask Code

The last thing left is to run the migrations. Hence run the commands:

Now run the server

And lets check the Browser. Go to “/form

That’s it now in our PostgreSQL shell, Type:

And the data will be right there!!

Conclusion

Источник

Flask by Example – Setting up Postgres, SQLAlchemy, and Alembic

In this part we’re going to set up a Postgres database to store the results of our word counts as well as SQLAlchemy, an Object Relational Mapper, and Alembic to handle database migrations.

Free Bonus: Click here to get access to a free Flask + Python video tutorial that shows you how to build Flask web app, step-by-step.

Need the code? Grab it from the repo.

Install Requirements

Tools used in this part:

To get started, install Postgres on your local computer, if you don’t have it already. Since Heroku uses Postgres, it will be good for us to develop locally on the same database. If you don’t have Postgres installed, Postgres.app is an easy way to get up and running for Mac OS X users. Consult the download page for more info.

Once you have Postgres installed and running, create a database called wordcount_dev to use as our local development database:

In order to use our newly created database within the Flask app we to need to install a few things:

If you’re on OS X and having trouble installing psycopg2 check out this Stack Overflow article.

You may need to install psycopg2-binary instead of psycopg2 if your installation fails.

Update Configuration

Add SQLALCHEMY_DATABASE_URI field to the Config() class in your config.py file to set your app to use the newly created database in development (local), staging, and production:

Your config.py file should now look like this:

Now when our config is loaded into our app the appropriate database will be connected to it as well.

Similar to how we added an environment variable in the last post, we are going to add a DATABASE_URL variable. Run this in the terminal:

And then add that line into your .env file.

In your app.py file import SQLAlchemy and connect to the database:

Data Model

Set up a basic model by adding a models.py file:

Here we created a table to store the results of the word counts.

We first import the database connection that we created in our app.py file as well as JSON from SQLAlchemy’s PostgreSQL dialects. JSON columns are fairly new to Postgres and are not available in every database supported by SQLAlchemy so we need to import it specifically.

We then created an __init__() method that will run the first time we create a new result and, finally, a __repr__() method to represent the object when we query for it.

Local Migration

We are going to use Alembic, which is part of Flask-Migrate, to manage database migrations to update a database’s schema.

Note: Flask-Migrate makes use of Flasks new CLI tool. However, this article uses the interface provided by Flask-Script, which was used before by Flask-Migrate. In order to use it, you need to install it via:

Create a new file called manage.py:

In order to use Flask-Migrate we imported Manager as well as Migrate and MigrateCommand to our manage.py file. We also imported app and db so we have access to them from within the script.

In order to run the migrations initialize Alembic:

After you run the database initialization you will see a new folder called “migrations” in the project. This holds the setup necessary for Alembic to run migrations against the project. Inside of “migrations” you will see that it has a folder called “versions”, which will contain the migration scripts as they are created.

Let’s create our first migration by running the migrate command.

Now you’ll notice in your “versions” folder there is a migration file. This file is auto-generated by Alembic based on the model. You could generate (or edit) this file yourself; however, for most cases the auto-generated file will do.

Now we’ll apply the upgrades to the database using the db upgrade command:

The database is now ready for us to use in our app:

Источник

Using SQLAlchemy with Flask and PostgreSQL

Introduction

Databases are a crucial part of modern applications since they store the data used to power them. Generally, we use the Structured Query Language (SQL) to perform queries on the database and manipulate the data inside of it. Though initially done via dedicated SQL tools, we’ve quickly moved to using SQL from within applications to perform queries.

One such ORM is SQLAlchemy. In this post, we will delve deeper into ORMs and specifically SQLAlchemy, then use it to build a database-driven web application using the Flask framework.

What is an ORM and why use it?

That being said, as it’s fairly easy to map an object to a database, the reverse is also very simple. This eases the process of developing software and reduces the chances of making manual mistakes when writing plain SQL code.

Another advantage of using ORMs is that they help us write code that adheres to the DRY (Don’t Repeat Yourself) principles by allowing us to use our models to manipulate data instead of writing SQL code every time we need to access the database.

ORMs abstract databases from our application, enabling us to use multiple or switch databases with ease. Say, if we used SQL in our application to connect to a MySQL database, we would need to modify our code if we were to switch to an MSSQL database since they differ in syntax.

If our SQL was integrated at multiple points in our application, this will prove to be quite the hassle. Through an ORM, the changes we would need to make would be limited to just changing a couple of configuration parameters.

Even though ORMs make our life easier by abstracting the database operations, we need to be careful to not forget what is happening under the hood as this will also guide how we use ORMs. We also need to be familiar with ORMs and learn them in order to use them more efficiently and this introduces a bit of a learning curve.

SQLAlchemy ORM

SQLAlchemy is an ORM written in Python to give developers the power and flexibility of SQL, without the hassle of really using it.

SQLAlchemy wraps around the Python Database API (Python DBAPI) which ships with Python and was created to facilitate the interaction between Python modules and databases.

The DBAPI was created to establish consistency and portability when it came to database management though we will not need to interact with it directly as SQLAlchemy will be our point of contact.

While SQLAlchemy ORM makes our applications database-agnostic, it is important to note that specific databases will require specific drivers to connect to them. One good example is Pyscopg which is a PostgreSQL implementation of the DBAPI which when used in conjunction with SQLAlchemy allows us to interact with Postgres databases.

For MySQL databases, the PyMySQL library offers the DBAPI implementation require to interact with them.

SQLAlchemy can also be used with Oracle and the Microsoft SQL Server. Some big names in the industry that rely on SQLAlchemy include Reddit, Yelp, DropBox and Survey Monkey.

Having introduced the ORM, let us build a simple Flask API that interacts with a Postgres database.

Flask with SQLAlchemy

Flask is a lightweight micro-framework that is used to build minimal web applications and through third-party libraries, we can tap into its flexibility to build robust and feature-rich web applications.

In our case, we will build a simple RESTful API and use the Flask-SQLAlchemy extension to connect our API to a Postgres database.

Prerequisites

We will use PostgreSQL (also known as Postgres) to store our data that will be handled and manipulated by our API.

To interact with our Postgres database, we can use the command line or clients that come equipped with graphical user interfaces making them easier to use and much faster to navigate.

For Mac OS, I recommend using Postico which is quite simple and intuitive and provides a clean user interface.

PgAdmin is another excellent client that supports all major operating systems and even provides a Dockerized version.

We will use these clients to create the database and also view the data during the development and execution of our application.

With the installations out of the way, let us create our environment and install the dependencies we will need for our application:

The above commands will create and activate a virtualenv, install the Psycopg2 driver, install flask-sqlalchemy, and install Flask-Migrate to handle database migrations.

Flask-Migrate uses Alembic, which is a light database migration tool that helps us interact with our database in a much clearer way by helping us create and recreate databases, move data into and across databases, and identify the state of our database.

In our case, we will not have to recreate the database or tables every time our application starts and will do that automatically for us in case neither exists.

Implementation

We will build a simple API to handle and manipulate information about cars. The data will be stored in a PostgreSQL database and through the API we will perform CRUD operations.

First, we have to create the cars_api database using our PostgreSQL client of choice:

With the database in place, let’s connect to it. We’ll start by bootstrapping our Flask API in the apps.py file:

We start by creating a Flask application and a single endpoint that returns a JSON object.

For our demo, we will be using Flask-SQLAlchemy which is an extension specifically meant to add SQLAlchemy functionality to Flask applications.

Let us now integrate Flask-SQLAlchemy and Flask-Migrate into our app.py and create a model that will define the data about our cars that we will store:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The CarsModel is the model class that will be used to define and manipulate our data. The attributes of the class represent the fields we want to store in the database.

We define the name of the table by using the __tablename__ alongside the columns containing our data.

With our model in place, and Flask-Migrate integrated, let’s use it to create the cars table in our database:

We start by initializing the database and enabling migrations. The generated migrations are just scripts that define the operations to be undertaken on our database. Since this is the first time, the script will just generate the cars table with columns as specified in our model.

The flask db upgrade command executes the migration and creates our table:

In case we add, delete, or change any columns, we can always execute the migrate and upgrade commands to reflect these changes in our database too.

Creating and Reading Entities

We begin by defining a /cars route which accepts both GET and POST requests. The GET request will return a list of all cars stored in our database while the POST method will receive a car’s data in JSON format and populate our database with the information provided.

To create a new car, we use the CarsModel class and provide the information required to fill in the columns for our cars table. After creating a CarsModel object, we create a database session and add our car to it.

To save our car to the database, we commit the session through db.session.commit() which closes the DB transaction and saves our car.

Let’s try adding a car using a tool like Postman:

Источник

Использование SQLAlchemy с Flask и PostgreSQL

В настоящее время объектно-реляционные картографы, такие как SQLAlchemy, используются в качестве моста между приложениями и базами данных SQL и облегчают работу с ними программно.

Вступление

Базы данных являются важной частью современных приложений, поскольку они хранят данные, используемые для их питания. Как правило, мы используем Structured Query Language (SQL) для выполнения запросов к базе данных и манипулирования данными внутри нее. Хотя первоначально это делалось с помощью специальных инструментов SQL, мы быстро перешли к использованию SQL из приложений для выполнения запросов.

Естественно, со временем появились Объектно – реляционные картографы (ORM), которые позволяют нам безопасно, легко и удобно подключаться к нашей базе данных программно, не прибегая к фактическому выполнению запросов для манипулирования данными.

Что такое норма и зачем ее использовать?

Тем не менее, поскольку сопоставить объект с базой данных довольно легко, обратное также очень просто. Это облегчает процесс разработки программного обеспечения и снижает вероятность совершения ошибок вручную при написании простого SQL-кода.

Еще одно преимущество использования ORMS заключается в том, что они помогают нам писать код, который придерживается принципов DRY ( Don’t Repeat Yourself ), позволяя нам использовать наши модели для манипулирования данными вместо написания SQL-кода каждый раз, когда нам нужно получить доступ к базе данных.

Формирует абстрактные базы данных из нашего приложения, позволяя нам легко использовать несколько или переключать базы данных. Скажем, если бы мы использовали SQL в нашем приложении для подключения к базе данных MySQL, нам пришлось бы изменить наш код, если бы мы переключились на базу данных MSSQL, поскольку они отличаются синтаксисом.

Если наш SQL был интегрирован в нескольких точках нашего приложения, это будет довольно хлопотно. С помощью ORM изменения, которые нам нужно будет внести, будут ограничены простым изменением нескольких параметров конфигурации.

Несмотря на то, что ORMS облегчают нашу жизнь, абстрагируя операции с базой данных, мы должны быть осторожны, чтобы не забыть, что происходит под капотом, поскольку это также будет определять, как мы используем ORMS. Мы также должны быть знакомы с ORMS и изучать их, чтобы использовать их более эффективно, и это вводит некоторую кривую обучения.

SQLAlchemy ORM

SQLAlchemy – это ORM, написанный на Python, чтобы дать разработчикам мощь и гибкость SQL без хлопот его реального использования.

API DB был создан для обеспечения согласованности и переносимости, когда речь заходит об управлении базами данных, хотя нам не нужно будет взаимодействовать с ним напрямую, так как SQLAlchemy будет нашей точкой контакта.

Также важно отметить, что SQLAlchemy ORM построен поверх SQLAlchemy Core – который обрабатывает интеграцию DB API и реализует SQL. Другими словами, ядро SQLAlchemy предоставляет средства для генерации SQL-запросов.

Для баз данных MySQL библиотека PyMySQL предлагает реализацию DBAPI, необходимую для взаимодействия с ними.

SQLAlchemy также можно использовать с Oracle и Microsoft SQL Server. Некоторые крупные имена в отрасли, которые полагаются на SQLAlchemy, включают Reddit, Yelp, DropBox и SurveyMonkey.

Представив ФОРМУ, давайте построим простой API Flask, который взаимодействует с базой данных Postgres.

Колба с SQLAlchemy

Flask-это легкий микро-фреймворк, который используется для создания минимальных веб-приложений, и с помощью сторонних библиотек мы можем использовать его гибкость для создания надежных и многофункциональных веб-приложений.

В нашем случае мы построим простой RESTful API и используем расширение Flask-SQLAlchemy для подключения нашего API к базе данных Postgres.

Предпосылки

Мы будем использовать PostgreSQL (также известный как Postgres) для хранения наших данных, которые будут обрабатываться и манипулироваться нашим API.

Для взаимодействия с нашей базой данных Postgres мы можем использовать командную строку или клиенты, оснащенные графическими пользовательскими интерфейсами, что упрощает их использование и значительно ускоряет навигацию.

pgAdmin – еще один отличный клиент, который поддерживает все основные операционные системы и даже предоставляет докеризованную версию.

Мы будем использовать эти клиенты для создания базы данных, а также для просмотра данных во время разработки и выполнения нашего приложения.

С установками покончено, давайте создадим нашу среду и установим зависимости, которые нам понадобятся для нашего приложения:

Приведенные выше команды создадут и активируют virtualenv, установят драйвер Psycopg2, установят flask-sqlalchemy и установят Flask-Migrate для обработки миграции баз данных.

В нашем случае нам не придется воссоздавать базу данных или таблицы каждый раз, когда наше приложение запускается, и мы сделаем это автоматически для нас, если ни того, ни другого не существует.

Реализация

Мы создадим простой API для обработки и манипулирования информацией об автомобилях. Данные будут храниться в базе данных PostgreSQL, и через API мы будем выполнять CRUD-операции.

Имея базу данных на месте, давайте подключимся к ней. Мы начнем с начальной загрузки нашего API Flask в apps.py файл:

Мы начинаем с создания приложения Flask и одной конечной точки, которая возвращает объект JSON.

После импорта flask_sqlalchemy мы начинаем с добавления URI базы данных в конфигурацию вашего приложения. Этот URL-адрес содержит наши учетные данные, адрес сервера и базу данных, которую мы будем использовать для нашего приложения.

Модель Cars – это класс модели, который будет использоваться для определения и обработки наших данных. Атрибуты класса представляют поля, которые мы хотим сохранить в базе данных.

Мы определяем имя таблицы, используя __tablename__ рядом со столбцами, содержащими ваши данные.

С нашей моделью на месте и Flask-Migrate интегрированной, давайте использовать ее для создания таблицы cars в нашей базе данных:

Мы начинаем с инициализации базы данных и включения миграции. Сгенерированные миграции-это просто сценарии, которые определяют операции, которые будут выполняться в нашей базе данных. Поскольку это первый раз, скрипт просто сгенерирует таблицу cars со столбцами, указанными в нашей модели.

Команда flask db upgrade выполняет миграцию и создает нашу таблицу:

Создание и чтение сущностей

Давайте попробуем добавить автомобиль с помощью такого инструмента, как Почтальон:

Ответное сообщение уведомляет нас о том, что наш автомобиль был создан и сохранен в базе данных:

Вы можете видеть, что теперь в нашей базе данных есть запись об этом автомобиле.

С автомобилями, сохраненными в нашей базе данных, запрос GET поможет нам получить все записи. Мы запрашиваем все автомобили, хранящиеся в нашей базе данных, используя модель Cars.query.call() функция, предоставляемая Flask-SQLAlchemy.

Метод GET в конечной точке /cars возвращает список автомобилей в том виде, в каком они появляются в нашей базе данных, а также общее количество.

Примечание: Обратите внимание, что в коде нет ни одного SQL-запроса. SQLAlchemy заботится об этом за нас.

Обновление и удаление сущностей

Пока что мы можем создать один автомобиль и получить список всех автомобилей, хранящихся в базе данных. Чтобы завершить набор операций CRUD над автомобилями в нашем API, нам нужно добавить функциональность для возврата деталей, изменения и удаления одного автомобиля.

Метод PATCH просто изменяет тот, который у нас есть в нашей базе данных, не заменяя его. Поэтому, чтобы обновить запись CarsModel в нашей базе данных, мы должны предоставить все атрибуты вашего автомобиля, включая те, которые должны быть обновлены.

Наш автомобиль был успешно обновлен.

Наконец, чтобы удалить автомобиль, мы отправляем запрос DELETE в ту же конечную точку. Поскольку объект CarsModel уже запрошен, все, что нам нужно будет сделать, это использовать текущий сеанс, чтобы удалить его, выполнив db.session.delete(car) и фиксация нашей транзакции для отражения наших изменений в базе данных:

Вывод

Реальные приложения не так просты, как наши, и обычно обрабатывают данные, которые связаны и распределены по нескольким таблицам.

В этом посте мы представили ORMS и, в частности, SQLAlchemy ORM. Используя Flask и Flask-SQLAlchemy, мы создали простой API, который предоставляет и обрабатывает данные об автомобилях, хранящиеся в локальной базе данных PostgreSQL.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *