1. web服务的架构和特点

image.png

2.使用线程池ThreadPoolExecutor加速

image.png

3. 代码fastapi实现web服务并加速

  1. import json
  2. import time
  3. import uvicorn
  4. from fastapi import FastAPI
  5. app = FastAPI()
  6. import time
  7. from functools import wraps
  8. def timethis(func):
  9. '''
  10. Decorator that reports the execution time.
  11. '''
  12. @wraps(func)
  13. def wrapper(*args, **kwargs):
  14. start = time.time()
  15. result = func(*args, **kwargs)
  16. end = time.time()
  17. print(func.__name__, end-start)
  18. return result
  19. return wrapper
  20. def do_file():
  21. time.sleep(0.1)
  22. return 'result file'
  23. def do_db():
  24. time.sleep(0.2)
  25. return 'result db'
  26. def do_api():
  27. time.sleep(0.3)
  28. return 'result api'
  29. from concurrent.futures import ThreadPoolExecutor
  30. import concurrent.futures
  31. @app.get('/')
  32. @timethis
  33. def index():
  34. with concurrent.futures.ThreadPoolExecutor() as pool:
  35. read_file = pool.submit(do_file)
  36. read_api = pool.submit(do_api)
  37. read_db = pool.submit(do_db)
  38. return json.dumps({
  39. "read_file":read_file.result(),
  40. "read_api":read_api.result(),
  41. "read_db":read_db.result()
  42. })
  43. if __name__ == '__main__':
  44. uvicorn.run(app,host='127.0.0.1',port=8000)
  45. ##############
  46. index 0.6029112339019775
  47. INFO: 127.0.0.1:55583 - "GET / HTTP/1.1" 200 OK
  48. vs
  49. index 0.3037288188934326
  50. INFO: 127.0.0.1:55264 - "GET / HTTP/1.1" 200 OK