Welcome back SE nerds!! I'm back with another blog to talk about everything you'll need to know about Python Flask! Flask is an awesome addition to being a full-stack developer, bringing the backend dynamics and the next step to put the frontend and backend together!
This first thing you should be familiar with is an extension called Flask-SQLAlchemy (pronounced 'sequel alchemy'). This extension is a great Object-Relational Mapping tool that allows you to work with databases! An example of code that uses SQLAlchemy, will look like this:
Another good thing to know is about relationships. These can be one-to-many or many-to-many relationships between tables that are setup using the 'db.relationship' method. A one-to-many relationship is a single record linked to multiple records. This is what that code would look like:
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('posts', lazy=True))
Many-to-many relationships means the records in one table can be linked to multiple records in another table, and vice versa. Code for this will look something like this:
A really cool feature to use with Flask is the use of APIs. Flask can handle APIs in various formats, including JSON. This is what a code for this will look like:
REST or Representational State Transfer is also good to know for Flask. This is an architectural style that uses HTTP requests to access and use data. Flask routes can handle RESTful operations defined by HTTP methods like GET, POST, PUT, DELETE. This code will look like This:
Constraints and Validations are key to having a legitimate backend. These ensure data integrity and correctness. In FLask-SQLAlchemy, these can be applied directly at the model level as shown in this example:
Cookies are also a good thing to know about. These are small pieces of data stored in the user's browser. Flask reads cookies easily. Here's an example of code using Cookies:
Authentication is also a good tool to know. This involves identifying users and allowing them access to certain resources. This is an example of code using authorization:
Password protection as you can guess, is an important tool when using personal data for a user. Passwords should be securely stored by hashing them before they're saved to the database. Flask uses libraries such as Flask-Bcrypt for this. Here's an example of how password protection works:
I hope you found this helpful, and if there are any errors or you would like to comment, feel free!!
Top comments (0)