import gevent
from gevent import monkey
import redis
import requests
import time
import flask
from flask import Flask
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
monkey.patch_all()
def task1():
print("start task1")
gevent.sleep(2)
return "task1"
def task2():
print("start task2")
gevent.sleep(9)
return "task2"
def task3(i):
t1 = time.time()
requests.get("http://localhost:" + str(i))
t2 = time.time()
return "task" + str(i) + "\t" + str(t2-t1)
def task4():
print("start task4")
jobs = []
for i in [8092, 8093]:
job = gevent.spawn(task3, i)
jobs.append(job)
results = gevent.joinall(jobs, timeout=2.8)
for result in results:
print(result.get())
return "task4"
def main():
tasks = [gevent.spawn(task1), gevent.spawn(task2), gevent.spawn(task4)]
@app.route("/")
def index():
with gevent.Timeout(1, False):
time.sleep(2)
main()
current_greenlet = gevent.getcurrent()
print(current_greenlet)
return "123"
if __name__ == "__main__":
http_server = WSGIServer(('0.0.0.0', 12345), app, log=None)
http_server.serve_forever()
- 这里可以看flask如何使用协程并发;
- 这里看协程如何超时熔断
3