Creating the Index Page Of the Application
Before moving forward and building our form let’s create an index page for our website. The HTML file is always stored inside a folder in the parent directory of the application named ‘templates’. Inside the templates folder create a file named index.html and paste the below code for now. We will go back to adding more code into our index file as we move on.
<html>
<head>
<title>Index Page</title>
</head>
<body>
<h3>Profiles</h3>
</body>
</html>
In the app.py add a small function that will render an HTML page at a specific route specified in app.route.
from flask import Flask, request, redirect
from flask.templating import render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
# adding configuration for using a sqlite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
# Creating an SQLAlchemy instance
db = SQLAlchemy(app)
# Models
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(20), unique=False, nullable=False)
last_name = db.Column(db.String(20), unique=False, nullable=False)
age = db.Column(db.Integer, nullable=False)
def __repr__(self):
return f"Name : {self.first_name}, Age: {self.age}"
# function to render index page
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
To test whether everything is working fine you can run your application using the command
python app.py
The command will set up a local server at http://localhost:5000.
Output:
Flask and Sqlalchemy Tutorial for Database
Flask is a micro web framework written in python. Micro-framework is normally a framework with little to no dependencies on external libraries. Though being a micro framework almost everything can be implemented using python libraries and other dependencies when and as required.
Table of Content
- Installing Flask
- Creating app.py
- Setting Up SQLAlchemy
- Creating Models
- Creating the database
- Making Migrations in database
- Creating the Index Page Of the Application
- Creating HTML page for form
- Function to add data using the form to the database
- Display data on Index Page
- Deleting data from our database
In this article, we will be building a Flask application that takes data in a form from the user and then displays it on another page on the website. We can also delete the data. We won’t focus on the front-end part rather we will be just coding the backend for the web application.