DEV Community

Ankithajitwta
Ankithajitwta

Posted on

Flask: A Guide to Building Web Applications with Python

Hey Reader,
My name is Ankitha, I'm working as junior software developer at Luxoft India. I've written an article on Basic Flask which we will be using on daily basis . So grateful that Luxoft has given me an opportunity to learn new concepts every day, hoping to continue the same. Happy reading !

Introduction:

Flask, a micro net framework for Python, has gained recognition for its simplicity, flexibility, and ease of use. Unlike large frameworks, Flask affords a minimalist technique, allowing builders to pick and integrate the components they need. In this article, we're going to discover the important thing ideas of Flask and offer code snippets to guide you through the system of constructing an internet utility.

  1. Getting Started with Flask To begin the use of Flask, you first want to install it. You can do that the usage of the subsequent command:
pip set up Flask
Enter fullscreen mode Exit fullscreen mode

Once Flask is hooked up, you may create a easy "Hello World" software:

# app.Py


from flask import Flask

app = Flask(__name__)

@app.Direction('/')
def hello_world():
    go again 'Hello, World!'

if __name__ == '__main__':
    app.Run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Run the application the usage of:

 app.Py

Visit http://127.Zero.0.1:5000/ to your net browser, and you have to see the "Hello, World!" message.
Enter fullscreen mode Exit fullscreen mode
  1. Routing and Views Flask makes use of decorators to define routes and companion them with perspectives. Let's create a greater complicated instance with more than one routes:
# app.Py

from flask import Flask, render_template

app = Flask(__name__)

@app.Route('/')
def domestic():
    cross lower back 'Home Page'

@app.Course('/approximately')
def about():
    pass lower back 'About Page'

@app.Course('/touch')
def contact():
    return 'Contact Page'

if __name__ == '__main__':
    app.Run(debug=True)
Enter fullscreen mode Exit fullscreen mode

In this situation, journeying /, /about, and /touch will show one-of-a-type pages.

Three. Templates with Jinja2
Flask integrates with the Jinja2 templating engine, allowing you to create dynamic HTML templates. First, create a templates folder to your project list. Then, regulate the preceding instance to apply templates:


# app.Py

from flask import Flask, render_template

app = Flask(__name__)

@app.Route('/')
def domestic():
    return render_template('home.Html')

@app.Course('/about')
def approximately():
    move back render_template('approximately.Html')

@app.Course('/contact')
def touch():
    go back render_template('touch.Html')

if __name__ == '__main__':
    app.Run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Create HTML templates within the templates folder similar to every path.

Four. Handling Forms
Flask simplifies shape dealing with. Let's create a simple shape and process it the usage of Flask-WTF (a Flask integration for WTForms).


pip set up Flask-WTF
Enter fullscreen mode Exit fullscreen mode
# app.Py

from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField

app = Flask(__name__)
app.Config['SECRET_KEY'] = 'your_secret_key'

beauty ContactForm(FlaskForm):
    name = StringField('Name')
    email = StringField('Email')
    publish = SubmitField('Submit')

@app.Path('/touch', strategies=['GET', 'POST'])
def contact():
    shape = ContactForm()
    if form.Validate_on_submit():
        # Process the form records (e.G., ship an e-mail)
        move back 'Form submitted efficaciously!'
    return render_template('contact_form.Html', form=shape)

if __name__ == '__main__':
    app.Run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Now, let's modify our Flask app to include database functionality:

# app.py



from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'  # Use SQLite for simplicity
db = SQLAlchemy(app)

class Contact(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(120), nullable=False)

db.create_all()

class ContactForm(FlaskForm):
    name = StringField('Name')
    email = StringField('Email')
    submit = SubmitField('Submit')

@app.route('/contacts', methods=['GET', 'POST'])
def contacts():
    form = ContactForm()

    if form.validate_on_submit():
        new_contact = Contact(name=form.name.data, email=form.email.data)
        db.session.add(new_contact)
        db.session.commit()
        return redirect(url_for('contacts'))

    contacts_list = Contact.query.all()
    return render_template('contacts.html', form=form, contacts=contacts_list)

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Conclusion

Flask's simplicity and versatility make it an super preference for building internet programs, whether or not or now not you're a newbie or an experienced developer. As you discover Flask in addition, you could find out extensions and integrations that beautify its talents, together with Flask-RESTful for constructing APIs or Flask-SQLAlchemy for database interactions. Flask's energetic community and sizeable documentation offer ample resources for developers at all ranges. Happy Flasking!

Top comments (0)