Everything was working fine, the imports have always worked and my project structure has not changed. I made some changes - adding fields & forms, and suddenly all the relative imports in my app/main/views.py stopped working. I reverted my changes - that did not work either. Help!
Update: So it runs fine from the command line with "flask run", but not in PyCharm. So I'm thinking it's PyCharm config issue. My config.py file has not changed at all, so I think it's here: PyCharm Run/Debug Config
I did not intentionally make ANY changes to the config.... so not sure what the next step is here. If anyone has advice on the config for this project, I would be grateful!
Here's the project structure. App, Auth and Main are shown as packages:
Project Structure
Here's the main app demo.py:
import os
from app import create_app, db
from app.models import Org, User, Role, DemoType, DemoReport, DemoRptQ, \
Demo, Question, Answer, Location
from flask_migrate import Migrate
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(app, db)
#app.shell_context_processor
def make_shell_context():
return dict(db=db, Org=Org, User=User, Role=Role, Location=Location,
DemoType=DemoType, DemoReport=DemoReport, DemoRptQ=DemoRptQ, Demo=Demo,
Question=Question, Answer=Answer)
#app.cli.command()
def test():
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
Here's the app init.py
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
And the app/main package init.py:
from flask import Blueprint
main = Blueprint('main', __name__)
from . import views, errors
from ..models import Permission
#main.app_context_processor
def inject_permissions():
return dict(Permission=Permission)
And finally the app/main views.py, where I am getting the error on the third line from .. import db
from datetime import datetime
from flask import render_template, session, redirect, url_for, flash
from .. import db
from ..models import User, Role, Location, Demo, Question, Answer, DemoType, DemoReport, DemoRptQ
from ..email import send_email
from . import main
from .forms import DashboardForm, EditProfileForm, EditProfileAdminForm, DemosForm, DemoForm
from .forms import QuestionsForm, QuestionForm, DemoTypesForm, DemoTypeForm, DemoReportsForm, DemoReportForm
from .forms import AnswerForm, AnswersForm, LocationsForm, LocationForm
from .forms import UsersForm
from flask_login import login_required, current_user
from ..decorators import admin_required
from wtforms.validators import DataRequired, Optional, Length
#main.route('/', methods=['GET', 'POST'])
def index():
form = DashboardForm()
if form.validate_on_submit():
btn = form.submit.raw_data[0]
if btn == 'Demos':
return redirect(url_for('.demos_list'))
elif btn == 'New Demo':
return redirect(url_for('.edit_demo', id=0))
elif btn == 'Login':
return redirect(url_for('auth.login'))
elif btn == 'Register':
return redirect(url_for('auth.register'))
return render_template('index.html', form=form, isauth=current_user.is_authenticated)
#main.route('/users')
def users_list():
form = UsersForm()
if form.validate_on_submit():
return redirect(url_for('.index'))
I found this answer in another post and it worked! In Pycharm Run/Debug Configs, uncheck "Add Content Roots to PYTHONPATH" and "Add Source Roots to PYTHONPATH". Don't understand why it broke or why it's fixed... but there's plenty of time for that later.
PyCharm Config Fix
Related
I'm trying to deploy a flask app on AWS Lambda using Zappa. However, when I call zappa deploy dev, I'm getting an error. After examining the logs, I've found that the error is being caused when the code runs db.create_all() within my create_database() function. The database isn't being created which is strange because when I run it locally, it works fine. I'm including the code for my application and a stack trace of the error below.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
db = SQLAlchemy()
DB_NAME = 'database.db'
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdfghjkl'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
db.init_app(app)
from .views import views
app.register_blueprint(views, url_prefix = '/')
from .models import User
create_database(app)
login_manager = LoginManager()
login_manager.login_view = 'views.home'
login_manager.init_app(app)
#login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app
def create_database(app):
if not path.exists('website/' + DB_NAME):
db.create_all(app = app) #where error is occuring
print('Created Database')
After running zappa deploy/update dev:
Any help would be appreciated!
I have a flask application with an init.py. In the create_app function, I have set app.config['UPLOAD_FOLDER']. I need to import app into my post.py file that has the routes which will be uploading and downloading files from. I am getting issues with every type of import I try.
init.py:
from flask import Flask, session, redirect, url_for
from bson.objectid import ObjectId
from pymongo import MongoClient
from os import path, mkdir
from flask_login import LoginManager
client = MongoClient()
db = client.Contractor
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = ''
upload_folder = 'uploads/'
if not path.exists(upload_folder):
mkdir(upload_folder)
from .views import views
from .auth import auth
from .post import post
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
app.config['UPLOAD_FOLDER'] = upload_folder
app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/auth/')
app.register_blueprint(post, url_prefix='/post/')
return app
post.py:
from flask import Blueprint, render_template, request, flash, redirect, url_for, session
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from . import db
from bson.objectid import ObjectId
from os import path, mkdir
#post.route('/upload', methods=['GET', 'POST'])
def create_post():
if 'username' in session:
current_user = db.users.find_one({ 'username' : session['username']})
if request.method == 'POST':
data = request.form
photo = request.files['photo']
print(photo)
---->photo.save(path.join(app.config['UPLOAD_FOLDER'], secure_filename(photo.filename)))
caption = data.get('caption')
location = data.get('location')
how can I import app from init.py
I think you can import app where you import db.
from . import app, db
I am new to flask, and I am trying to add my forms objects so I can record them in my Database.
The problem is when I try to do something at the routes.py file I get a 400 error, and for the life of me I cant understand what is happening.
I also want to check if the record has already been added to the database before I commit the changes to the database.
Things are working ok at the database level as I have checked and created tables and headers in my models.py file, the forms.py file is also working fine, the problem occurs whenever I try to make it work at the routes.py file.
I am using a Blueprint factory model to develop this application as well.
Here is the Folders Structure
This is the folder structure
.
|
|- __init__.py
|- forms.py
|- models.py
|-routes.py
|-templates
| |-clients-forms.html
|- util.py
init.py Contents:
blueprint = Blueprint(
'cml_blueprint',
__name__,
url_prefix='',
template_folder='templates',
static_folder='static'
)
routes.py content:
from flask import jsonify, render_template, redirect, request, url_for
from flask_login import (
current_user,
login_required,
login_user,
logout_user
)
from app import db, login_manager
from app.cml import blueprint
from app.cml.forms import (
ClientsForm,
RegisterForm,
ComercialForm,
SupplierForm,
NonConformityForm,
TestForm
)
from flask import render_template, redirect, url_for, request
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
#blueprint.route('/clients-forms.html', methods=['GET','POST'])
#login_required
def clients-forms():
clients_form = ClientsForm(request.form)
id = request.form['id']
registered_clients = Clients.query.filter_by(id=id).first()
if registered_clients:
return render_template( 'clients-forms.html',
msg='Already Registered',
success=False,
form=clients_form)
registered_clients = ClientsForm(**request.form)
db.session.add(registered_clients)
db.session.commit()
return render_template('clients-forms.html',
form=cadastro_clientes_form )
Quick fix it was missing the import from the models.py
the file was lacking those imports and not runing on Development mode, so the only aswer I got back was a 400.
from app.cml.models import RegisteredClients
I was trying to create a new user from the terminal using flask fab but when I run the command and fill all the required info like username, email, password I get this error message: AttributeError: 'Flask' object has no attribute 'appbuilder'.
Full traceback:
https://pastebin.com/gACSfChG
FLASK_APP=run.py
run.py
import os
from app import RubyAPP
config_name = os.getenv('FLASK_CONFIG')
app = RubyAPP(config_name).app()
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_login import current_user
from flask import render_template
db = SQLAlchemy()
app = Flask(__name__, instance_relative_config=True)
login_manager = LoginManager(app)
#app.errorhandler(404)
def not_found_404(e):
return render_template('404.html'), 404
class RubyAPP(object):
def __init__(self, config_name):
# App manager
app.config.from_pyfile('config.py')
db.init_app(app)
# Login manager
login_manager.init_app(app)
login_manager.login_message = 'You must be logged in to access this page'
login_manager.login_view = 'auth.login'
# Flask migrate
migrate = Migrate(app, db)
def app(self):
# Error handling apps registers
app.register_error_handler(404, not_found_404)
# Models
from app import models
# Views
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
from .profile.links import links as links_blueprint
app.register_blueprint(links_blueprint)
from .login import login as login_blueprint
app.register_blueprint(login_blueprint)
return app
I tried reinstalling appbuilder but gives the same error. I think these 2 files are enough but since I don't know whats giving the error let me know if you need any extra file.
Had the same error. You have to run appbuilder.init_app() for your app:
..
..
class RubyAPP(object):
def __init__(self, config_name):
# App manager
app.config.from_pyfile('config.py')
db.init_app(app)
with app.app_context():
appbuilder.init_app(app, db.session)
..
..
I am trying to run a small flask modular application under windows 10. I have created a module to lunch the index page. While as a single application runs correctly and loads the home page, I cannot make it modular getting a 404 error page not found.
Here is my directory structure:
Application directory structure
My files:
runserver.py
import os
#from app.models import User, Role
from flask import Flask
basedir = os.path.abspath(os.path.dirname(__file__))
from landingpage import app
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
__init__.py
import os
from flask import Flask, render_template, session, redirect, url_for
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, TextField, DateField, SubmitField
from wtforms.validators import Required
from wtforms.fields.html5 import DateField
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin.form.widgets import DatePickerWidget
basedir = os.path.abspath(os.path.dirname(__file__))
#print "basedir is %r " % (basedir)
app = Flask(__name__)
import views
class AnotherSearchForm(Form):
place = StringField(default=u'Où voulez-vous aller?', validators=[Required()])
checkin =TextField(default=u'checkin', validators=[Required()])
checkout=TextField(default=u'checkout', validators=[Required()])
dt = DateField('DatePicker', format='%Y-%m-%d')
submit = SubmitField('Rechercher')
views.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
from flask import Flask, render_template, session, redirect, url_for, current_app
#from .. import db
#from ..models import User
#from ..email import send_email
import landingpage
from landingpage import app
#from .forms import AnotherSearchForm
#app.route('/', methods=['GET', 'POST'])
def index():
form = AnotherSearchForm()
return render_template('indexnew.html',
title='Home',
form=form)
The application is running correctly as you see below,
$ python runserver.py
C:\Users\admin\Anaconda\lib\site-packages\flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.')
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
but is failing to load the home page indexnew.html on http://127.0.0.1:5000/ giving a 404 error:
127.0.0.1 - - [22/Apr/2016 14:10:21] "GET / HTTP/1.1" 404 -
You appear to have app defined in runserver.py as well as in your __init__.py
I suspect that runserver.py is running the app defined there, while your real application is actually being set up and then overridden by your runserver.py.
You want to import app within runserver.py and use that, rather than define it again.
In other words, remove this line from runserver.py...
app = Flask(__name__)
update
I've got a version of your code that has the fix I suggest. You can find it on GitHub:
https://github.com/martinpeck/stackoverflow_example_1
I took your code. It failed in two ways:
your import of views didn't work for me
once I'd fixed that, I saw the 404
To fix your code:
replace import views with import landingpage.views in __init__.py
as suggested above, remove app = Flask(__name__) from runserver.py