Skip to content

Instantly share code, notes, and snippets.

@snower
Created September 10, 2021 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snower/b6d0288c60f4d40e544fb530a011ce62 to your computer and use it in GitHub Desktop.
Save snower/b6d0288c60f4d40e544fb530a011ce62 to your computer and use it in GitHub Desktop.
flask_and_asyncio
# -*- coding: utf-8 -*-
# 2021/9/9
# create by: snower
import threading
import asyncio
from flask import Flask
app = Flask(__name__)
_loop_thread = None
_loop = None
def get_loop():
global _loop_thread, _loop
if _loop:
return _loop
_loop = asyncio.new_event_loop()
def run():
asyncio.set_event_loop(_loop)
_loop.run_forever()
_loop_thread = threading.Thread(target=run)
_loop_thread.setDaemon(True)
_loop_thread.start()
return _loop
@app.route("/")
def hello_world():
event = threading.Event()
def asyncio_run():
print("This is running in asyncio")
event.set()
print("This is wait asyncio run")
get_loop().call_soon_threadsafe(asyncio_run)
event.wait()
print("This is asyncio running finish")
return "<p>Hello, World!</p>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment