ProxyApi.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. -------------------------------------------------
  5. File Name: ProxyApi.py
  6. Description : WebApi
  7. Author : JHao
  8. date: 2016/12/4
  9. -------------------------------------------------
  10. Change Activity:
  11. 2016/12/04: WebApi
  12. 2019/08/14: 集成Gunicorn启动方式
  13. -------------------------------------------------
  14. """
  15. __author__ = 'JHao'
  16. import sys
  17. import gunicorn.app.base
  18. from gunicorn.six import iteritems
  19. from werkzeug.wrappers import Response
  20. from flask import Flask, jsonify, request
  21. sys.path.append('../')
  22. from Config.ConfigGetter import config
  23. from Manager.ProxyManager import ProxyManager
  24. app = Flask(__name__)
  25. class JsonResponse(Response):
  26. @classmethod
  27. def force_type(cls, response, environ=None):
  28. if isinstance(response, (dict, list)):
  29. response = jsonify(response)
  30. return super(JsonResponse, cls).force_type(response, environ)
  31. app.response_class = JsonResponse
  32. api_list = {
  33. 'get': u'get an useful proxy',
  34. # 'refresh': u'refresh proxy pool',
  35. 'get_all': u'get all proxy from proxy pool',
  36. 'delete?proxy=127.0.0.1:8080': u'delete an unable proxy',
  37. 'get_status': u'proxy number'
  38. }
  39. @app.route('/')
  40. def index():
  41. return api_list
  42. @app.route('/get/')
  43. def get():
  44. proxy = ProxyManager().get()
  45. return proxy.info_json if proxy else {"code": 0, "src": "no proxy"}
  46. @app.route('/refresh/')
  47. def refresh():
  48. # TODO refresh会有守护程序定时执行,由api直接调用性能较差,暂不使用
  49. # ProxyManager().refresh()
  50. pass
  51. return 'success'
  52. @app.route('/get_all/')
  53. def getAll():
  54. proxies = ProxyManager().getAll()
  55. return [_.info_dict for _ in proxies]
  56. @app.route('/delete/', methods=['GET'])
  57. def delete():
  58. proxy = request.args.get('proxy')
  59. ProxyManager().delete(proxy)
  60. return {"code": 0, "src": "success"}
  61. @app.route('/get_status/')
  62. def getStatus():
  63. status = ProxyManager().getNumber()
  64. return status
  65. class StandaloneApplication(gunicorn.app.base.BaseApplication):
  66. def __init__(self, app, options=None):
  67. self.options = options or {}
  68. self.application = app
  69. super(StandaloneApplication, self).__init__()
  70. def load_config(self):
  71. _config = dict([(key, value) for key, value in iteritems(self.options)
  72. if key in self.cfg.settings and value is not None])
  73. for key, value in iteritems(_config):
  74. self.cfg.set(key.lower(), value)
  75. def load(self):
  76. return self.application
  77. def runFlask():
  78. app.run(host=config.host_ip, port=config.host_port)
  79. def runFlaskWithGunicorn():
  80. _options = {
  81. 'bind': '%s:%s' % (config.host_ip, config.host_port),
  82. 'workers': 4,
  83. 'accesslog': '-', # log to stdout
  84. 'access_log_format': '%(h)s %(l)s %(t)s "%(r)s" %(s)s "%(a)s"'
  85. }
  86. StandaloneApplication(app, _options).run()
  87. if __name__ == '__main__':
  88. # runFlask()
  89. runFlaskWithGunicorn()