database setup: python

Step 1: Set Up Your Environment

  1. Install Python: Ensure Python is installed on your system. You can download it from python.org.
  2. Install Flask: Open your terminal or command prompt and run:
    bash
    pip install flask

Step 2: Create the Flask Project

  1. Create a new directory for your project:
    bash
    mkdir flask_blog
    cd flask_blog
  2. Create a file named app.py:
    bash
    touch app.py

Step 3: Set Up the Flask Application

In app.py, set up a basic Flask app:

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to My Flask Blog!"

if __name__ == '__main__':
    app.run(debug=True)

Run the app:

bash
python app.py

Visit http://127.0.0.1:5000/ in your browser. You should see “Welcome to My Flask Blog!”


Step 4: Add a Database

We’ll use SQLite for simplicity and SQLAlchemy to interact with the database.

  1. Install the required packages:
    bash
    pip install flask-sqlalchemy
  2. Update app.py to include the database setup:
    python
    from flask import Flask, render_template, request, redirect, url_for
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
    db = SQLAlchemy(app)
    
    class Post(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(100), nullable=False)
        content = db.Column(db.Text, nullable=False)
        author = db.Column(db.String(50), nullable=False)
    
        def __repr__(self):
            return f"Post('{self.title}', '{self.author}')"
    
    # Create the database
    with app.app_context():
        db.create_all()
    
    @app.route('/')
    def home():
        posts = Post.query.all()
        return render_template('home.html', posts=posts)
    
    if __name__ == '__main__':
        app.run(debug=True)

Step 5: Create Templates

  1. Create a folder named templates in your project directory:
    bash
    mkdir templates
  2. Inside the templates folder, create a file named home.html:
    html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Flask Blog</title>
    </head>
    <body>
        <h1>Welcome to My Flask Blog</h1>
        {% for post in posts %}
            <div>
                <h2>{{ post.title }}</h2>
                <p>{{ post.content }}</p>
                <p>By {{ post.author }}</p>
            </div>
        {% endfor %}
    </body>
    </html>

Step 6: Add a Form to Create Posts

  1. Update app.py to handle form submissions:
    python
    @app.route('/create', methods=['GET', 'POST'])
    def create():
        if request.method == 'POST':
            title = request.form['title']
            content = request.form['content']
            author = request.form['author']
            new_post = Post(title=title, content=content, author=author)
            db.session.add(new_post)
            db.session.commit()
            return redirect(url_for('home'))
        return render_template('create.html')
  2. Create a create.html template in the templates folder:
    html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Create Post</title>
    </head>
    <body>
        <h1>Create a New Post</h1>
        <form method="POST">
            <label for="title">Title:</label><br>
            <input type="text" id="title" name="title"><br><br>
            <label for="content">Content:</label><br>
            <textarea id="content" name="content"></textarea><br><br>
            <label for="author">Author:</label><br>
            <input type="text" id="author" name="author"><br><br>
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
  3. Add a link to the create page in home.html:
    html
    <a href="{{ url_for('create') }}">Create New Post</a>

Step 7: Run the Application

  1. Run the app:
    bash
    python app.py
  2. Visit http://127.0.0.1:5000/ to see your blog.
  3. Click “Create New Post” to add a new blog post.

Optional Enhancements

  • Add user authentication using Flask-Login.
  • Style your blog using Bootstrap or custom CSS.
  • Add functionality to edit or delete posts.
  • Use a more robust database like PostgreSQL or MySQL.