How do I use Flask.route with Flask - python

A brief introduction to the directory structure is as follows:
__init__.py contain the application factory.
page.py
from app import app
# a simple page that says hello
#app.route('/hello')
def hello():
return 'Hello, World!'
app.py
from flaskr import create_app
app = create_app()
if __name__ == '__main__':
app.run()
When I start the server and go to the '/hello', it says 404.
What's the problem?

Here is a short solution which should run.
page.py
from flaskr import app
#app.route('/hello')
def hello():
return 'Hello'
__index__.py
from flask import Flask
app = Flask(__name__)
from flaskr import page
app.py
from flaskr import app
To run this you just need to define a Environment Variable on the Commandline like this:
export FLASK_APP=microblog.py
And then run it with
flask run

The way you have structured your code is not right. That's the reason you are not able to access your "/hello" API.
Let's assume that you run the app.py file. In this case, you haven't imported page.py right? So, how will the app.py know that there is a route defined in page.py?
Alternatively, let's assume you run page.py. In this case, when you do an "from app import app" , the main definition does not get executed. Here too, the route will now be present, but the app will not be run, thereby you will be unable to access your API.
The simplest solution would be to combine the contents of app.py and page.py into a single file.

Related

Flask can't import application from root directory to test

I have the following folder structure:
In the application.py file I am using a factory method create_app():
# application.py
def create_app():
flask_app = Flask(__name__)
return flask_app
app = create_app()
# --- Import Routes ---
from src.routes import *
if __name__ == "__main__":
app.run()
In the test folder I have the following code
# /tests/test.py
from application import create_app
def test_root_route():
flask_app = create_app()
with flask_app.test_client() as test_client:
response = test_client.get('/')
assert response.status_code == 200
Now I get the following error when running the test:
from application import create_app
ModuleNotFoundError: No module named 'application'
Why can't I import the method from the application.py file?
Unfortunately I can't change the folder structure as the application.py needs to be in root so it can be run by our server.
Please share folder structure properly , looking at it currently seems like while running tests.py , the application.py file is in the directory above the current one .
Also you can try to make a test.py where apllication.py is located. Then import the tests you've written in test directory.
try using from .application import with and __init__.py file in the root file
Python has a lot of problems with sibling imports

Flask Python - basic program does not work

I wrote this super basic application. It runs but does not do a thing:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def Index():
return "<h1>Hello!</h1>"
if __name__ == "__name__":
app.run(debug=True)
The console shows:
C:\Users\TalT\PycharmProjects\FlaskBeginners\venv\Scripts\python.exe
C:/Users/TalT/PycharmProjects/FlaskBeginners/MyFirstWebPage.py
Process finished with exit code 0
I work on Win10, PyCharm 2019.3.3 and Python 3.7 .
I don't understand where is the problem? Is it a python issue or maybe project configuration?
Your problem is:
if __name__ == "__name__":
Must change to:
if __name__ == '__main__':
To start a flask app you have 2 easy different ways.
1. Rename your main file to app.py or wsgi.py and go to path of the file in terminal and type flask run. In this way, if you want to run app in debug mode, In the same path, type set FLASK_ENV=development in terminal (Windows) and then write flask run.
Tip: In this way, you must delete the following code from your project:
if __name__ == '__main__':
app.run()
2. Write your code in a python file (name is not matter) for example with main.py name write like this:
from flask import Flask
app = Flask(__name__)
app.config['DEBUG']=True
#app.route('/')
def Index():
return '<h1>Hello!</h1>'
if __name__ == '__main__':
app.run()
And run the application by running this command in the path of your file: python main.py . Remember, add this code app.config['DEBUG']=True only if you want to run your code in debug mode.

Flask CLI command not in __init__.py file

I'm trying to add commands to my Flask app.
This is my __init__.py file:
import os
from flask import Flask
from flask_cors import CORS
from flask_mongoengine import MongoEngine
app = Flask(__name__)
CORS(app)
app.config.from_object(os.environ['APP_SETTINGS'])
db = MongoEngine(app)
import slots_tracker_server.views # noqa
If I add to it:
#app.cli.command()
def test_run():
print('here')
I can run flask test_run with no problems, but if I try to move the code to another file, for example: commands.py, I get the error Error: No such command "test_run". when trying to run the command.
What I'm missing?
Use click (the library behind Flask commands) to register your commands:
# commands.py
import click
#click.command()
def test_run():
print('here')
In your __init__.py import and register the commands:
# __init__.py
from yourapp import commands
from flask import Flask
app = Flask(__name__)
app.cli.add_command(commands.test_run)
Take a look at the official docs
In you commands.py you can add register function like that:
def register(app):
#app.cli.command(name='test_run', help="test_run command")
def register_test_run():
test_run()
# other commands to register
And then in your __init__.py import this register function
from flask import Flask
app = Flask(__name__)
from commands import register
register(app)
Notice, that you should import register after you've initialized your app.

Flask not finding routes in imported modules

I'm having a problem with Flask wherein routes declared in imported modules are not be registered and always result in a 404. I am running the latest version Flask on Python 2.7.
I have the following directory structure:
run.py has the following code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
import views.home
if __name__ == '__main__':
app.run()
home.py has the following code:
from run import app
#app.route('/test')
def test():
return "test"
When I run run.py the route declared in home.py (http://localhost:5000/test) always returns a 404 even though run.py imports views.home. The root view (http://localhost:5000) declared in run.py works fine.
I have written a function that prints out all the registered routes and /test is not in there (get a list of all routes defined in the app).
Any idea why?
I have discovered that switching the import statement in run.py from
import views.home
to
from views.home import *
makes everything work, which gave me the clue as to why the modules are not being registered using import views.home.
Basically, when run.py is run as a script it is given the name __main__ and this is the name given to the module in sys.modules (Importing modules: __main__ vs import as module)
Then when I import app from run.py in views.home.py a new instance of run.py is registered in sys.modules with the name run. As this point, the reference to app in run.py and views.home.py are two different references hence the routes not being registered.
The solution was to move the creation of the app variable out of run.py and in to a separate python file (I called it web_app.py) that is imported into run.py. This guarantees that the Flask app variable declared inside web_app.py is the always referenced correctly wherever web_app.py is imported.
So run.py now looks like this:
from web_app import app
if __name__ == '__main__':
app.run()
and web_app.py looks like this:
from flask import Flask
app = Flask(__name__)
import view.home
You can do it by reorganizing your code as it is described here Larger Applications, but it is more recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. For a gentle introduction into this topic refer to the Modular Applications with Blueprints chapter of the documentation.
Modular Applications with Blueprints

Flask app does not use routes defined in another module

I can't get it to work to use one module that creates the Flask application object and runs it, and one module that implements the views (routes and errorhandlers). The modules are not contained in a Python package.
app.py
from flask import Flask
app = Flask('graphlog')
import config
import views
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
views.py
from app import app
#app.route('/')
def index():
return 'Hello!'
config.py
host = 'localhost'
port = 8080
debug = True
I always get Flask's default "404 Not Found" page. If I move the contents of view.py to app.py however, it works. What's the problem here?
You have four modules here:
__main__, the main script, the file you gave to the Python command to run.
config, loaded from the config.py file.
views, loaded from the views.py file.
app, loaded from app.py when you use import app.
Note that the latter is separate from the first! The initial script is not loaded as app and Python sees it as different. You have two Flask objects, one referenced as __main__.app, the other as app.app.
Create a separate file to be the main entry point for your script; say run.py:
from app import app
import config
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
and remove the import config line from app.py, as well as the last two lines.
Alternatively (but much uglier), use from __main__ import app in views.py.

Categories

Resources