Flask的服务, 默认是同步的, 所以以下代码, 在接收多个请求是会发生阻塞的, 导致打开页面变得很慢, 很卡:
# -*- coding: utf-8 -*-
from flask import Flask
import requests
import random
from datetime import datetime
app = Flask(__name__)
urls = ['https://www.python.org/','https://www.yahoo.com/','https://github.com/']
@app.route('/')
def index():
time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
respond = requests.get(urls[int(random.random()*3)]).content.decode()
print(time+' -- '+ str(len(respond)))
return datetime.now().strftime("%Y-%m-%d %H:%M:%S --")+ str(len(respond))
app.run('127.0.0.1',5000)
比较简便的实现异步的方式就是借助第三方库: gevent
# -*- coding: utf-8 -*-
from gevent im