Creating a web application using Flask is a fantastic way to delve into web development. In this guide, we will walk you through the process of setting up a simple web application, configuring a database, and rendering dynamic content.
How to Create a Simple Web Application Using Flask
Flask is a lightweight web framework in Python that makes it easy to get a web application up and running. We will use Flask to create a basic web app with a simple database. Follow along with this course on YouTube by freeCodeCamp.
Step 1: Setting Up Flask
First, ensure you have Flask installed in your Python environment. You can install Flask using pip:
bashCopy codepip install flask
Next, set up a basic Flask application in a new Python file (e.g., app.py
):
pythonCopy codefrom flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'
db = SQLAlchemy(app)
Step 2: Creating the Database
One of the issues learners face is creating the database file as shown in the video. If you don’t see the .db
file in your folder, you can create it manually using the Python terminal. Open your terminal and run the following commands:
pythonCopy codefrom market import app, db
app.app_context().push()
db.create_all()
This will create the market.db
file in your project directory.
Step 3: Defining the Database Model
With the database set up, let’s define a model for our items:
pythonCopy codeclass Item(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(length=30), nullable=False, unique=True)
price = db.Column(db.Integer(), nullable=False)
barcode = db.Column(db.String(length=12), nullable=False, unique=True)
description = db.Column(db.String(length=1024), nullable=False, unique=True)
def __repr__(self):
return f'Item {self.name}'
Step 4: Creating Routes
Flask allows you to create routes to handle different pages on your website. Here are a few example routes:
pythonCopy code@app.route('/')
@app.route('/home')
def home_page():
return render_template('home.html')
@app.route('/about/<username>')
def about_page(username):
return f'<h1>This is the about page of {username}</h1>'
@app.route('/market')
def market_page():
items = Item.query.all()
return render_template('market.html', items=items)
Step 5: Running Your Application
To run your Flask application, use the following command in your terminal:
bashCopy codepython app.py
Visit http://127.0.0.1:5000/
in your web browser to see your app in action.
Conclusion
Creating a simple web application using Flask is a great way to get started with web development. By following the steps outlined in this guide, you can set up a basic application, configure a database, and create dynamic content. Remember, learning web development is a gradual process, and every step you take brings you closer to mastering this skill.
How to Fix Black Screen Issue with Non-Lighting Keyboard on Dell XPS 15Z L511Z