Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallThe reliable path is PostgreSQL installed from Ubuntu’s packages, a Python virtual environment containing FastAPI, Uvicorn, SQLAlchemy, Alembic and the appropriate PostgreSQL driver, then an environment-based connection URL, mapped models and migrations. Use psycopg2-binary with regular def endpoints for the simplest synchronous application, or asyncpg with SQLAlchemy’s asyncio support and async def endpoints when your whole request path is asynchronous.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
This guide builds both patterns on Ubuntu, explains where SQLModel fits, and shows how to move from an empty machine to a migrated API without putting database passwords in source code.
As an Amazon Associate I earn from qualifying purchases.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →What you are building
A FastAPI application does not contain a database layer by itself. You choose a relational database, a Python database driver, an ORM or SQL toolkit, and a migration tool. In the stack below, PostgreSQL stores the data, SQLAlchemy maps Python classes to tables, Alembic records schema changes, and FastAPI supplies HTTP routes and dependency injection.
- Database: PostgreSQL running as an Ubuntu service.
- Driver:
psycopg2-binaryfor synchronous SQLAlchemy orasyncpgfor asynchronous SQLAlchemy. - ORM: SQLAlchemy 2.x, whose current documentation has separate 2.0 and 2.1 lines.
- Migrations: Alembic, paired with SQLAlchemy.
- Web server: Uvicorn during development and deployment.
FastAPI’s official SQL tutorial chooses SQLModel, which combines SQLAlchemy and Pydantic. Its sample uses SQLite, but the tutorial states that any database supported by SQLAlchemy, including PostgreSQL, can be used. The SQLModel-based tutorial was added in FastAPI 0.115.1, released on October 12, 2024. You can therefore use SQLModel for a concise tutorial-style model layer, or use SQLAlchemy directly when you need explicit mappings and a conventional Alembic setup.
#1 Best Overall
- BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
- EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
- COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
- LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
- WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
Choose PostgreSQL and a driver before installing
Ubuntu’s packaged PostgreSQL
Ubuntu’s server documentation uses the distribution package and notes that it is configured with usable defaults:
sudo apt update
sudo apt install postgresql
sudo systemctl status postgresql
Ubuntu ships one fixed PostgreSQL major version for each Ubuntu release. That is convenient for a standard server, but it means sudo apt install postgresql is not a request for an arbitrary latest major release.
Free tools Windows power users keep installed
One-click scans. No signup required.
When you need a newer major release
Use the PostgreSQL project’s APT repository (PGDG) when your application requires a major version newer than the one supplied by your Ubuntu release. PGDG documents adding its repository and installing versioned packages such as postgresql-18. Follow the repository’s current Ubuntu instructions for the exact release codename and signing-key procedure; those details change as Ubuntu and PostgreSQL releases change. The PostgreSQL Linux download documentation also provides Ubuntu-specific PGDG instructions.
Do not mix an Ubuntu PostgreSQL package and a PGDG package casually on an existing server. Decide which major version and repository you will operate, then keep upgrades and backups aligned with that choice.
Synchronous or asynchronous Python?
| Choice | Install | URL scheme | Route functions | Migration consideration |
|---|---|---|---|---|
| Synchronous | psycopg2-binary |
postgresql+psycopg2:// (or SQLAlchemy’s PostgreSQL default) |
def |
Use the same synchronous URL in Alembic. |
| Asynchronous | sqlalchemy[asyncio] and asyncpg |
postgresql+asyncpg:// |
async def |
Alembic’s runner is synchronous; configure a synchronous migration URL, commonly by removing +asyncpg so the URL uses the synchronous PostgreSQL driver. |
Synchronous code is easier to follow and is the path used by many tutorials. Asynchronous code can fit an application that already performs asynchronous I/O, but it adds an async engine, async sessions and a separate migration URL. Do not make only the database call asynchronous while leaving the rest of the application unaware of the change.
Install and verify PostgreSQL on Ubuntu
Install the service
sudo apt update
sudo apt install postgresql
sudo systemctl status postgresql
The status command should show the service as active. If it is not running, inspect the service output before configuring the application:
Recommended Free Tools
sudo systemctl start postgresql
sudo systemctl enable postgresql
sudo journalctl -u postgresql --no-pager
The last two commands are service-management checks; use them only when the status indicates that PostgreSQL is stopped or failed.
Rank #2
- WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
- AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
- PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
- ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
- COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
Create an application role and database
Use the operating-system postgres account to open psql:
sudo -u postgres psql
Inside the prompt, create a login role with a password and a database owned by that role. Replace the example password with a strong secret that is not committed to your project:
CREATE ROLE game_api LOGIN PASSWORD 'replace-with-a-long-secret';
CREATE DATABASE game_data OWNER game_api;
q
Check the connection using the new role. The -h 127.0.0.1 option deliberately tests TCP rather than relying on a local Unix socket:
psql "postgresql://game_api:[email protected]:5432/game_data" -c "SELECT current_user, current_database();"
If the command succeeds, PostgreSQL, the role, the database and local authentication are working independently of FastAPI. If it fails, fix the database service, role password or PostgreSQL authentication configuration before debugging Python.
Create the FastAPI project
Make an isolated environment
mkdir fastapi-game-api
cd fastapi-game-api
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
Keep the virtual environment out of version control. A basic synchronous dependency set is:
python -m pip install fastapi uvicorn sqlalchemy alembic psycopg2-binary
For an asynchronous project, install the async SQLAlchemy extra and driver instead:
python -m pip install fastapi uvicorn "sqlalchemy[asyncio]" alembic asyncpg
Pin the versions you have tested in your project’s requirements or lock file. FastAPI, SQLAlchemy, Alembic, PostgreSQL and Ubuntu all evolve independently, so do not copy a secondary tutorial’s version numbers without checking the current package indexes and your supported Ubuntu release.
Rank #3
- Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
- Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
- Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
- ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
- Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
Use an environment variable for the URL
For local development, export a URL in your shell:
export DATABASE_URL='postgresql+psycopg2://game_api:[email protected]:5432/game_data'
A password containing characters such as @, :, / or # must be URL-encoded. In a deployed service, set the variable through the service manager or secret store rather than placing it in a committed .env file.
Suggested layout
fastapi-game-api/
├── app/
│ ├── __init__.py
│ ├── database.py
│ ├── models.py
│ └── main.py
├── alembic/
├── alembic.ini
└── requirements.txt
Build a synchronous SQLAlchemy connection
Define the engine, session factory and base
Create app/database.py:
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
DATABASE_URL = os.environ["DATABASE_URL"]
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
class Base(DeclarativeBase):
pass
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
pool_pre_ping=True makes SQLAlchemy test a pooled connection before using it, which helps recover from a database connection that was closed while idle. The dependency creates one session for a request and closes it in the finally block.
Map a table
Create app/models.py and import the base so Alembic can discover the model metadata:
from datetime import datetime
from sqlalchemy import DateTime, String, func
from sqlalchemy.orm import Mapped, mapped_column
from .database import Base
class Game(Base):
__tablename__ = "games"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200), nullable=False)
platform: Mapped[str] = mapped_column(String(80), nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
This model declares a numeric primary key, required title and platform fields, and a timestamp generated by PostgreSQL. It does not create the table automatically; Alembic will do that through a migration.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesAdd request and response schemas and a route
In app/main.py, use Pydantic models for the HTTP contract and SQLAlchemy for persistence:
from datetime import datetime
from fastapi import Depends, FastAPI, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from .database import get_db
from .models import Game
app = FastAPI()
class GameCreate(BaseModel):
title: str
platform: str
class GameRead(BaseModel):
id: int
title: str
platform: str
created_at: datetime
model_config = {"from_attributes": True}
@app.post("/games", response_model=GameRead, status_code=status.HTTP_201_CREATED)
def create_game(payload: GameCreate, db: Session = Depends(get_db)):
game = Game(title=payload.title, platform=payload.platform)
db.add(game)
db.commit()
db.refresh(game)
return game
@app.get("/games", response_model=list[GameRead])
def list_games(db: Session = Depends(get_db)):
return db.scalars(select(Game).order_by(Game.id)).all()
The commit makes the insert durable, and refresh loads database-generated values such as the primary key and timestamp. For larger applications, put transaction and repository logic in separate modules, but keep the same request-session lifecycle.
Create and apply Alembic migrations
Initialize Alembic
Run this once from the project root:
alembic init alembic
Alembic creates its configuration file and migration directory. Set the database URL through an environment variable rather than committing a password in alembic.ini. One straightforward development arrangement is to set the generated sqlalchemy.url value from the shell before running each command, but a production project should read DATABASE_URL inside Alembic’s environment file.
Rank #4
- Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
- Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
- 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
- Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
- USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
Point env.py at your metadata
Edit alembic/env.py so the model metadata is imported and assigned to target_metadata. The important lines for the synchronous project are:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →import os
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.database import Base
from app import models # registers mapped classes with Base.metadata
target_metadata = Base.metadata
config = context.config
if os.getenv("DATABASE_URL"):
config.set_main_option("sqlalchemy.url", os.environ["DATABASE_URL"])
Keep the rest of Alembic’s generated online and offline functions intact, including the call that passes target_metadata to context.configure. Importing app.models matters: without it, the metadata can be empty and autogenerate will see no tables.
Generate and apply the first revision
export DATABASE_URL='postgresql+psycopg2://game_api:[email protected]:5432/game_data'
alembic revision --autogenerate -m "create games table"
alembic upgrade head
Review the generated revision before applying it. Autogenerate compares metadata with the live schema; it is a starting point, not a guarantee that every semantic change has been detected. After upgrade head, inspect the database with psql if you need to confirm that the games table and Alembic version table exist.
Handle later schema changes
When you add a column or table, change the SQLAlchemy model, create a new revision and apply it:
alembic revision --autogenerate -m "add release year"
alembic upgrade head
Read and edit the revision, especially for renames, data migrations, non-null columns on existing rows and destructive operations. Commit migration files with the application code so every environment can be brought to the same revision in a repeatable order.
Use the asynchronous SQLAlchemy pattern
Install and configure the async engine
Install sqlalchemy[asyncio] and asyncpg, then use an postgresql+asyncpg:// URL:
export DATABASE_URL='postgresql+asyncpg://game_api:[email protected]:5432/game_data'
Replace app/database.py with an async engine and session factory:
Best Value
- Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
- Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
- Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
- Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
- Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
import os
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
DATABASE_URL = os.environ["DATABASE_URL"]
engine = create_async_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
async def get_db():
async with SessionLocal() as db:
yield db
Make routes and queries awaitable
from fastapi import Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@app.get("/games", response_model=list[GameRead])
async def list_games(db: AsyncSession = Depends(get_db)):
result = await db.scalars(select(Game).order_by(Game.id))
return result.all()
Writes likewise require await db.commit() and await db.refresh(game). Keep blocking libraries out of an async route; otherwise the event loop can still be blocked even though the function is declared with async def.
Give Alembic a synchronous URL
Alembic’s migration runner is synchronous. A common arrangement is to retain the async URL for the application and derive a migration URL by removing +asyncpg, producing a URL that uses the synchronous PostgreSQL driver. Install that driver in the environment used for migrations, or maintain a separate migration requirements set. Do not point Alembic at the async URL and assume it will automatically use the same execution path as your application.
Use SQLModel instead of direct SQLAlchemy when it fits
SQLModel is the choice in FastAPI’s official SQL tutorial. A SQLModel class can serve as both a validation model and an ORM table model, reducing repetition for small services. The tutorial demonstrates SQLite, but PostgreSQL is available through SQLAlchemy’s supported dialects. You still need a PostgreSQL URL, an appropriate driver and a migration strategy for a real deployment.
Choose direct SQLAlchemy when you need separate input/output schemas, advanced relationships, precise column types or an existing SQLAlchemy codebase. Choose SQLModel when shared schemas make the project clearer and its SQLAlchemy behavior meets your requirements. The database decision does not change the Ubuntu installation, role creation or driver rules described above.
Run and test the API
Start Uvicorn in development
source .venv/bin/activate
export DATABASE_URL='postgresql+psycopg2://game_api:[email protected]:5432/game_data'
uvicorn app.main:app --reload
The --reload option is for development. It restarts the process when source files change and should not be treated as a production process manager.
Exercise both write and read paths
curl -X POST http://127.0.0.1:8000/games
-H 'Content-Type: application/json'
-d '{"title":"Example Quest","platform":"Ubuntu"}'
curl http://127.0.0.1:8000/games
A successful POST should return HTTP 201 with an assigned id and created_at. The GET should return an array containing the inserted row. FastAPI also exposes interactive documentation at /docs while the development server is running.
Troubleshoot failures in the right order
- “Connection refused”: check
systemctl status postgresql, the host and port inDATABASE_URL, and whether PostgreSQL is listening on the address you selected. - “Password authentication failed”: verify the role name and password with a direct
psqlconnection. URL-encode special characters in the password. - “Database does not exist”: confirm the database name and that the role was created in the same PostgreSQL cluster.
- Autogenerate creates an empty revision: confirm that
env.pyimports every model module and assignsBase.metadatatotarget_metadata. - Async driver errors: check that the URL uses
postgresql+asyncpg://, the packageasyncpgis installed, and routes use anAsyncSessionwith awaited operations. - Migration errors in an async project: configure Alembic with a synchronous migration URL and ensure its driver is installed.
- Changes do not appear in the database: remember that changing a Python model does not alter PostgreSQL until a reviewed migration is generated and applied.
Prepare the setup for deployment
- Keep
DATABASE_URLin a secret-managed environment, not in Git, shell history shared with other users or application responses. - Use a dedicated application role rather than connecting as the PostgreSQL superuser.
- Run
alembic upgrade headas an explicit deployment step before starting code that expects the new schema. - Back up PostgreSQL and test restoring a backup before making destructive migrations.
- Pin and regularly update the versions of FastAPI, SQLAlchemy, Alembic, the driver and your Ubuntu packages.
- Choose one PostgreSQL packaging route—Ubuntu’s fixed release or PGDG’s versioned packages—and document the major version for operations and backups.
- Use a production process manager and reverse proxy appropriate to your hosting environment instead of relying on Uvicorn’s development reload mode.
- Set connection-pool limits deliberately when several Uvicorn workers or other services share the database; PostgreSQL connections are finite resources.
Which approach should you choose?
For a new, small API, install Ubuntu’s PostgreSQL package, use synchronous SQLAlchemy with psycopg2-binary, and let Alembic manage the schema. This has the fewest moving parts and keeps the migration URL identical to the application URL. Adopt async SQLAlchemy when the surrounding application already uses asynchronous clients or when you have a measured reason to keep database waits off synchronous workers; then plan for an async engine in the application and a synchronous URL for Alembic. SQLModel is a reasonable model-layer alternative when its combined validation and ORM style makes the code easier to maintain.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




