1. web服务的架构和特点
2.使用线程池ThreadPoolExecutor加速
3. 代码fastapi实现web服务并加速
import jsonimport timeimport uvicornfrom fastapi import FastAPIapp = FastAPI()import timefrom functools import wrapsdef timethis(func): ''' Decorator that reports the execution time. ''' @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end-start) return result return wrapperdef do_file(): time.sleep(0.1) return 'result file'def do_db(): time.sleep(0.2) return 'result db'def do_api(): time.sleep(0.3) return 'result api'from concurrent.futures import ThreadPoolExecutorimport concurrent.futures@app.get('/')@timethisdef index(): with concurrent.futures.ThreadPoolExecutor() as pool: read_file = pool.submit(do_file) read_api = pool.submit(do_api) read_db = pool.submit(do_db) return json.dumps({ "read_file":read_file.result(), "read_api":read_api.result(), "read_db":read_db.result() })if __name__ == '__main__': uvicorn.run(app,host='127.0.0.1',port=8000)##############index 0.6029112339019775INFO: 127.0.0.1:55583 - "GET / HTTP/1.1" 200 OKvsindex 0.3037288188934326INFO: 127.0.0.1:55264 - "GET / HTTP/1.1" 200 OK