Invite a friend, get 1 month of Pro freeHow it works

opencode Flask: practical guide for Flask developers

Use opencode on Flask projects: set up AGENTS.md, run a test-driven loop, and get reliable blueprint, Jinja, SQLAlchemy, and pytest changes from your CLI.

Solviera Teknoloji 6 min read

opencode is a terminal coding agent that works directly in a Flask project folder. For Flask developers, the key to good results is an explicit AGENTS.md and a test-first workflow: the agent reads project instructions, edits blueprints, templates, models, and tests, then runs pytest and reports the diff. This guide assumes you already know Flask and want to use opencode for everyday changes safely. See the opencode documentation and the step-by-step guide if you need setup first.

How opencode handles Flask’s context and conventions

Flask projects reward structure, but that structure varies a lot: single-file apps, packages, blueprints, application factories, Flask-SQLAlchemy or raw SQLAlchemy. opencode becomes useful when you encode your choices in AGENTS.md and keep the test suite fast. It can follow Flask conventions if they are stated, such as where blueprints live, how routes are registered, and how db and migrate are initialized. Because the agent runs terminal commands, it can execute python -m pytest, flask routes, and flask db migrate and use the output to adjust its next edit. It also handles Jinja and SQLAlchemy well when it knows the context: route variables passed to templates and model relationships defined in code. The main risk is not the agent but context drift; if AGENTS.md is stale, the agent will follow old conventions.

Preparing the Flask repo with AGENTS.md

Create or update AGENTS.md in the repository root before starting opencode. The file should contain the commands opencode is allowed to run, the folder layout, and Flask-specific rules. Be exact with commands because the agent uses them as its safe path. Do not describe every line of code; describe invariants. A realistic AGENTS.md looks like this:

# AGENTS.md

## Commands
- install: python -m pip install -r requirements.txt
- run: flask --app wsgi.py run
- test: python -m pytest
- lint: ruff check .
- format: ruff format .
- migrations: flask --app wsgi.py db migrate -m 'change description'

## Layout
- app/ uses an application factory in app/__init__.py: create_app()
- blueprints live in app/blueprints/<name>.py and are registered in create_app
- models live in app/models.py and use the db object from app/extensions.py
- templates live in app/templates/<blueprint>/<name>.html
- static assets live in app/static/<blueprint>/
- tests live in tests/ with fixtures in tests/conftest.py

## Flask rules
- Always use url_for instead of hard-coded URLs.
- Return JSON from API blueprints with jsonify; return HTML from page blueprints with render_template.
- Keep request handlers thin; put reusable logic and validation in app/services.py.
- Do not hard-code secrets or configuration values; read from app.config.
- Do not add a new dependency without updating requirements.txt.
- When adding a model, create a migration with flask db migrate but do not edit existing migration files.
- In tests, use the application factory with a temporary SQLite database and drop all tables after each test.

Keep AGENTS.md under version control. When you change conventions, update it before asking opencode to refactor. If you use Flask-SQLAlchemy, say whether db is in app/extensions.py or app/__init__.py; that one line prevents many circular-import fixes.

A repeatable test-first loop for Flask changes

Work in small, verifiable steps. For each task, ask opencode to describe its plan, make the edit, run the relevant tests, and show git diff before you accept. Do not ask for a large refactor and a new feature in the same prompt. Typical prompts for a Flask project:

  • Add a users blueprint with /register and /login routes using the existing User model. Put form validation in services.py and keep route handlers under ten lines.
  • Create a Jinja macro for form field errors and replace the repeated error markup in app/templates/auth/login.html and register.html. Keep the markup the same and run pytest after.
  • Add a SQLAlchemy model Post with title, body, created_at, and a relationship to User. Show me the generated migration command but do not run it unless I approve.
  • Write pytest fixtures for an in-memory SQLite app using the application factory. Cover GET /health and POST /auth/login with valid and invalid input.
  • Refactor create_app to register blueprints from a list instead of individual calls. Update all blueprint files to match and run pytest; report any failures.

After each prompt, review the diff with git diff or your normal review tool. If the agent proposes a regression, ask it to revert only that file and explain why. This loop keeps Flask’s implicit context assumptions visible: app context, request context, and current_app use.

Flask pitfalls to watch when reviewing opencode’s diff

opencode handles many Flask tasks well once conventions are explicit, but it can also reproduce common Flask mistakes if you let it. The table below summarizes the main areas.

Flask areaGood promptWatch closely
BlueprintsAdd a posts blueprint with list and detail routes; register it in create_app.Duplicate endpoint function names, missing import in factory, wrong url_prefix.
Jinja templatesReplace repeated form errors with a macro; keep the same class names.Undefined variables in inherited templates, missing url_for calls, autoescape on raw HTML.
SQLAlchemy modelsAdd Comment model with user and post relationships and cascades.Lazy loading in templates, session commit outside app context, migration autogenerate missing constraints.
Application factoryMove config loading into create_app and avoid circular imports.Extensions initialized twice or before app exists, circular imports between models and extensions.
TestsAdd parametrized tests for login validation using the test client.Test database isolation, missing app context in fixtures, false positives from shared state.

The pitfalls are specific because Flask uses global proxies such as current_app, g, request, and session. opencode may write code that accesses these outside a request or app context. Always run pytest after such changes and ask it to add a test when context handling matters. For SQLAlchemy, watch for code that assumes the session remains open after the view returns; Flask-SQLAlchemy removes the session at teardown, and lazy attribute access in a template can raise DetachedInstanceError. For Jinja, undefined variables in templates can silently render empty if configured with undefined=Undefined; if you want strict behavior, set that in AGENTS.md.

Keeping Flask tests fast and trustworthy with opencode

The test suite is the contract. Before trusting opencode, make sure pytest runs quickly and covers at least route status codes, JSON shape, and template rendering. Good Flask test fixtures include an app fixture from the application factory with a temporary SQLite database and a client fixture. Ask opencode to use python -m pytest -q after each change and not to edit tests merely to make them pass unless the test expectation is wrong. After tests pass, run flask routes to confirm new endpoints are registered under the expected rules. Check ruff check . and ruff format --check . if configured. For Jinja, render each template in a test with the same variables the view passes to catch undefined names. For SQLAlchemy, use db.drop_all() and db.create_all() in fixtures or transaction rollback to isolate tests. Do not accept changes that add a new route without at least a smoke test.

Running multiple opencode agents on a Flask repo with AgentVera

AgentVera is a desktop app that runs opencode and other coding agents’ real command line tools side by side in one window. For Flask work, the most useful parts are parallel agents in separate git worktrees, so one agent can add a blueprint while another updates Jinja templates without overwriting files. After each turn, automatic code review flags issues such as missing app context or unsafe SQLAlchemy queries. Checkpoints let you undo a bad refactor of the application factory in one click. Token budgets stop a long agent session before it burns budget while preserving the conversation.

Final notes for Flask and opencode

opencode is a practical choice for Flask work when you treat context as code. Keep AGENTS.md current, prefer small prompts, run pytest often, and review the diff for Flask-specific context and registration issues. With those habits, opencode can add blueprints, templates, models, and tests without forcing you to hold every app-factory detail in your head. For broader CLI agent comparisons, see the best AI coding tools page.

Questions

How do I start opencode on a Flask project?

Run opencode in the project root. It reads AGENTS.md for project instructions, so create that file first with Flask commands, layout, and conventions.

Can opencode edit Flask blueprints and Jinja templates together?

Yes, if AGENTS.md describes your blueprint and template layout, opencode can add routes, register blueprints, and update the related Jinja files while following your conventions.

Does opencode run pytest and Flask CLI commands?

Yes, opencode can run python -m pytest, flask routes, and flask db commands in the terminal and use their output to fix failures. Keep commands in AGENTS.md.

How do I prevent opencode from breaking my Flask app factory?

Tell it in AGENTS.md to avoid circular imports, initialize extensions in the factory, and run pytest after changes; review the diff for app context and registration order.

Bring your agents to one desk.

Download AgentVera for free; your installed CLIs are ready to go.

More opencode guides

Other agents for Flask