Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask ImportError: cannot import name app

Tags:

python

flask

After setting up a simple Flask app from this tutorial, with a run.py file containing:

from site import app
import os

app.secret_key = os.urandom(24)
app.run(debug=True)

I have site/__init__.py with

from .views import app
from .models import graph

And under site/views.py

from .models import User, get_todays_recent_posts
from flask import Flask, request, session, redirect, url_for, render_template, flash

app = Flask(__name__)

with a bunch of @app.route functions

site/models.py has

from py2neo import Graph, Node, Relationship
from passlib.hash import bcrypt
from datetime import datetime
import os
import uuid

graph = Graph()

I keep getting a ImportError: cannot import name app error on the first line of run.py.

All the other questions seem to be a circular import issue, but I'm sure I don't have one.

I haven't created a virtual environment as described in the project, could that be the issue?

I'm using python2.7 on windows.

EDIT:

A fix to the problem was to restructure entire project into one .py file, which feels like a cleaner file structure anyway.

like image 403
Marthinus Bosman Avatar asked May 05 '18 14:05

Marthinus Bosman


2 Answers

Look at the source code

You'll see in site/__init__.py

from  .views import app 

This declares app in the site module, therefore allowing you to use this at the run module

from site import app

Otherwise, you need

 from site.views import app 
like image 72
OneCricketeer Avatar answered Nov 16 '22 09:11

OneCricketeer


app is defined within site.views, so you need to import it from there.

from site.views import app
like image 45
Daniel Roseman Avatar answered Nov 16 '22 09:11

Daniel Roseman