flask 404 error under windows - python

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

Related

I am getting import errors when trying to import my database into my own module

I have a module called crop.py in my flask application. Everything works great until I want to import database parts from models.py. I'm guessing it has something to do with initializing the module into the app and then trying to import models into it, but I'm not sure.
Here is the error:
flask.cli.NoAppException: While importing 'test', an ImportError was raised.
Here is my basic app construction.
-app
models.py
crop.py
crop.py
from app import current_app
from flask import url_for, Markup
import PIL
from PIL import Image
from uuid import uuid4
import os
#Adding these below causes an importerror------------------------------------
#from app import db
#from app.models import Upload
class _Avatars(object):
#code here
class Avatars(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
#code here
__init.py
from flask import Flask, request, current_app _l
from elasticsearch import Elasticsearch
from redis import Redis
import rq
from config import Config
#This is my module-----------------------------------------------------
from .crop import Avatars
db = SQLAlchemy()
migrate = Migrate()
avatars = Avatars()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
avatars.init_app(app)
I think it is causing a circular import error, since you're importing your crop model in your __init.py file and you're import db from __init.py into crop model file. Python does not allow this kind of scenario. Either you'll have to define your DB connections elsewhere in a separate file or add them manually everywhere you need to use the DB.

Python / Flask App - Relative Imports Stopped Working

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

Getting 404 not found on Flask app deployed on PythonAnywhere

I've rummaged through maybe 50 different answers to this and still I haven't manage to fix it... I'm pretty new to flask and python.
I have an app which was running great locally but I've struggled with deploying on python anywhere. Initially I had a few import modules issues, now it runs but doesn't return any html template, despite not seeing any other issue. The main issue I had was that it couldn't find the "routes" app from wsgi, and I sort of fixed adding the app = Flask(name) line on routes.py (the short blueprint object is not callable).
routes.py:
from flask import Blueprint, render_template, request, redirect, send_file
import pyqrcode
from pyqrcode import QRCode
import subprocess
from extensions import db
from models import Link
app = Flask(__name__)
short = Blueprint('short', __name__, url_prefix='/')
#short.route('/index')
def index():
return render_template('index.html')
init.py
from flask import Flask
from extensions import db
from routes import short
def create_app(config_file='settings.py'):
app = Flask(__name__)
app.config.from_pyfile(config_file)
db.init_app(app)
app.register_blueprint(short)
return app
wsgi.py
import sys
# add your project directory to the sys.path
project_home = u'/home/b297py/mysite'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# import flask app but need to call it "application" for WSGI to work
from routes import app as application
For the purpose of testing, I've placed all the html templates both in the root directory and in the specific /template directory but it just didn't fix the issue.
In wsgi.py you are not calling create_app so you are never registering the blueprint. You should replace :
from routes import app as application
by something like :
from package_name import create_app
application = create_app()
(Example: https://www.pythonanywhere.com/forums/topic/12889/#id_post_50171)
Also as you mentioned, the fix adding app = Flask(__name__) to routes.pyallows you to bypass create_app (so you should remove it if you want to stick to the create_app approach).

Flask cannot run and stop during initialization

I'm not able to run flask successfully
When i execute the apps_server.py..it stop initialized as follow
Serving Flask app "apps_server" (lazy loading) Environment:production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
Debug mode: on
It just stuck at that point...and there is no Running on http://localhost:5000/ line show up...
May I know what could be the problem?
This is snippet of the code
from flask import Flask, render_template, Markup, request, jsonify
from flask.helpers import send_file
import os,httplib,json,subprocess
import flask
from flask import request, jsonify, abort, render_template, flash, redirect, url_for
import argparse, sys
import logging
import logging.config
from logging.handlers import RotatingFileHandler
from logging import Formatter
#app = flask.Flask(__name__)
app=Flask(__name__,template_folder='templates')
app.config["DEBUG"] = True
##Functions and code to execute##
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
Please advise further.
I got your code working by doing the following changes:
from flask import Flask, render_template, Markup, request, jsonify
from flask.helpers import send_file
import os,http.client,json,subprocess
import flask
from flask import request, jsonify, abort, render_template, flash, redirect, url_for
import argparse, sys
import logging
import logging.config
from logging.handlers import RotatingFileHandler
from logging import Formatter
app = Flask(__name__)
#app.route("/")
def home():
return "Hello World!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Try now ;) Seems like it might have been the debugging. Also, make sure that the #app.route statement is correct. If you are using a template here and there is just a small mistake, it will not work. I am not sure if your code is correct inside what you call the ##Functions and code to execute##. Make sure that whatever you have inside here is correct. Python 3 also renamed httplib to http.client (ref here), so I changed this during the import. However, the code above is working for me.
Also, if you want to use a template (as you've indicated in the post), you can refer to the template as following:
#app.route("/", methods=["GET"])
def home():
return render_template("home.html")
Remember to make a directory called "templates", and put the home.html file there. Flask will automatically look for the "templates" directory.

Circular imports on python app

I'm beginning to learn python and I'm following this tutorial on setting up Flask, but I'm having some trouble understanding the author in how he lays out his files. From what I can gather, it seems like I'm running into a circular import problem and I can't trouble shoot it.
The files are set up as follows:
__init__.py
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = "something here";
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://app.db"
app.py
from flask import render_template, request, redirect, url_for, abort, session
from app import app
#app.route('/')
.... some stuff here
models.py
from flask.ext.sqlalchemy import SQLAlchemy
from app import app
db = SQLAlchemy(app)
class User(db.Model):
.... some stuff here
manage.py
#!/usr/bin/env python
from flask.ext.script import Manage, Shell, Server
from app import app
manage = Manager(app)
manager.add_command("runserver", Server())
manager.add_command("shell", Shell())
#manager.command
def createdb():
from app.models import db
db.create_all()
manager.run()
The first error is being unable to start the server through running manage.py runserver. I was able to do it initially until I switched the files around initialized the app within init.py (originally I had everything located in app.py). I receive an error saying -
ImportError: cannot import name app
That aside, if I eliminate init.py and get the server up and running, I can't create a database because I receive an error stating -
Import Error: no module named models when running manage.py createdb

Categories

Resources