Loading...

Building Your First Web App with Flask and Python

Welcome to this comprehensive guide on building your first web application with Flask and Python. Flask is a micro web framework for Python that allows you to build web applications quickly and with minimal complexity. In this blog post, we will guide you step-by-step through the process of building a simple web app using Flask and Python. By the end of this tutorial, you will have a solid understanding of how Flask works and how to build a basic web app with it. Let's get started!

Getting Started with Flask

Before we dive into building our web app, we need to ensure that we have Python installed on our machine. You can check your Python installation by running python --version or python3 --version in your terminal or command prompt. If you don't have Python installed, you can download it from the official Python website.

Once you have Python installed, you can install Flask using pip. Open your terminal or command prompt and run the following command:

pip install Flask

With Flask installed, we're now ready to start building our web app.

Creating a Basic Flask App

To create a basic Flask app, we'll start by creating a new folder for our project. Name it something like my_first_flask_app. Inside this folder, create a new file called app.py. This file will contain the main code for our web app. Open app.py in your favorite code editor and add the following lines of code:

from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello, Flask!" if __name__ == '__main__': app.run()

Here's a breakdown of what this code does:

  1. We import the Flask class from the flask module.
  2. We create an instance of the Flask class called app.
  3. We define a route by using the @app.route decorator, which maps a URL to a Python function. In this case, we're mapping the root URL ("/") to the hello function.
  4. Inside the hello function, we return a simple string "Hello, Flask!".
  5. Finally, we run the Flask app if the script is being run directly (not imported as a module).

To test our basic Flask app, navigate to the project folder in the terminal or command prompt, and run the following command:

python app.py

You should see the following output:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Open your web browser and navigate to http://127.0.0.1:5000/. You should see the message "Hello, Flask!" displayed in your browser.

Building a Simple Web App

Now that we have a basic Flask app up and running, let's expand on it by building a simple web app that allows users to submit their name and receive a personalized greeting.

Creating HTML Templates

Flask uses the Jinja2 templating engine to render HTML templates. First, we need to create a folder named templates inside our project folder. Inside the templates folder, create two new HTML files: index.html and greeting.html.

Open index.html and add the following code:

<!doctype html> <html> <head> <title>My First Flask App</title> </head> <body> <h1>Welcome to My First Flask App!</h1> <form action="/greet" method="POST"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name" required> <input type="submit" value="Greet me!"> </form> </body> </html>

This HTML code creates a simple form that asks the user to input their name. When the form is submitted, it sends a POST request to the /greet URL.

Next, open greeting.html and add the following code:

<!doctype html> <html> <head> <title>Greeting</title> </head> <body> <h1>Hello, {{ name }}!</h1> <p><a href="/">Go back</a></p> </body> </html>

This template displays a personalized greeting based on the user's input. The {{ name }} syntax is a Jinja2 placeholder that will be replaced with the user's name when the template is rendered.

Handling Form Submissions

Now that we have our templates, we need to modify our Flask app to handle form submissions and render the appropriate templates.

Open app.py and update it with the following code:

from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/greet', methods=['POST']) def greet(): name = request.form['name'] return render_template('greeting.html', name=name) if __name__ == '__main__': app.run()

Here, we've made the following changes:

  1. We imported the render_template and request functions from the flask module.
  2. We updated the hello function to index and changed its return statement to render the index.html template.
  3. We added a new route and function, greet, which handles the form submission. It gets the user's name from the form data, and then renders the greeting.html template with the user's name.

Restart the Flask app by pressing CTRL+C in the terminal or command prompt, and then running python app.py again. Navigate to http://127.0.0.1:5000/ in your browser, enter your name in the form, and click "Greet me!" You should see a personalized greeting based on your input.

FAQ

How can I deploy my Flask app to a web server?

There are several options for deploying your Flask app to a web server, such as using a platform-as-a-service (PaaS) provider like Heroku or a virtual private server (VPS) like DigitalOcean. The Flask documentation provides a deployment guide with more information on various deployment options.

How can I use a database with my Flask app?

Flask does not include built-in support for working with databases, but there are several popular extensions available that make it easy to integrate your Flask app with a database. Some popular choices are Flask-SQLAlchemy (for working with relational databases) and Flask-MongoDB (for working with MongoDB). You can find more information about these extensions in the Flask documentation's extensions section.

How can I add user authentication to my Flask app?

To add user authentication to your Flask app, you can use the Flask-Login extension, which provides a simple and secure way to handle user authentication. The Flask-Login documentation includes a quickstart guide#quickstart) that walks you through the process of setting up user authentication in your Flask app.

Can I use Flask to build a RESTful API?

Yes, Flask is an excellent choice for building RESTful APIs. You can use the Flask-RESTful extension to simplify the process of building a RESTful API with Flask. The Flask-RESTful documentation provides a quickstart guide to help you get started.

How can I serve static files (CSS, JavaScript, images) with Flask?

To serve static files with Flask, create a folder named static in your project directory. You can then store your CSS, JavaScript, and image files inside this folder. In your HTML templates, you can use the url_for function to generate URLs for your static files, like this:

<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> <script src="{{ url_for('static', filename='scripts.js') }}"></script> <img src="{{ url_for('static', filename='image.jpg') }}" alt="An example image">

Flask will automatically serve the files located in the static folder when requested by the browser.

Conclusion

Congratulations! You've successfully built your first web app using Flask and Python. By following this tutorial, you've learned the basics of Flask, including how to create routes, handle form submissions, and render HTML templates. We've also covered some frequently asked questions about Flask, such as deploying your app, working with databases, adding user authentication, building RESTful APIs, and serving static files.

As you continue to explore Flask, you'll find that it's a powerful and flexible web framework that can help you build a wide variety of web applications. Keep learning and experimenting, and you'll be well on your way to becoming a Flask expert!

Sharing is caring

Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far