Flask-Sqlalchemy: Sql Database Control for Flask

in utopian-io •  7 years ago  (edited)

What Will I Learn?

  • We will learn database operations for Flask projects.
  • We will learn to create relational database tables.
  • We will learn to test it in the Shell environment.

Requirements

  • Knowing Python
  • Using Flask
  • Knowing what is SQL, Relational Algebra and ORM

Difficulty

Those who are not interested in the database can be a little challenging. But overall it is basic.

Tutorial Contents

In this tutorial, I think we have a project produced for the flask. We need to store the data in this project. We will use SQLalchamy which is the most idea solution on Flask side to store this data.

Source : image

Introduction

SQLalchemy is an Object Relational Mapping library. It makes SQL expressions compatible with programming logic. It prevents long and unnecessary SQL statements from being written. Optimizes the database. It is capable of filtering, counting and bringing objects. It has many talents that we have not mentioned here. Let's go to the next step..

How to install Flask-Sqlalchemy?

  • I would suggest you build it on a shell. You can skip this step.

pip install virtualenv

mkdir project_dir
virtualenv -p python3 src
source src/bin/activate
cd project_dir
  • Install the flask-related setups and requirements of your project. Now install flask-sqlalchemy.

`` pip install flask-sqlalchemy```

It will complete the process by establishing its own requirements.

Implement

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
.
..

#Configration
Flask offers us a great opportunity in terms of configuration. The project has the following configuration options for `flask_sqlalchemy '.

NameExplanation
SQLALCHEMY_ECHOSQL expressions succeed to the terminal.
SQLALCHEMY_NATIVE_UNICODESets Unicode support.
SQLALCHEMY_DATABASE_URIThe database path is defined.
SQLALCHEMY_BINDSIs used to connect multiple databases.
SQLALCHEMY_POOL_ (SIZE-TIMEOUT -RECYCLE)Pool (size - timeout - reactivity)

Creating a Table Class

Database tables for ORM are defined as Class. Classes can communicate with each other. Classes can be set as meta_tag to be displayed to the user or displayed to Shell. Let's examine the example below.

  • Utopian Post and Tag Table :)
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tittle = db.Column(db.String(80), nullable=False)
    body = db.Column(db.Text, nullable=False)

    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'), nullable=False)
    tag = db.relationship('Tag', backref=db.backref('posts', lazy=True))

    def __repr__(self):
        return '<Post %r>' % self.title

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tag = db.Column(db.String(50), nullable=False)

    def __repr__(self):
        return '<Tag %r>' % self.tag
  • db.Model - Tables were created as inheritance.
  • db.Column - Created Column.
  • db.relationship - Relations set.
  • db.backref - Users in the other table will change.

Field Types

Field types that can be used in the columns.

Field
Integer
String
Text
Datetime
Float
Boolean

Use for example : db.Integer or db.String(150)

Try shell environment

We can check how the database tables we write work in the Shell environment. It will help you understand how this web service will behave. See example usage:

  • Call us first as Class. You will use this in your project. I create an object by defining the required field. We do not enter a string expression in relational tables. Be careful. We define it as an object.

1.png

  • We need to save our objem in the database after we create it. If we do not do this, the data will not be saved!

2.png

  • We can draw all the data on a table. We can do the filtering process. It is possible to perform complex operations.

3.png

Suggestion

Sqlalchemy users should pay attention to these.

  • There may be many different solutions to what you are looking for.
  • Do not query the database without saving the data. You will not have to process the updated data.
  • Define the secret key and do not share it.
  • Explore the database-specific SqlAlchemy configuration files you are using.



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Good job.

Thank you for the contribution. It has been approved.

Very interesting, I don't know much about databases, but this looks a lot better than what I'm currently using for my Flask application. Anyway a few notes about your tutorial:

  • Some formatting, spelling and grammar is wrong, try to make sure everything is in order before submitting.

You can contact us on Discord.
[utopian-moderator]

Thank you. I am trying to improve my English. I have pay more attention. :)

Thank you so much usefull

Hey @tolgahanuzun I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x