-
-
Save snower/b6d0288c60f4d40e544fb530a011ce62 to your computer and use it in GitHub Desktop.
flask_and_asyncio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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