This article discusses streamlining the main.py file by removing redundant imports and outdated code snippets for improved clarity and maintainability.
In this lesson, we focus on streamlining our main.py file by removing redundant imports and outdated code snippets. With the migration of our routes to designated folders and the adoption of SQLAlchemy for database interactions, many of the previously used imports are now obsolete. Below, we outline the changes made and provide detailed examples for better clarity.Many unused imports appear grayed out in your IDE. For example, consider the following block of code that once included multiple imports and a raw database connection:
The code for connecting to the database using the traditional Postgres driver is now redundant because SQLAlchemy is managing our database connections. It is recommended to either move this logic into the database.py file for future reference or remove it completely.
For documentation purposes, here is how the section originally looked before the changes were implemented:
Copy
Ask AI
from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker, declarative_basefrom psycopg2.extras import RealDictCursorimport psycopg2engine = create_engine(SQLALCHEMY_DATABASE_URL)SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)Base = declarative_base()def get_db(): db = SessionLocal() try: yield db finally: db.close()while True: try: conn = psycopg2.connect( host='localhost', database='fastapi', user='postgres', password='password123', cursor_factory=RealDictCursor ) cursor = conn.cursor() print("Database connection was successful!") break except Exception as error: print("Connecting to database failed") print("Error:", error)
Since SQLAlchemy now handles our database operations, the raw SQL connection is obsolete and can be safely deleted from the main.py file. Only the necessary functions and modules from the database module need to be imported.Next, we remove additional unused imports and helper functions. Earlier versions of main.py included elements from typing, status, Body, Pydantic, and even the Postgres library, which are no longer utilized after integrating the database. For example, the following code block demonstrated older implementations that are now redundant:
Copy
Ask AI
from typing import Optional, Listfrom fastapi import FastAPI, Response, status, HTTPException, Dependsfrom fastapi.params import Bodyfrom pydantic import BaseModelfrom random import randrangeimport psycopg2from psycopg2.extras import RealDictCursorimport timefrom sqlalchemy.orm import Sessionfrom sqlalchemy.sql.functions import modefrom . import models, schemas, utilsfrom .database import engine, get_dbfrom .routers import post, user, authmodels.Base.metadata.create_all(bind=engine)app = FastAPI()my_posts = [ {"title": "title of post 1", "content": "content of post 1", "id": 1}, {"title": "favorite foods", "content": "I like pizza", "id": 2}]
Additionally, helper functions like the ones below have become unnecessary:
Copy
Ask AI
def find_post(id): for p in my_posts: if p['id'] == id: return pdef find_index_post(id): for i, p in enumerate(my_posts): if p['id'] == id: return i
Removing these unused sections not only makes your main.py file cleaner but also improves maintainability by reducing clutter. The focus is now solely on the application’s main functionality.
The final cleaned-up version of main.py is structured more succinctly. It now only imports the modules required for the proper functioning of the application and includes the essential routers. The refined file is as follows:
With these changes, the application is free from redundant code and unused imports, making it easier to maintain and enhancing overall code clarity. This optimization is key for better project scalability and improved performance.