api.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. -------------------------------------------------
  3. File Name: api.py
  4. Description: API模块,运行后打开浏览器,访问
  5. http://127.0.0.1:5000/进入主页。
  6. 访问 http://127.0.0.1:5000/get
  7. 从代理池中获取一个代理。
  8. 访问 http://127.0.0.1:5000/count
  9. 获取代理池中可用代理的总数。
  10. Author: Liu
  11. Date: 2016/12/9
  12. -------------------------------------------------
  13. """
  14. from flask import Flask, g
  15. from .db import RedisClient
  16. __all__ = ['app']
  17. app = Flask(__name__)
  18. def get_conn():
  19. """Opens a new redis connection if there is none yet for the
  20. current application context.
  21. """
  22. if not hasattr(g, 'redis_client'):
  23. g.redis_client = RedisClient()
  24. return g.redis_client
  25. @app.route('/')
  26. def index():
  27. return '<h1>Welcome</h1>'
  28. @app.route('/get')
  29. def get_proxy():
  30. """Get a proxy
  31. """
  32. conn = get_conn()
  33. return conn.pop()
  34. @app.route('/count')
  35. def get_counts():
  36. """Get the count of proxies
  37. """
  38. conn = get_conn()
  39. return str(conn.queue_len)
  40. if __name__ == '__main__':
  41. app.run()