Home » Colleges » Simple Blogging Web App using Flask, SQL,Glassmorphism

Simple Blogging Web App using Flask, SQL,Glassmorphism

In this article, we will explore how to create a basic blogging web application using Flask, a popular Python web framework. The app will allow users to view blog posts, add new posts, and delete existing ones. We will cover each aspect step-by-step, ensuring easy comprehension for readers of all ages, including 5th-grade students.

Simple Blogging Web App using Flask, SQL, and Glassmorphism By Nilesh Community

What is Flask?

Before we jump right in, let’s take a quick sip of knowledge and understand what Flask is all about. Flask is a fantastic Python web framework that allows us to build web applications effortlessly. It’s lightweight, flexible, and provides just the right ingredients to whip up a scrumptious web app!

Prerequisites

Before we dive into building the web app, make sure you have the following:

  1. Python installed on your computer.
  2. Basic understanding of Python and HTML.

Setting up Flask and the Database

First, let’s set up our Flask application and configure it to use a SQLite database with SQLAlchemy. SQLAlchemy helps us interact with the database efficiently.

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

app = Flask(__name__, template_folder='template')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///Nileshblog.db'
db = SQLAlchemy(app)

# Model for the blog posts
class Nileshblogpost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    subtitle = db.Column(db.String(50))
    author = db.Column(db.String(20))
    date_posted = db.Column(db.DateTime)
    content = db.Column(db.Text)

Here, we import necessary modules and create our Flask app instance. We also configure the database URI to point to an SQLite database named “Nileshblog.db”. Then, we define the Nileshblogpost class to represent our blog posts using SQLAlchemy.

Creating the Home Page

The home page will display all the blog posts in descending order based on the date they were posted.

@app.route('/')
def index():
    posts = Nileshblogpost.query.order_by(Nileshblogpost.date_posted.desc()).all()
    return render_template('index.html', posts=posts)

In this route, we use the index function to fetch all blog posts from the database and pass them to the index.html template for rendering.

Creating the About Page

We will add a simple About page to provide additional information about the website.

@app.route('/about')
def about():
    return render_template('about.html')

Here, when a user visits /about URL, the about function is called to render the about.html template.

Viewing Individual Blog Posts

Users can view a single blog post by clicking on it. We will use the post ID to identify and display the specific post.

@app.route('/blog/')
@app.route('/post/')
def post(post_id):
    post = Nileshblogpost.query.filter_by(id=post_id).one()
    return render_template('post.html', post=post)

This route has two URL patterns: /blog/ and /post/. Both patterns map to the post function. We use the post_id parameter to query the specific post from the database and pass it to the post.html template for rendering.

Adding a New Blog Post

Next, we will allow users to add new blog posts. This requires an authentication mechanism, so we will use the requires_auth decorator (not shown in code).

@app.route('/add')
@requires_auth
def add():
    return render_template('add.html')

@app.route('/addcontent', methods=['POST'])
def addpost():
    title = request.form['title']
    subtitle = request.form['subtitle']
    author = request.form['author']
    content = request.form['content']
    post = Nileshblogpost(title=title, subtitle=subtitle, author=author, content=content, date_posted=datetime.now())
    db.session.add(post)
    db.session.commit()
    return redirect(url_for('index'))

The add function is responsible for rendering the add.html template, which allows users to enter details for a new blog post. The addpost function is triggered when the form in add.html is submitted. It retrieves form data and creates a new Nileshblogpost object, which is then added to the database.

Deleting a Blog Post

Lastly, we will enable users to delete blog posts they no longer wish to keep.

@app.route('/deleteContent', methods=['DELETE', 'POST'])
def deletepost():
    post_id = request.form.get("post_id")
    post = Nileshblogpost.query.filter_by(id=post_id).first()
    db.session.delete(post)
    db.session.commit()
    return redirect(url_for('index'))

The deletepost function handles deleting a blog post. It retrieves the post ID from the form data and deletes the corresponding post from the database.

Generating Sitemap

A sitemap is essential for search engine optimization (SEO) to help search engines crawl and index your website efficiently.

@app.route('/sitemap')
@app.route('/sitemap/')
@app.route('/sitemap.xml')
def sitemap():
    # Generate sitemap
    # ...
    response = make_response(xml_sitemap)
    response.headers["Content-Type"] = "application/xml"
    return response

In the sitemap function, we generate the XML sitemap containing static URLs and dynamic URLs from the database. This helps search engines navigate and index our website effectively.

Outputs

Site which is built using this above code is

You can check it out by googling it o google.com : Newss.pythonanywhere.com,technilesh.com

How to Host Web App

Time needed: 10 minutes

You can host your Flask app on Pthonanywhere hosting with just 10 steps. if you occur any error comment error. we will try to solve it. You can Avaible your site on google in just 10 minutes.

  1. Step 1: Sign Up for PythonAnywhere

    If you don’t already have an account on PythonAnywhere, visit https://www.pythonanywhere.com/ and sign up for a free account.

  2. Step 2: Set Up a Virtual Environment

    In your PythonAnywhere account, navigate to the “Consoles” tab and click on “Start a new console.” Choose “Bash” as the console type. Once the console is started, create a virtual environment for your Flask app:

    mkvirtualenv myflaskapp –python=/usr/bin/python3.8

    Replace “myflaskapp” with the name you want for your virtual environment.

  3. Step 3: Upload Your Flask App Files

    Now, you need to upload your Flask app files to PythonAnywhere. You can use the “Files” tab to upload your app’s code files and any necessary templates and static files.

  4. Step 4: Install Dependencies

    In the console, activate your virtual environment:

    Copy code
    workon myflaskapp

    Then, install Flask and any other dependencies your app requires:

    pip install Flask

  5. Step 5: Configure WSGI File

    Create a WSGI file that will tell PythonAnywhere how to run your Flask app.
    In the console, navigate to the “Web” tab:

    bash
    Copy code
    cd /var/www/<your_pythonanywhere_username>_pythonanywhere_com_wsgi.py

    Edit the existing WSGI file (usually named “flask_app.py”) or create a new one:
    bash

    nano flask_app.py

    Add the following code to the WSGI file, adjusting the paths and app names as needed:
    python
    Copy code
    from your_flask_app import app as application
    import sys path = ‘/home/<your_pythonanywhere_username>/path/to/your/app’
    if path not in sys.path:
    sys.path.append(path)

  6. Step 6: Configure Flask App

    Ensure that your Flask app is set up to run in production mode. For example, change the app.run() line to the following:
    python

    if __name__ == ‘__main__’: app.run(host=’0.0.0.0′)

  7. Step 7: Configure Static Files

    In the “Web” tab, configure the static files path. Set the URL and directory to point to your static files:
    URL: /static/ Directory: /home/<your_pythonanywhere_username>/path/to/your/app/static/

  8. Step 8: Reload Web App

    In the “Web” tab, click the “Reload” button to apply the changes.

  9. Step 9 :Visit Your Flask Web App

    Your Flask web app should now be up and running on PythonAnywhere! You can access it by going to your PythonAnywhere account’s URL, followed by the path to your app.

    For example: http://<your_pythonanywhere_username>.pythonanywhere.com

    That’s it! Your Flask web app is now deployed and accessible on PythonAnywhere. Enjoy your culinary journey in the world of Flask, SQL, and Glassmorphism!

Faq on Simple Blogging Web App using Flask, SQL,Glassmorphism

Q1: How do I install Flask on my computer?

A: To install Flask, you can use pip, a package manager for Python. Open your command prompt or terminal and run: pip install Flask.

Q2: Can I use a different database instead of SQLite?

A: Yes, you can use other databases supported by SQLAlchemy, such as MySQL, PostgreSQL, or Oracle. Just change the database URI in the configuration accordingly.

Q3: Is Flask suitable for large-scale web applications?

A: While Flask is great for small to medium-sized projects, it might not be the best choice for large-scale applications. For such projects, you may consider using more robust frameworks like Django.

Q4: How do I handle user authentication in my Flask app?

A: Flask provides various extensions for handling user authentication, such as Flask-Login and Flask-Security. You can choose the one that best fits your requirements.

Q: Can I deploy my Flask app to a production server?

A: Yes, you can deploy your Flask app to a production server. Popular options include using Apache with mod_wsgi, Gunicorn, or uWSGI. Make sure to follow best practices for security and performance when deploying to production

Conclusion

In this tutorial, we learned how to build a simple blogging web application using Flask. Users can view, add, and delete blog posts, and we ensured that the explanations are easy to understand, even for 5th-grade students. Additionally, we implemented essential SEO techniques like creating a sitemap for better search engine visibility. This project can be a great starting point for aspiring web developers looking to dive into web development with Flask. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *