Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Fix Flask WSGI ImportError: Cannot Import Name App

A practical guide to Flask WSGI ImportError: cannot import name app, with exact Gunicorn and Flask CLI targets, factory and wsgi.py patterns, circular-import fixes, and environment checks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“ImportError: cannot import name app” means the WSGI loader found a Python module but could not obtain an object named app from it. Fix it by making the deployment target match the module and exported object—for example, gunicorn myapp:app for a direct Flask instance, or gunicorn 'myapp:create_app()' for an application factory. If the name is correct, inspect the first traceback failure for a circular import, an import-time exception, or a working-directory/Python-path mismatch.

What the error actually means

A WSGI server does not run your Flask file as a script. It imports a module, then looks up the attribute named after the colon in its target. In gunicorn package.wsgi:app, Gunicorn imports package.wsgi and searches for an attribute called app. The Flask object must exist under that exact name when import finishes.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Therefore, cannot import name app usually indicates one of four conditions:

  • The target points to the wrong module, such as gunicorn app:app when the object lives in myproject/__init__.py.
  • The module exists, but its Flask instance has another name, such as application or flask_app.
  • The module began importing but failed before defining the object. A circular import commonly produces the phrase partially initialized module.
  • The process starts in a different directory or Python environment, so its import path is not the one you tested locally.

This is different from ModuleNotFoundError. A module-not-found error means Python could not locate the module at all; an import-name error generally means Python located it but could not finish loading the requested attribute.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Start with the first traceback failure

Read the traceback from the bottom upward, but pay attention to the earliest exception in your own code. The final Gunicorn line often reports only the consequence of an earlier failure.

  • ImportError: cannot import name 'app' from 'myapp': check the exported variable, import order, and target string.
  • ImportError: cannot import name 'app' from partially initialized module ...: look for two modules importing each other while the Flask object is still being created.
  • ModuleNotFoundError: No module named ...: correct the package path, current directory, virtual environment, installation, or PYTHONPATH before investigating the object name.
  • A traceback from configuration, extensions, or route code: fix that exception first. The WSGI loader cannot expose an object if module initialization aborts.

Do not keep changing the Gunicorn command while an import-time exception remains. The command can be syntactically correct and still fail because application setup never reaches the line that defines app.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make the WSGI target match your code

The general target form is module:object. The module is a Python import path, not normally a filename ending in .py; the object is the exported Flask instance or factory.

Code layout Correct target examples What the server imports
myapp.py contains app = Flask(__name__) gunicorn myapp:app
flask --app myapp run
Module myapp, attribute app
myapp.py contains application = Flask(__name__) gunicorn myapp:application Module myapp, attribute application
myapp/__init__.py defines create_app() gunicorn 'myapp:create_app()'
flask --app 'myapp:create_app()' run
Package myapp, then calls the factory
wsgi.py defines application = create_app() gunicorn wsgi:application Module wsgi, attribute application
package/wsgi.py defines app gunicorn package.wsgi:app Module package.wsgi, attribute app

Use the fully qualified dotted path when the file is inside a package. A file at src/myapp/wsgi.py is not necessarily targeted as wsgi:app; if src is the project root on the import path, the target is usually myapp.wsgi:app.

Factory targets need parentheses because the server must call the function and receive a Flask application. Without them, myapp:create_app exports the function itself. Some shells interpret parentheses, so quote the complete target as shown above.

Fix a direct Flask instance

A direct instance creates the application when the module is imported:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from flask import Flask

app = Flask(__name__)

@app.get('/')
def home():
    return 'OK'

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

For this file saved as myapp.py, start local development with flask --app myapp run or production import with gunicorn myapp:app. The variable name is significant. If your code says web = Flask(__name__), then the target must be myapp:web; renaming the target to myapp:app does not create an alias.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Keeping app.run() inside if __name__ == '__main__': prevents a WSGI import from starting Flask’s development server. When Gunicorn imports myapp, the condition is false, so import returns the application object instead of blocking in a local server.

Flask’s quickstart documents automatic discovery for files named app.py or wsgi.py when using the Flask command. That convenience does not mean every WSGI server can infer your object name. Also avoid naming your own file flask.py; it can shadow the Flask package and cause confusing import failures.

Fix an application factory

A factory delays application construction until the loader calls it. This is useful when you need different configurations, multiple app instances in tests, or a package that should not create global state during import.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config.from_mapping(
        SECRET_KEY='replace-this-in-real-configuration'
    )

    from .views import bp
    app.register_blueprint(bp)
    return app

With this layout in myapp/__init__.py, use gunicorn 'myapp:create_app()'. Flask’s command accepts the same factory notation: flask --app 'myapp:create_app()' run. If your factory is called make_app, target myapp:make_app() instead. Flask’s documented discovery recognizes common names such as app, application, create_app, and make_app, but an explicit target is clearer and is required for other names.

Do not put request handling or a development server at module level in a factory module. The factory should complete configuration, extension initialization, blueprint registration, and other setup before returning. A WSGI server then calls the returned Flask object for each request.

Use a dedicated wsgi.py shim when deployment expects it

Some hosting systems conventionally look for wsgi.py. A small shim makes the exported name unambiguous:

from myapp import create_app

application = create_app()

Point the server at wsgi:application. If you instead write app = create_app(), point it at wsgi:app. The filename alone does not determine the exported variable; the part after the colon still has to match.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

A shim is also useful when your package has a complicated internal layout. It gives the process manager one stable import path while the package remains free to reorganize its factories and views.

Break circular imports and “partially initialized module” errors

Python adds a module to its import table before executing the whole file. If module A imports module B and B immediately imports A, B may see A before A has defined app. Python then reports that the name cannot be imported from a partially initialized module.

A common failing arrangement looks like this:

# myapp/__init__.py
from flask import Flask
from .views import bp       # views imports app below

app = Flask(__name__)
app.register_blueprint(bp)

# myapp/views.py
from . import app            # app does not exist yet

Create the object before importing modules that need it, or move to a factory pattern:

# myapp/__init__.py
from flask import Flask

def create_app():
    app = Flask(__name__)
    from .views import bp
    app.register_blueprint(bp)
    return app

# myapp/views.py
from flask import Blueprint

bp = Blueprint('main', __name__)

@bp.get('/')
def home():
    return 'OK'

The local import inside create_app() is deliberate: the Flask object exists before the blueprint module is loaded and registered. Other valid fixes include moving shared constants into a third module that imports neither the app nor the routes, importing an extension object without binding it to a specific app, or registering routes after construction.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not solve every cycle by adding arbitrary imports at the bottom of files. That can hide the dependency problem and produce a different failure later. Draw the import direction explicitly: configuration and extensions should not import route modules that, in turn, import the application object.

Use current_app instead of importing the global app

Flask’s application context exposes the active application through current_app. Code that runs during a request, CLI command, or an explicitly pushed application context can use it without importing the module that created the app:

from flask import current_app

def read_setting():
    return current_app.config['SECRET_KEY']

Importing a global app instance throughout a large project couples every module to the creation module and increases circular-import risk. For reusable extensions and factories, define the extension independently and initialize it inside the factory, then access configuration through current_app when an application context is active.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

current_app is not a substitute for an application context. Calling it in a standalone script or background thread without a pushed context raises a different “working outside of application context” error. In those cases, pass the needed value explicitly or use with app.app_context(): around code that genuinely requires Flask context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the working directory and Python environment

A command that works in a terminal can fail under a service manager because the service starts elsewhere, uses another virtual environment, or does not include your project root on sys.path.

  1. Activate the same virtual environment used by Gunicorn or the hosting service.
  2. Change to the project directory that contains the package, or configure the service’s working directory explicitly.
  3. Run a direct import check with the exact target components. For a direct instance, use python -c "from myapp import app; print(app)".
  4. For a factory, use python -c "from myapp import create_app; print(create_app())". If this fails, fix the displayed exception before starting Gunicorn.
  5. Confirm that the interpreter and Gunicorn belong to the same environment with python -c "import sys; print(sys.executable)" and which gunicorn on Unix-like systems.
  6. Use the complete package path, including parent packages. A missing __init__.py, an incorrect source-directory layout, or an uninstalled package can change what Python imports.

If a platform offers separate fields for a start command, working directory, and Python path, configure all three consistently. A target such as myapp.wsgi:app is only valid when Python can import myapp.wsgi from that process’s path.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep development startup separate from production WSGI startup

Flask is a WSGI application. The built-in development server is intended for local development; production should use a dedicated WSGI server or a hosting platform. A production command imports your object, while flask run is a development workflow that discovers an app and launches Flask’s development server.

These commands are not interchangeable:

Purpose Example Important behavior
Local direct-instance development flask --app myapp run Flask locates the module and starts its development server.
Local factory development flask --app 'myapp:create_app()' run Flask calls the factory, then starts development mode.
Production direct instance gunicorn myapp:app Gunicorn imports the module and serves the exported callable.
Production factory gunicorn 'myapp:create_app()' Gunicorn calls the factory and serves the returned app.

Complete all setup before handling requests. Flask’s lifecycle documentation emphasizes that the WSGI server calls the Flask object after application setup; route registration, configuration, and extension initialization should not continue unpredictably after serving begins.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Targeted fixes for common command and code mistakes

The file is named correctly but the variable is different

Inspect the assignment that creates the Flask object. Change the command to the real name, such as gunicorn myapp:application, or deliberately add app = application if you want the conventional target. Keep one canonical name where possible to avoid deployment drift.

The target includes a filename extension

Use an import path, not myapp.py:app. The normal form is myapp:app. For nested files, replace directory separators with dots: package/wsgi.py becomes package.wsgi:app.

The factory was supplied without a call

Use create_app() in a target that supports factory notation. A server that receives only create_app may treat the function as the WSGI callable and fail when it expects the two-argument WSGI interface.

The server starts from the wrong directory

Set the service working directory to the project root, install the package into the active environment, or use the full dotted package path. Avoid relying on an interactive shell’s accidental PYTHONPATH.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Importing the module starts a server

Move app.run() below an if __name__ == '__main__': guard. A WSGI import should construct and return the application without opening a development-server loop.

The import works once and then fails after a rename

Remove stale bytecode only if necessary, check for another file with the old module name, and print the loaded module’s location with python -c "import myapp; print(myapp.__file__)". Python may be importing a different package or file than the one you edited.

Choose the least risky application structure

Approach Best fit Strengths Risks to manage
Direct instance in one module Small applications and simple deployments Few moving parts; target is easy to read Global creation can encourage circular imports and makes alternate configurations harder.
Factory in a package Multiple configurations, tests, or growing applications Creates independent app instances and keeps setup explicit Every deployment target must call the factory; import order still matters for blueprints.
Explicit wsgi.py shim Platforms with a fixed WSGI filename or teams wanting a stable entry point Separates deployment wiring from internal package layout The shim’s exported variable must match the target exactly.

There is no universal requirement to rename your application to app. The reliable rule is consistency: document the module, exported object or factory, working directory, and exact startup command together.

Final verification checklist

  • The traceback’s first application error has been fixed.
  • The target’s module imports with a plain Python command in the same environment as the server.
  • The text after the colon exactly matches an exported instance, or the factory target includes parentheses.
  • Package directories and the process working directory produce the same dotted import path you tested locally.
  • Routes and blueprints are imported only after the application exists, or are registered inside a factory at the appropriate point.
  • Modules use current_app where an application context is appropriate instead of importing the app everywhere.
  • app.run() is protected by the main-module guard and is not part of production import.
  • All configuration and extension setup completes before the WSGI server begins handling requests.

Once these checks pass, an error that says the loader cannot import app should either disappear or become a more specific exception pointing to the remaining application bug. That specificity is useful: fix the underlying Python exception rather than changing the WSGI target blindly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.