It gives answers to these questions:
In short, if you are curious about what your endpoints are doing and what requests they are receiving, give a try to flask-profiler.
With flask-profiler's web interface, you can monitor all your endpoints' performance and investigate endpoints and received requests by drilling down through filters.
Dashboard view displays a summary.
You can create filters to investigate certain type requests.
You can see all the details of a request.
It is easy to understand flask-profiler going through an example. Let's dive in.
Install flask-profiler by pip.
pip install flask_profiler
Edit your code where you are creating Flask app.
# your app.py
from flask import Flask
import flask_profiler
app = Flask(__name__)
app.config["DEBUG"] = True
# You need to declare necessary configuration to initialize
# flask-profiler as follows:
app.config["flask_profiler"] = {
"enabled": app.config["DEBUG"],
"storage": {
"engine": "sqlite"
},
"basicAuth":{
"enabled": True,
"username": "admin",
"password": "admin"
},
"ignore": [
"^/static/.*"
]
}
@app.route('/product/<id>', methods=['GET'])
def getProduct(id):
return "product id is " + str(id)
@app.route('/product/<id>', methods=['PUT'])
def updateProduct(id):
return "product {} is being updated".format(id)
@app.route('/products', methods=['GET'])
def listProducts():
return "suppose I send you product list..."
@app.route('/static/something/', methods=['GET'])
def staticSomething():
return "this should not be tracked..."
# In order to active flask-profiler, you have to pass flask
# app as an argument to flask-profiler.
# All the endpoints declared so far will be tracked by flask-profiler.
flask_profiler.init_app(app)
# endpoint declarations after flask_profiler.init_app() will be
# hidden to flask_profiler.
@app.route('/doSomething', methods=['GET'])
def doSomething():
return "flask-profiler will not measure this."
# But in case you want an endpoint to be measured by flask-profiler,
# you can specify this explicitly by using profile() decorator
@app.route('/doSomethingImportant', methods=['GET'])
@flask_profiler.profile()
def doSomethingImportant():
return "flask-profiler will measure this request."
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
Now run your app.py
python app.py
And make some requests like:
curl http://127.0.0.1:5000/products
curl http://127.0.0.1:5000/product/123
curl -X PUT -d arg1=val1 http://127.0.0.1:5000/product/123
If everything is okay, Flask-profiler will measure these requests. You can see the result heading to http://127.0.0.1:5000/flask-profiler/ or get results as JSON http://127.0.0.1:5000/flask-profiler/api/measurements?sort=elapsed,desc
If you like to initialize your extensions in other files or use factory apps pattern, you can also create a instance of the Profiler
class, this will register all your endpoints once you app run by first time. E.g:
from flask import Flask
from flask_profiler import Profiler
profiler = Profiler()
app = Flask(__name__)
app.config["DEBUG"] = True
# You need to declare necessary configuration to initialize
# flask-profiler as follows:
app.config["flask_profiler"] = {
"enabled": app.config["DEBUG"],
"storage": {
"engine": "sqlite"
},
"basicAuth":{
"enabled": True,
"username": "admin",
"password": "admin"
},
"ignore": [
"^/static/.*"
]
}
profiler = Profiler() # You can have this in another module
profiler.init_app(app)
# Or just Profiler(app)
@app.route('/product/<id>', methods=['GET'])
def getProduct(id):
return "product id is " + str(id)
You can use flaskprofiler with SqlLite, MongoDB, Postgresql, Mysql or MongoDB database systems. However, it is easy to support other database systems. If you would like to have others, please go to contribution documentation. (It is really easy.)
In order to use SQLite, just specify it as the value of storage.engine
directive as follows.
app.config["flask_profiler"] = {
"storage": {
"engine": "sqlite",
}
}
Below the other options are listed.
Filter key | Description | Default |
---|---|---|
storage.FILE | SQLite database file name | flask_profiler.sql |
storage.TABLE | table name in which profiling data will reside | measurements |
In order to use MongoDB, just specify it as the value of storage.engine
directive as follows.
app.config["flask_profiler"] = {
"storage": {
"engine": "mongodb",
}
}
In order to use SQLAchemy, just specify it as the value of storage.engine
directive as follows.Also first create an empty database with the name "flask_profiler".
app.config["flask_profiler"] = {
"storage": {
"engine": "sqlalchemy",
"db_url": "postgresql://user:pass@localhost:5432/flask_profiler" # optional, if no db_url specified then sqlite will be used.
}
}
Specify engine as string module and class path.
app.config["flask_profiler"] = {
"storage": {
"engine": "custom.project.flask_profiler.mysql.MysqlStorage",
"MYSQL": "mysql://user:password@localhost/flask_profiler"
}
}
The other options are listed below.
Filter key | Description | Default |
---|---|---|
storage.MONGO_URL | mongodb connection string | mongodb://localhost |
storage.DATABASE | database name | flask_profiler |
storage.COLLECTION | collection name | measurements |
Control the number of samples taken by flask-profiler
You would want control over how many times should the flask profiler take samples while running in production mode.You can supply a function and control the sampling according to your business logic.
Example 1: Sample 1 in 100 times with random numbers
app.config["flask_profiler"] = {
"sampling_function": lambda: True if random.sample(list(range(1, 101)), 1) == [42] else False
}
Example 2: Sample for specific users
app.config["flask_profiler"] = {
"sampling_function": lambda: True if user is 'divyendu' else False
}
If sampling function is not present, all requests will be sampled.
By default, we can access flask-profiler at /flask-profiler
app.config["flask_profiler"] = {
"endpointRoot": "secret-flask-profiler"
}
Flask-profiler will try to track every endpoint defined so far when init_app() is invoked. If you want to exclude some of the endpoints, you can define matching regex for them as follows:
app.config["flask_profiler"] = {
"ignore": [
"^/static/.*",
"/api/users/\w+/password"
]
}
Contributions are welcome!
Review the Contributing Guidelines for details on how to:
MIT
1. 疑问 @app.cli.command() @click.option('--length', default=25, help='Number of functions to include in the profiler report.') @click.option('--profile-dir', default=None, h
Abstrct flask从0.11版本开始引入了click提供命令行支持,在此之前我们通常会引入Flask-Script来提供。 在《Flask web开发》这本书编写时flask0.11还没有发布,因此书中仍然以flask-script提供命令行支持。因此在flask0.11发布一年后,作者写了这篇文章来帮助大家从flask-script迁移到Flask-Cli,该博文便是作者这篇文章的翻译。
SQLite是一个小型的轻量数据库,特别适合个人学习使用。因为SQLite不需要额外的数据库服务器,同时它也是内嵌在Python中的。缺点就是如果有大量的写请求过来,它是串行处理的,速度很慢。 连接数据库 新建flaskr/db.py文件: import sqlite3 import click from flask import current_app, g from flask.cli im
一、SQLAlchemy SQLAlchemy是个不错的orm框架,但是有点尴尬,因为flask的目的就是轻量,大多数情况于我而言就是随便写几个接口,如果功能复杂质量要求高,我就直接用java了。所以用flask写接口,也许我们不需要关注数据库里各个表中的关系,而只要知道每个sql语句返回的数据结构就足够了。 二、Flask中随性的SQL 不把SQLAlchemy当orm用,但不代表SQLAlch
问题内容: 在官方的快速入门中,建议在使用单个 模块 时使用: 2. …如果您使用的是单个模块(如本例所示),则应使用,因为取决于它是作为应用程序启动还是作为模块导入,其名称将有所不同(与实际导入名称不同)。… 但是,在他们的API文档中,当我的应用程序为 软件包 时,建议进行硬编码: 因此,您在此处提供的内容很重要。如果使用单个模块,则始终为正确的值。但是,如果您使用的是包,通常建议在其中硬编码
在前面,我们介绍了 REST Web 服务,并使用 Flask 提供服务。这里,我们使用第三方库 Flask-RESTful,它使得在 Flask 中提供 REST 服务变得更加简单。 安装 使用 pip 安装: $ pip install flask-restful 使用 下面我们主要使用官方文档的例子进行说明。 Hello World 我们先来看一个简单的例子。 # -*- coding: u
Bootstrap 是 Twitter 开源的一个 CSS/HTML 框架,它让 Web 开发变得更加迅速,简单。要想在我们的 Flask 应用中使用 Boostrap,有两种方案可供选择: 第 1 种,在我们的 Jinja 模板中直接引入 Bootstrap 层叠样式表 (CSS) 和 JavaScript 文件,比如 bootstrap.min.css,bootstrap.min.js; 第
在 Web 应用中,我们经常需要保护我们的 api,以避免非法访问。比如,只允许登录成功的用户发表评论等。Flask-HTTPAuth 扩展可以很好地对 HTTP 的请求进行认证,不依赖于 Cookie 和 Session。本文主要介绍两种认证的方式:基于密码和基于令牌 (token)。 安装 使用 pip 安装: $ pip install Flask-HTTPAuth 基于密码的认证 为了简化
假设你的 Web 服务对于某些请求比较耗时,而该请求的返回结果在较短的时间内(比如 5 分钟内)都是足够有效的,这时你能想到什么方法去改善这种状况呢?缓存?对,至少这是一种提高性能的最简单的方法。 Flask 本身不提供缓存功能,但是作为 Flask 核心的 Werkzeug 框架则提供了一个简单的缓存对象 SimpleCache,它将缓存项存放在 Python 解释器的内存中。使用 Simple
MongoDB 是一个文档型数据库,是 NoSQL (not only SQL) 的一种,具有灵活、易扩展等诸多优点,受到许多开发者的青睐。MongoEngine 是一个用来操作 MongoDB 的 ORM 框架,如果你不知道什么是 ORM,可以参考 Flask-SQLAlchemy 一节。在 Flask 中,我们可以直接使用 MongoEngine,也可使用 Flask-MongoEngine