Viewing a Flask app in the Cloud9 Test Browser - flask

I'm creating a web app based on Miguel Grinberg's Flasky app (from his book Flask Web Development).
When running manage.py runserver in the Cloud9 IDE, the command line tells me that it is running at http://127.0.0.1:5000/. However, when I type this IP address into the Cloud9 test browser, I see nothing. https://[workspace]-[username].c9users.io (with or without :5000) doesn't work either.
Here's my manage.py code:
from app import create_app
from flask.ext.script import Manager, Shell
app = create_app('default')
manager = Manager(app)
if __name__ == '__main__':
manager.run()

This video https://www.youtube.com/watch?v=MI8YIRDeGzU by Chris Lynch outlines the flask configuration settings you need for the Cloud9 browser at around the 7 minute mark. In order to start server hit the green run button near the top of the page to the right of the preview button.
#Insert the line below to to run on Cloud9
app.run(host=os.getenv('IP', '0.0.0.0'), port=int(os.getenv('PORT', 8080)))
#end insert, place above __name__ == __main__
if __name__ == '__main__':
app.run()
app.debug(True)

Related

Running Flask in Pycharm but can't enter custom commands [duplicate]

I created new flask project in PyCharm but I can't see how to run flask shell in integrated PyCharm python console window.
Name app is not defined when start console:
I still can run command "flask shell" in integrated PyCharm terminal but it will start without code completion, hints, syntax checks, etc.
Flask app is defined in terminal:
Is there any way to start flask shell in integrated PyCharm python console?
You can use a combination of creating a request context for the Shell (which flask shell does) and a custom starting script for the PyCharm console.
# Step 1: acquire a reference to your Flask App instance
import app
app_instance = app.create_app()
# I return app instance from a factory method here, but might be be `app.app` for basic Flask projects
# Step 2: push test request context so that you can do stuff that needs App, like SQLAlchemy
ctx = app_instance.test_request_context()
ctx.push()
Now you should have the benefits of flask shell alongside the code completion and other benefits that IPython Shell provides, all from the default PyCharm Python Shell.
In my case (in my server.py I had app=Flask(__name__)) I used
from server import app
ctx = app.app_context()
ctx.push()
Then added this to File | Settings | Build, Execution, Deployment | Console | Python Console starting script
This also works:
from app import app
ctx = app.test_request_context()
ctx.push()
more on the Flask docs page
Running a Shell
To run an interactive Python shell you can use the shell command:
flask shell
This will start up an interactive Python shell, setup the correct
application context and setup the local variables in the shell. This
is done by invoking the Flask.make_shell_context() method of the
application. By default you have access to your app and g.
It's just a normal interactive Python shell with some local variables already setup for you, not an IDE editor with code completion, hints, syntax checks, etc.

Python Flask Web application not able to deploy on Heroku using Waitress server

I am trying to deploy my Flask application on Heroku PaaS Cloud Service. It, however, works on localhost with no errors. I am using git for version control and pushing to Heroku. Initially, as a web server, I used 'gunicorn' but later came to know it is useful for UNIX distributions. So I resorted my webserver to 'waitress'. I saw some of the posts and tried everything in the Procfile for hosting to Heroku. My Procfile reads like: web: waitress-serve --port=$PORT app:app. I also know that the first app in this line is the package and the second app is the name of the instance best to my knowledge. I even changed from app to myapp, website and I have all the packages including these mentioned are in my VS code editor. But my application is not getting deployed onto Heroku and it gives Application Error. Now when I check the logs using heroku logs --tail it gives me the following error as in the screenshot. Any help would be highly obliged. I am trying this for 23 hours. Heroku Logs
The Procfile looks correct but the problem could be that the file (app.py) and the variable (app) have the same name.
I suggest the following approach, in app.py
# define Flask app
def create_app():
try:
web_app = Flask(__name__)
logging.info('Starting up..')
return web_app
except Exception as e:
logging.exception(e)
# retrieve port
def get_port():
return int(os.environ.get("PORT", 5000))
# start Flask app
if __name__ == '__main__':
web_app = create_app()
web_app.run(debug=False, port=get_port(), host='0.0.0.0')
The application can be launched from the Procfile with
web: waitress-serve --port=$PORT --call 'app:create_app'

Flask - converting python execution to flask run

I developed my first flask application that is currently running and everything work fine. The application is loaded using "python application.py" or using gUnicorn. There is no fancy fancy folder structure everything is in the same folder, with exception of the static\ and templates\
Folder Structure:
- application\hello.py
- application\static\
- application\templates\
To Run:
- python hello.py
#hello.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(host='0.0.0.0', load_dotenv=True, debug=True, threaded=True)
Now that looking to add more functionalities to the application noticed most tutorials uses "flask run" to launch the instead. There are two different tutorials I am following one using blueprints and the other one is the microblog tutorial both using similar folder structure:
- application\run.py
- application\app\main.py
- application\app\static\
- application\app\templates\
To run:
- export Flask_APP=run.py
- flask run
The application will continue to grow and I want to follow best practices.
Question 1:
How do I enable the following parameters when using "flask run"??:
if __name__ == '__main__':
app.run(host='0.0.0.0', load_dotenv=True, debug=True, threaded=True)
Question 2:
Is there any pro/cons configuring the app to run using flask run vs python app.py????? There was another post with this title but context was unrelated.
When can I read more about this??
Threaded mode is enabled by default. You don't have to pass it in. Source
For debug mode, use export FLASK_DEBUG=1. Source
For load_dotenv use export FLASK_SKIP_DOTENV=0 Source
For specifying port use export FLASK_RUN_PORT=8000. Source
To bind the app to 0.0.0.0, set SERVER_NAME config like app.config['SERVER_NAME']. Source
Also see:
http://flask.pocoo.org/docs/1.0/cli/#setting-command-options

unittest on flask_restful app does not work - stuck on flask server running

My tools: Python 3.5.0, flask 1.0.2, mac osx
My problem:
I have a very simple RESTful app with two endpoints that are working. I wrote two very simple unit tests, via unittest, and they are not proceeding for a reason that I'm not sure of right now. The tests succeed if I do the following:
If I run the server separately, say on http://127.0.0.1:8015/, (and not setUp() anything)
And run the tests such that they call requests.get(http://127.0.0.1:8015/employee/3)
the tests run just fine and they pass
The tests just hang if I run the tests with the setUp(self) definition below:
Serving Flask app "testing" (lazy loading)
Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
Debug mode: off
Running on http://127.0.0.1:8015/ (Press CTRL+C to quit)
And here is the pertinent code
def setUp(self):
self.app = Flask("testing")
self.app.testing = True
self.client = self.app.test_client()
self.EmployeeId = 4
with self.app.app_context():
db_connect = create_engine('sqlite:///some.db')
self.api = Api(self.app)
self.api.add_resource(server.Car, '/car/<employee_id>') # Route_4
app.run(port=8015, debug=False)
def test_api_can_get_employee_by_id(self):
res = requests.get(url = 'http://127.0.0.1:8015/car/{}'.format(self.EmployeeId))
data = res.json()
self.assertEqual(res.status_code, 200)
self.assertIn('mazda', data["data"][0]['make_model'])
I've looked online and found no resource that really covers my question. The set up of the server works during the testing but the unit tests are not executed. How would you recommend troubleshooting this? I'm open to all suggestions including changing the approach. Thank you!
For those of you stumbling here after Googling "Unit tests stuck on Running on with Flask":
It's possible that your code always starts the Flask server, regardless of how your module was loaded. If that's the case, even the unit tests will start the server, which will indefinitively listens for connections as expected.
Eg, this will get stuck:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return "Hello World!"
app.run()
Instead, you'll need to start the Flask server only if your module is the main program:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
More info on the "name == 'main'" block here.
Regarding the original question, this answer does not solves it. To do something like that you would need to start the Flask server, but in a non-blocking way such as another thread or process. There's many ways to do this and without any additional info, the question is just too vague to answer as is.

404 on any route for Flask app deployed to Elastic Beanstalk

I am trying to host a Flask app that implements a REST API using Flask-RESTful on Elastic Beanstalk through the eb cli. I have successfully deployed my application and I am not getting any error messages on my events log. I can successfully ssh into the instances and run the script to prepopulate my database and everything. But whenever I try to access any routes I keep getting a 404 error.
I initially assumed that it was because it wasn't finding my WSGIPath, so I changed the file name to application.py and updated the EBS software configuration to point to that file. I have also updated all instances of app to application in the codebase based on AWS documentation. Still nothing. Does anyone have any idea what could be wrong?
This is my application.py:
from flask import Flask
from config import Config
CONFIG = Config()
# AWS Elastic Beanstalk expects an `application` variable.
application = Flask(__name__)
if __name__ == "__main__":
# Importing these here to avoid issue with circular imports
from endpoints.v1.exports import exports_api
from endpoints.v1.imports import imports_api
application.register_blueprint(exports_api, url_prefix="/api/v1")
application.register_blueprint(imports_api, url_prefix="/api/v1")
application.run(debug=CONFIG.DEBUG)
Here is where the application.py file lies in the folder structure:
- project root
- ...
- application.py
- ...
Just realized what was going on. I was trying to register the blueprints inside of the if __name__ == "__main__": block. But since the application.py file is not run directly by Elastic Beanstalk, it was never reaching those lines and so the endpoints I was trying to hit didn't exist.
I had to refactor my code so I could move it outside of that block and avoid issues with circular imports, but now it's all working as it should.