惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Security Blog
Microsoft Security Blog
aimingoo的专栏
aimingoo的专栏
I
InfoQ
C
Check Point Blog
IT之家
IT之家
MyScale Blog
MyScale Blog
Apple Machine Learning Research
Apple Machine Learning Research
Vercel News
Vercel News
Last Week in AI
Last Week in AI
GbyAI
GbyAI
P
Proofpoint News Feed
量子位
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
B
Blog
T
The Blog of Author Tim Ferriss
H
Help Net Security
云风的 BLOG
云风的 BLOG

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
How to Use Asyncio with Flask Applications
2020-06-07 · via jdhao's digital space

I was using asyncio inside a view function for Flask to run some asynchronous functions and met an error.

Here is the demo code:

import asyncio

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/toy", methods=["GET"])
def index():
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(hello())

    return jsonify({"result": result})


async def hello():
    await asyncio.sleep(1)
    return 1


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=4567, debug=False)

When I request this service, I get the following error from asyncio.event:

RuntimeError: There is no current event loop in thread ‘Thread-1’.

for the following line of code:

loop = asyncio.get_event_loop()

From the asyncio documentation on default event loop policy:

If the current thread doesn’t already have an event loop associated with it, the default policy’s get_event_loop() method creates one when called from the main thread, but raises RuntimeError otherwise

So it seems that the view function index() is not run in the main thread. As a result, there is no event loop associated with the current thread, hence the error message. To verify this, we can use the threading module to help us find which thread we are currently in:

import threading
import asyncio

from flask import Flask, jsonify


print(f"In flask global level: {threading.current_thread().name}")
app = Flask(__name__)

@app.route("/toy", methods=["GET"])
def index():
    print(f"Inside flask function: {threading.current_thread().name}")

    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(hello())

    return jsonify({"result": result})


async def hello():
    await asyncio.sleep(1)
    return 1


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=4567, debug=False)

When running the flask app, we can see the following message:

In flask global level: MainThread

So the statement outside the view function is run in the main thread.

When we request the service, we can see the following message from the view function:

Inside flask function: Thread-1

This verifies that Flask is indeed running the view functions in a separate thread other than the main thread.

In the Flask.run() doc, this is also briefly mentioned in the changelog part:

Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files.

If set, the FLASK_ENV and FLASK_DEBUG environment variables will override env and debug.

Threaded mode is enabled by default.

Under the hood, Flask.run() is using werkzeug.serving.run_simple() to server the app and set the threaded option to True by default:

threaded – should the process handle each request in a separate thread?

What does the threaded mode mean? It means that the server can serve requests in a non-blocking fashion, i.e., it does not need to wait for one request to finish to process another request. That is often preferred than the single-threaded mode. Note, however, that the development server is not for production purposes. We need to use dedicated WSGI server such as gunicorn and uWSGI in production for better performance.

References#