Getting 404 upon splitting up a file in flask - python-2.7

My flask app runs fine.
But, when I split it up into 3 parts, the imported one displays a 404.
Here is the file structure:
myproject/
run.py
appy/
__init__.py
index.py
.
#run.py
from appy import app
if __name__ == '__main__
app.run()
.
#__init.py
from flask import Flask
app = Flask('appy')
from appy import index
#app.route("/h")
def hello():
return "Hello"
.
#index.py
from appy import app
#app.route("/s")
def shello():
return "Shello"
localhost/h runs fine returning Hello.
localhost/s gives 404.
Also, everything runs fine when merged into a single file.
Please suggest a way to do it correctly.

You're running into a circular import error. You are importing app into index.py but you are also importing index.py into __init__.py.
If you want to have everything in a different file the best way to do it is make your init.py file empty, and create a differently named file for the contents of index.py
Then from your new "init.py" file (with a new name) import the contents of index, and then run the app.
Should work now.

Related

Initialising flask environment variable issues

I am trying to create a an application using Flask. I have done this before successfully, however, I am not sure why this is not working this time. Everything seems to be in the right order. I have searched for answers, however, I still can't determine what's going wrong as everything seems logical to me? Yet, it is still going wrong?
ZXM934/
app/
__innit__.py
views.py
venv/
run.py
The following are each files contents:
run.py
# Importing app object which was created in __innit__.py file into app.py
from app import app
if __name__ == "__main__":
app.run()
__innit__.py
# This class will ultimately bring our entire application together.
from flask import Flask
# Creating Flask app.
app = Flask(__name__)
# Importing views file to avoid circular import.
from app import views
view.py
# This class represents the UI of our website.
# Importing app directory. As __innit__.py file is apart of this directory,
# this import treats it as a package.
from app import app
#app.route("/")
def public_home():
return "Homepage"
#app.route("/login")
def login():
return "<h1 style='color: red'>Login</h1>"
I set the environment variables as following within the console:
export FLASK_APP=run.py
export FLASK_ENV=development
I then run the following command:
flask run
The following error occurs:
flask.cli.NoAppException: While importing "run", an ImportError was raised:
Traceback (most recent call last):
File "/Users/zahidmalik-ramzan/Desktop/zxm934/venv/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/Users/zahidmalik-ramzan/Desktop/zxm934/run.py", line 2, in <module>
from app import app
ImportError: cannot import name 'app' from 'app' (unknown location)
I don't understand what I am doing wrong?
Your problem is in the file name __innit__.py.
For python to understand that a folder is an actual package within your project structure you need a special file inside, i.e. __init.py__ ps: no double n.
A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace.
Conclusion: change your __innit.py__ to __init.py__

Cannot import module to begin basic Flask app

So I'm following a beginners tutorial on Flask and for whatever reason am getting an error on what is essentially the very first step.
I first created an "app" directory where I created a python file for "init.py" which contains the following code:
from flask import Flask
app = Flask(__name__)
from app import routes
I then created a "routes.py" python file in the same directory:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Finally (and this is where the problem stems from), I created a python file named "microblog.py" which is located in the same folder as the "app" directory:
from app import app
I then go to my virtual environment and run (using cmd windows):
set FLASK_APP=microblog.py
So far so good, however when I try to run the following code in cmd:
flask run
I get the following error:
ImportError: cannot import name 'app' from 'app' (C:\Users\Grae_\microblog\app\__init__.py)
If any further clarification is needed, here are my file locations:
C:\Users\Grae_\microblog
C:\Users\Grae_\microblog\app
C:\Users\Grae_\microblog\__init__.py
C:\Users\Grae_\microblog\routes.py
C:\Users\Grae_\microblog\venv
C:\Users\Grae_\microblog\microblog.py
Apologies if this is really obvious, I'm just obviously very new to Flask and have been stuck on this for a while.
Thanks
The issue here is on python package "app". The directory should have a file named __init__.py instead of init.py.
For example, you rename the file init.py to __init__.py and replace content with below code it should work
from flask import Flask
app = Flask(__name__)
def start():
from app import routes
start()
You can do something like this:-
test.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Index!"
#app.route("/hello")
def hello():
return "Hello World!"
#app.route("/members")
def members():
return "Members"
#app.route("/members/<string:name>/")
def getMember(name):
return name</string:name>
if __name__ == "__main__":
app.run()
In command prompt, run the command-
python test.py
Try the URLs in your browser:
http://127.0.0.1:5000/
http://127.0.0.1:5000/hello
http://127.0.0.1:5000/members
http://127.0.0.1:5000/members/Karan/

Moving Custom CLI commands to another file

I have a few custom cli commands for a flask app I'm writing. I'm following the instructions here:
Command Line Interface
The problem is I do not want to put them all in my app.py file, it will get overbloated. What I would like to do is have my project structure:
project
|_ app.py
|_ cli.py
I thought about using a blueprint, but I get "Blueprint has no attribute 'cli'"
This is what I tried:
cli = Blueprint('cli', __name__) # I knew this would not work but I had to try
#cli.cli.command()
#click.argument('name')
def create_user(name):
print("hello")
Thanks
I would do something like this:
cli.py:
from flask import Flask
import click
def register_cli(app: Flask):
#app.cli.command()
#click.argument('name')
def create_user(name):
print("hello", name)
app.py:
from flask import Flask
from cli import register_cli
app = Flask(__name__)
register_cli(app)
It's common to create and configure (or just configure) app in factory functions.

Flask-Ask not working when using runserver pattern

Trying to add flask-Ask to an existing flask website that uses the runserver pattern where app setup done in init but app.run is called in runserver
/myapp
/myapp
__init__.py
views.py
alexa_views.py
runserver.py
This pattern works fine for Flask ( its recommended for larger apps) but Flask-Ask is failing silently when app.run(debug=True) is called from runserver.py.
If I call app.run(debug=True) in _init__.py and run that then Flask-Ask works fine and Alexa responds.
Any ideas?
code:
alexa_views.py
from flask import blueprints
from flask_ask import Ask, statement
askblueprint = blueprints.Blueprint('alexa', __name__, url_prefix='/alexa')
ask = Ask(blueprint=askblueprint)
#ask.launch
def launch():
return statement (' it works')
init.py
from flask import Flask, blueprints
from myapp.alexa_views import askblueprint
app = Flask(__name__)
app.register_blueprint(askblueprint)
# lots of other unrelated configuration here - db etc
# running app here causes Flask-Ask to work!
# if __name__ == '__main__':
# app.run(debug=True)
# late import of views to break circular import
import myapp.views
runserver.py
# running this starts website normally but Flask-Ask does nothing
from myapp import app
if __name__ == '__main__':
app.run(debug=True)
I am going to close this.
The problem does exist in my real app but this simple example now works fine so I will have to dig deeper to find something I can demonstrate.
Bill

Flask Application returning ImportError: No module named user_auth.views

I'm in the beginning stages of a Flask application. The problems I'm having is that whenever I attempt to run the application I get:
app/application/___init___.py, line 11 in <module>
from user_auth.views import auth
ImportError: No module named user_auth.views
I have no idea what the problem is. The import for the home.view did this as well, then it stopped and worked fine on the local server. Been trying to figure this out for the longest, there aren't that many moving parts in the application as of yet, so not sure why this is happeninng. File structure and code below:
|app
|-application
|--__ init __.py
|--home
|--user_auth
|----forms.py
|----views.py
|----templates
|----static
My application/__ init __.py file:
from flask import Flask
app = Flask(__name__)
app.config.from_object('_config')
from home.views import home
from user_auth.views import auth
app.register_blueprint(home)
app.register_blueprint(auth)
My application/user_auth/views.py
from flask import Blueprint
auth = Blueprint('auth', __name__,
url_prefix='/user_auth',
template_folder='templates',
static_folder='static')
You're missing an __init__.py file under ./user_auth/ to make user_auth a module.
There's more information about modules in the docs.