- Install Python in the system.
- Make a local folder in the disk (e.g., Flask Project).
- Open the folder in the command prompt by typing
cmdin the address bar. - Install virtual environment in the folder:
pip install virtualenv
- Create a virtual environment folder:
virtualenv env
- Activate the virtual environment by navigating to scripts:
cd env cd scripts activate
- Navigate back to the main folder:
cd .. - Install Flask in the virtual environment:
pip install Flask
- Check if Flask is successfully installed:
To exit, press
python import flask flask.__version__
ctrl + Z.
- Create a new Python file for Flask:
app.py.
- Basic flask code to start the flask app:
from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>"
- Run the Flask app to check if it's working:
flask --app app run
- Terminate the server in the cmd:
Ctrl + C
- Creating the basic folder to start:
static and templates
- Properties of the folders created:
a. Static folder is public in nature. b. Templates folder is private in nature. c. All the web components are created in the templates folder.(html, css, js)
- Importing the and Using of teh templates folder:
a. " from flask import Flask, render_template " command is used to import the templates. b. We use the return function to show the templates folder during the app run. c. return render_template('index.html') d. We can also use multiple html files by adding the route. e. @app.route("/name of the route")
- Dyanmaically updating the preview during the production:
app.run(debug=True){ for real time changes} - Passing of Variables to the html file:
a. Firstly in the app.py: variable="Rahul" return render_template('index.html', name=variable) b. Then to display it in the html file: {{name}} inside any tag
- Using the jinja(url_for):
Normal way: <img src=”static/img_name.png”> using the jinja: <img src="{{ url_for('static', filename='img_name.png') }}"> OR <link href="{{ url_for('static', filename='css/main.css') }}" rel="stylesheet">
- Using the jinja(for loop):
<ul> {% for user in users %} <li><a href="{{ user.url }}">{{ user.username }}</a></li> {% endfor %} </ul>
- Base html file format for the Inheritance:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML Page</title> </head> {% block body %} {% endblock %} </html>
- All the Inheritating classes:
{% extends "Base.html" %} {% block body %} <body> <!-- All content here --> </body> {% endblock %} - For further reference on the jinja read the documentation: https://jinja.palletsprojects.com/en/2.11.x/templates/
- Downloading the Xampp Application and Setting it up:
https://www.apachefriends.org/download.html
a. Keep the admin and the password default b. Default Admin will be "root" c. Default password will be "blank"
- Starting the Xampp Control panel:
a. Start the "Apache". b. Start the "MySQl". c. Everything should turn green over the apche and mysql. d. If Something goes wrong then check ( Task Manager>>Details and check the PID). e. End task armsvc.exe and everything should be fine.
- Opening the database in the browser: http://localhost/phpmyadmin/
- Create a new Database:
a. Go to http://localhost/phpmyadmin/ link, you will see a interface. b. Click on “New” to create a database c. Write your database name d. Create the database
- Create a new Table in the database:
a. Click on “Create”. b. Fill the table according to need. c. A_I section for thr primary key. A_I stands for Auto Incrementation. It means it will automatically increment value so that there is no repetition.
- Install flask-sqlalchemy in the system.
pip install flask-sqlalchemy or pip install flask_sqlalchemy
- Import this module in the python file.
from flask_sqlalchemy import SQLAlchemy
- To connect with the database first we have to give database’s address.
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'
- If do not set the user or the password during the installtion of the xammp the default values are:
username: root password: BLANK db_name: is the database name which we have setup app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/DATABASENAME' It should look shomething like this once configured.
- Importing the class and object from the sqlalchemy and to do so we have to make a variable:
db = SQLAlchemy(app)
- Once we have connected to the database we need to access the table in the python file:
class Contacts(db.Model): sno = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) phone_num = db.Column(db.String(12), nullable=False) msg = db.Column(db.String(120), nullable=False) date = db.Column(db.String(12), nullable=True) email = db.Column(db.String(20), nullable=False)
- Basic structure of a post request:
@app.route("/contact", methods = ['GET', 'POST']) def contact(): return render_template('index.html')
- Implementation of the POST method:
@app.route("/contact", methods = ['GET', 'POST']) def contact(): if(request.method=='POST'): '''Fetch data and add it to the database''' return render_template('index.html')
- Fetch data from the form and send to the database:
a. First add name attribute to the html: <input name="email" type="email" placeholder="Email Address"> b. We use the name attribute to locate the data from the form and send to data base: @app.route("/contact", methods = ['GET', 'POST']) def contact(): if(request.method=='POST'): '''Add entry to the database''' name = request.form.get('name') email = request.form.get('email') phone = request.form.get('phone') message = request.form.get('message') entry = Contacts(name=name, phone_num = phone, msg = message, date= datetime.now(),email = email ) db.session.add(entry) db.session.commit() return render_template('contact.html') c. Now to we need to add method and action in te html file, like this: <form name="sentMessage" action = "/contact" method="post" novalidate>
- After everything the main.py file should look something like this :
from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/codingthunder' db = SQLAlchemy(app) class Contacts(db.Model): sno = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) phone_num = db.Column(db.String(12), nullable=False) msg = db.Column(db.String(120), nullable=False) date = db.Column(db.String(12), nullable=True) email = db.Column(db.String(20), nullable=False) @app.route("/", methods = ['GET', 'POST']) def contact(): if(request.method=='POST'): '''Add entry to the database''' name = request.form.get('name') email = request.form.get('email') phone = request.form.get('phone') message = request.form.get('message') entry = Contacts(name=name, phone_num = phone, msg = message, date= datetime.now(),email = email ) db.session.add(entry) db.session.commit() return render_template('contact.html') app.run(debug=True)
- We will configure the Paramerters using the config.json .
- Firtsly we will create a config.json in the project directory.
- In the json file we will implement the configurationa s follows:
{ "params": { "websitename": "Flask-Project" } } - In the main.py file we will import the json file as follows:
import json with open('config.json', 'r') as c: params = json.load(c)["params"]
- Now we can simply use the json file to pass the parameters as we pass the variables:
params['websitename'] - Passing the json file to html to implement the configuration:
@app.route("/") def home(): return render_template('index.html', params=params)
- Implementing the json parameter in the HTML:
<h1>{{params['websitename']}}</h1>
- We can do the same for the links and any other variables that are needed:
pip install Flask
- In order to redirect the form data to the mail we can use te following code to so:
The above code is added to the if condition of the POST and GET class.
mail.send_message('New message from ' + name, sender=email, recipients = [params['gmail-user']], body = message + "\n" + phone )
- Install Flask library in the system.
- Link for the documentation : https://pythonhosted.org/Flask-Mail/ .
- Setting up Flask-Mail:
from flask_mail import Mail
- Code to configure Flask-mail in main.py:
app.config.update( MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = '465', MAIL_USE_SSL = True, MAIL_USERNAME = params['gmail-user'], MAIL_PASSWORD = params['gmail-password'] ) mail = Mail(app)
- Sending Message through Flask-Mail:
mail.send_message() - Configure the function file to send the mail:
mail.send_message('New message from ' + name, sender = "sender's email", recipients = "your-email", body = "message", )
- Getting data from the database table:
class Posts(db.Model): sno = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), nullable=False) slug = db.Column(db.String(21), nullable=False) content = db.Column(db.String(120), nullable=False) date = db.Column(db.String(12), nullable=True) img_file = db.Column(db.String(12), nullable=True) - Filtering the data :
@app.route("/post/<string:post_slug>", methods=['GET']) def post_route(post_slug): return render_template('post.html', params=params)
- Making a Slug from the webpage:
@app.route("/post/<string:post_slug/", methods=['GET']) def post_route(post_slug): post = Posts.query.filter_by(slug=post_slug).first() return render_template('post.html', params=params, post=post)
- Code to configure Flask-mail in main.py:
app.config.update( MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = '465', MAIL_USE_SSL = True, MAIL_USERNAME = params['gmail-user'], MAIL_PASSWORD = params['gmail-password'] ) mail = Mail(app)
- Displaying the post on the html file:
<h1>{{post.title}}</h1>
- Filtering and sending posts to HTMl:
posts = Posts.query.filter_by().all() or posts = Posts.query.filter_by().all()[0:5] or posts = Posts.query.filter_by().all()[0:params['no_of_posts']]
- To pass the filtered list we have to do the following using a new class :
@app.route("/") def home(): posts = Posts.query.filter_by().all()[0:params['no_of_posts']] return render_template('index.html', params=params, posts=posts)
- Using for loop in HTML:
{% for user in users %} <li><a href="{{ user.url }}">{{ user.username }}</a></li> {% endfor %}