Step-by-Step Guide for Creating Flask API with MariaDB on EC2
Step 1: Signing In
Sign in to your Management Console. Go to EC2.
Step 2: Launching Instance
Click on the âInstancesâ section in the left sidebar. Click the âLaunch Instanceâ button to start the instance creation process.
Then enter the appropriate Name of instance, for example MyInstance and select instance type as Amazon Linux 2 AMI(HVM) -Kernel 5.10, SSD volume Type in Application and OS Images. Select t2.micro as instance type.
Step 3: Creating Key Pair(.pem)
Choose an existing key pair if you have one, or create a new one. If you create a new key pair, make sure to download the private key file (.pem) and store it securely.
Step 4: Configuration to Launch Instance
Create a new security group or choose an existing one. Open ports for SSH (22), HTTP (80), Custom TCP(8080) to Run Flask API, MySQL/Aurora(3306). Review your settings and launch the Instance by clicking the Launch Instance Button
Step 5: Connecting to Instance
We can see our Instance (MyInstance) in EC2 instance Dashboard. Select the check box of our Instance and go to Action and click on Connect to Connect the Instance.
Step 6: Checking Python Version
Enter the following command in the console to check the Python Version.
python3 --version
if Python is not installed then enter following command.
sudo apt-get install python3
Step 7: Installing MariaDB Server
Run the following command for installing mariadb-server
sudo yum install -y mariadb-server
This command will install the MariaDB server.
After install MariaDB server start using
sudo systemctl start mariadb
Use this command for start MariaDB service automatically
sudo systemctl enable mariadb
Step 8: Accessing MariaDB Shell
Access the MariaDB shell
mysql -u root
create a new database for your Flask app using SQL commands
CREATE DATABASE mydb
Use the new created Database and create a Table using SQL command
CREATE TABLE users (id INT PRIMARY KEY, username VARCHAR(20), password VARCHAR(20))
To Insert Data in Table using SQL command
INSERT INTO users (username, password) VALUES ('Harsh', 'Harsh'), ('Ram', 'Ram')
Step 9: Save Flask App
After exiting from MySQL and Create a Directory to save your Flask app code and its related file.
mkdir Web
cd Web
Step 10: Setup Flask Environment
Setup Flask environment, For creating virtual environment
python3 -m venv exflask
Activate the virtual environment
source exflask/bin/activate
Step 11: Install Flask Package using pip
Install the Flask package using pip
pip3 install Flask
This command install the Flask package, which help us to create an web application in python.Access the mysql in your flask app to install flask-mysqllab package.
pip3 install Flask-MySQLdb
.If you get an error like this.
We have to Install some dependencies to avoid the error.
âpip install mysqlclient>=1.3.7
These commands install necessary dependencies allow to the âmysqlclientâ package to Flask app.
Step 12: Writing Code for Flask App
Leatâs create Flask app.
touch app.py
This command creates an empty file which contains your Flask application code.
To write your application code in app.py file ,Using
nano app.py
This command opens the app.py file in the nano editor, you write and edit your code hear.
Inside the âapp.pyâ file, youâll write your Flask application code.
Python
from flask import Flask, render_template, request, redirect, url_for from flask_mysqldb import MySQL app = Flask(__name__) app.config[ 'MYSQL_HOST' ] = 'localhost' app.config[ 'MYSQL_USER' ] = 'root' app.config[ 'MYSQL_PASSWORD' ] = '' app.config[ 'MYSQL_DB' ] = 'mydb' mysql = MySQL(app) @app .route( '/login' , methods = [ 'GET' , 'POST' ]) def login(): if request.method = = 'POST' : uname = request.form[ 'uname' ] pas = request.form[ 'pas' ] mysql_cur = mysql.connection.cursor() query = "SELECT * FROM users WHERE username = " + uname mysql_cur.execute(query) user_info = mysql_cur.fetchone() mysql_cur.close() if user_info and user_info[ 2 ] = = pas: return "Login successful!" else : return "Login failed. Please try again." return render_template( 'login.html' ) app.run(host = '0.0.0.0' , port = 8080 ) |
Step 13: Creating Templates
Inside your main project directory create a subdirectory named âtemplatesâ
mkdir templates && cd templates
Within the âtemplatesâ directory, create a new HTML file named login.html
touch login.html
This command creates an empty login.html file, which youâll write your login page code.
nano login.html
Inside the âlogin.htmlâ file, paste the following HTML code to define the structure of your login page template
HTML
<!DOCTYPE html> < html > < head > < title >Login Page</ title > </ head > < body > < h1 >Login Page</ h1 > {% if error_message %} < p >{{ error_message }}</ p > {% endif %} < form method = "POST" > < label for = "username" >Username:</ label > < input type = "text" id = "uname" name = "uname" >< br >< br > < label for = "password" >Password:</ label > < input type = "password" id = "pas" name = "pas" >< br >< br > < input type = "submit" value = "Login" > </ form > </ body > </ html > |
Step 14: Running Flask App
Navigate to Your main Project Directory âWebâ and Run Your Flask App
python3 app.py
This command starts the Flask development server
Open your browser and open AWS console navigate EC2 and select your instance public IP copy it and past it in URL and at last add â:8080â to access our flask app (ec2-public-ip:8080).
For going Login page write
â(ec2-public-ip:8080/loginâ
Enter a username and password to test the login functionality.
How to Create a Flask API with MariaDB on AWS EC2
In this article, We are going to create an ec2 instance, install a MySQL database using MariaDB on the ec2 instance, and create an API of Login using the flask python framework. Flask is a micro web framework written in Python. MariaDB is one of the most popular open-source relational database management systems and could be used as a great replacement for MySQL. AWS ec2 instance allows users to rent virtual computers on which to run their computer applications, installing and Running MYSQL on EC2 Server(Linux)