I want to monitor .hprof files in the system using Grafana, so I wrote a small Flask app. I am able to access localhost, I am able to see the number of hprof files on terminal, but I cannot see the number of hprof files on my localhost. Here is my code:
import fnmatch,os
app = Flask(__name__)
#app.route('/')
def hprof():
num_files = len(fnmatch.filter(os.listdir("/home/ubuntu/files"),'*.hprof'))
return("Total hprof files: ", num_files)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)
ubuntu#ubuntu-virtual-machine:~/hprof$ python3 hprof.py
* Serving Flask app "hprof" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 284-945-814
127.0.0.1 - - [15/Aug/2022 11:58:05] "GET / HTTP/1.1" 3 -
What I see on localhost:
Total hprof files:
Can anyone briefly explain how to solve my problem?
I had the same issue.
I solved it by entering
localhost:8000
In the browser search bar.
In a view function, returning a tuple like this:
return("Total hprof files: ", num_files)
means that Flask treats it as a (response, status) tuple, so num_files is used for the HTTP status code.
In order to return your intended response, you need to return a single string:
return "Total hprof files: " + str(num_files)
See the relevant Flask docs for more info.
Related
I used Flask command in my program for first time. Following was the bit of code I wrote:
from flask import Flask,jsonify, request
app = Flask(__name__)
#app.route("/")
def hello_world():
return "Hello World!"
if (__name__ == "__main__"):
app.run(debug=True)
This code was written by me in IDLE Shell 3.8-32 bit and the output should had come in a web browser. But it didn't came. I just got the following output from IDLE:
* Serving Flask app "sa" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
app.run(host=0.0.0.0, port=5000, debug=True)
You can change your port number to your convenience.
I have a small application built using Flask and Flask-restx. I can run the app using python app.py and the flask server runs on port 8888. I try to run the file using set FLASK_APP=app.py and run using flask run which seems to run, but doesnt open my swagger page. Please advice.
app.py
import logging.config
import os
from flask import Flask, Blueprint
from flask_cors import CORS
from werkzeug.middleware.proxy_fix import ProxyFix
from src.config import default
from src.api.controllers.endpoints.users import ns as users_namespace
from src.api.controllers.endpoints.statuses import ns as status_namespace
from src.api import api
from src.database import db
app = Flask(__name__)
CORS(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
logging_conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '../logging.conf'))
logging.config.fileConfig(logging_conf_path)
log = logging.getLogger(__name__)
def configure_app(flask_app):
flask_app.config['SERVER_NAME'] = default.FLASK_SERVER_NAME
flask_app.config['SQLALCHEMY_DATABASE_URI'] = default.SQLALCHEMY_DATABASE_URI
flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = default.SQLALCHEMY_TRACK_MODIFICATIONS
flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = default.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
flask_app.config['RESTPLUS_VALIDATE'] = default.RESTPLUS_VALIDATE
flask_app.config['RESTPLUS_MASK_SWAGGER'] = default.RESTPLUS_MASK_SWAGGER
flask_app.config['ERROR_404_HELP'] = default.RESTPLUS_ERROR_404_HELP
def initialize_app(flask_app):
configure_app(flask_app)
blueprint = Blueprint('CovidAPI', __name__, url_prefix='/')
api.init_app(blueprint)
api.add_namespace(users_namespace)
api.add_namespace(status_namespace)
flask_app.register_blueprint(blueprint)
db.init_app(flask_app)
def main():
initialize_app(app)
log.info('>>>>> Starting development server at http://{}/ <<<<<'.format(app.config['SERVER_NAME']))
app.run(debug=default.FLASK_DEBUG)
if __name__ == "__main__":
main()
Flask Settings:
# Flask settings
FLASK_SERVER_NAME = 'localhost:8888'
FLASK_DEBUG = True # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
Output using python command:
2020-04-29 10:25:42,519 - __main__ - INFO - >>>>> Starting development server at http://localhost:8888/ <<<<<
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
2020-04-29 10:25:42,610 - werkzeug - INFO - * Restarting with stat
2020-04-29 10:25:45,398 - __main__ - INFO - >>>>> Starting development server at http://localhost:8888/ <<<<<
2020-04-29 10:25:45,426 - werkzeug - WARNING - * Debugger is active!
2020-04-29 10:25:45,458 - werkzeug - INFO - * Debugger PIN: 258-749-652
2020-04-29 10:25:45,530 - werkzeug - INFO - * Running on http://localhost:8888/ (Press CTRL+C to quit)
Running through flask run:
* Serving Flask app "src\app.py" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 313-115-045
* Running on http://localhost:6000/ (Press CTRL+C to quit)
The flask run command works by importing an app object from your app.py module.
Therefor the stuff in this function is never executed in that case:
def main():
initialize_app(app)
log.info('>>>>> Starting development server at http://{}/ <<<<<'.format(app.config['SERVER_NAME']))
app.run(debug=default.FLASK_DEBUG)
When running with the python app.py command it is, because this gets executed:
if __name__ == "__main__":
main()
I'm not sure how it runs fully in your case with python, as neither the configure_app or initialize_app functions return the app object. However, you may wish to change the code to something like:
# ...
def configure_app(flask_app):
# ...
return flask_app
def initialize_app(flask_app):
# ...
return flask_app
app = initialize_app(app)
Now that (fully configured) app object is avaialable to flask run. You shouldn't need to set the FLASK_ENV environment variable, as it looks for an object called app by default.
If you still want the ability to run with the interpreter, then add this block to the end, although this is kinda defunct if using the flask command.
if __name__ == "__main__":
log.info('>>>>> Starting development server at http://{}/ <<<<<'.format(app.config['SERVER_NAME']))
app.run(debug=default.FLASK_DEBUG)
I'm running a Flask app in Cloud9. Whenever I start my Flask app, it says this message:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
Is there a way to change this message? I'd like it to say something like this:
Connect to me at http://0.0.0.0:80/!
I've searched stack overflow and the web but couldn't find anything. I'm starting my app with app.run().
Also, is it possible to make the URL cyan?
You can change everything besides Running on http://0.0.0.0:80/ (Press CTRL+C to quit) by changing show_server_banner of flask.cli:
from flask import Flask
import sys
cli = sys.modules['flask.cli']
# put your own message here
cli.show_server_banner = lambda *x: click.echo("My nice message")
app = Flask(__name__)
app.run(host='0.0.0.0', port='80')
To get rid of the Running on http://0.0.0.0:80/ ... message, you can use unittest.mock:
from unittest import mock
from werkzeug._internal import _log
def my_startup_log(*args):
# log all messages except for the * Running on message
if not args[1].startswith(" * Running on"):
return _log(*args)
app = Flask(__name__)
with mock.patch('werkzeug.serving._log') as mocked:
# patch the logger object and replace with own logger
mocked.side_effect = my_startup_logger
app.run(host='0.0.0.0', port='8000')
This is very hacky and depends on the internal implementation of flask. Be careful when using this in production code, as this could easily break.
I am new to Flask ,as part of POC I am building a web app which takes some input and runs a long python program (it takes 3-4 hours) to run based on the user input.Now I read that I should use celery so that user need not wait for a response from my program , which would take a lot of time , instead I can redirect them to some page .
So here is my attempt at calling my long process via Celery
from flask import Flask,render_template
from forms import LoginForm
from test_webapp import testing_webapp
from flask import render_template, flash, redirect
from celery import Celery
app = Flask(__name__)
app.config['SECRET_KEY'] = 'This is secret key'
celery = Celery(app.name, broker= 'amqp://localhost//')
#celery.task
def call_demographic_data(brand,start_date,end_date,Country):
'''
This is a really long process
'''
testing_webapp(brand,start_date,end_date,Country)
#app.route('/index',methods=[ 'GET','POST'])
def index():
return "Query Submitted successfully"
#app.route('/',methods=[ 'GET'])
#app.route('/input',methods=[ 'GET','POST'])
def input():
form = LoginForm()
if form.validate_on_submit():
call_demographic_data.delay(form.brand.data,form.startdate.data,form.enddate.data,form.Country.data)
return redirect('/index')
return render_template('input.html', title='Enter a Brand', form=form)
#return ("should return index page")
if __name__ == '__main__':
app.run(debug=True)
but when I run my python script , nothing happens to interface, it is kind of stuck, it should have been redirected to index page (the one which shows that query has been successfully submitted)
Below is the console (Anaconda Prompt o/p)
(base) C:\Users\aadhikarla\Insight Auomation\app>python standard_routes.py
* Serving Flask app "standard_routes" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 908-258-463
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [26/Jun/2019 12:47:14] "GET /input HTTP/1.1" 200 -
It does not move forward from the GET request , I had changed the long program to just few print statements for testing celery , but it is not happening at all.
Also It is my understanding that by using Celery even if the user closes the browser , the Job will still persist and not stop , please let me know if my inference is correct as well
I am trying to get started with Flask, and I get 404 Not Found error for the hello world program.
The program I use:
from flask import Flask
app = Flask(__name__)
#app.route('/')
#app.route('/index.html')
def hello_world():
return 'Hello, World'
if __name__== '__main__':
app.run(host='localhost')
then I run
$export FLASK_APP = minimal.py
$flask run
Which returns:
* Serving Flask app "minimal"
* Forcing debug mode on
* Restarting with stat
* Debugger is active!
* Debugger PIN 127-804-808
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
When I visit http://localhost:5000 or http://127.0.0.1:5000, I get:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
And my host file looks like this:
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
Any idea whats wrong? Thank you
Yeah, you can remove the error 404 not found in following ways:
1: You should write command netstat -a -b to check which port is not free or busy doing something or
2: write in your code app.run(port=4996) instead of app.run() which by default choose port no. 50000.