ProxyApi.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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 platform
  18. from werkzeug.wrappers import Response
  19. from flask import Flask, jsonify, request
  20. sys.path.append('../')
  21. from Config.ConfigGetter import config
  22. from Manager.ProxyManager import ProxyManager
  23. app = Flask(__name__)
  24. class JsonResponse(Response):
  25. @classmethod
  26. def force_type(cls, response, environ=None):
  27. if isinstance(response, (dict, list)):
  28. response = jsonify(response)
  29. return super(JsonResponse, cls).force_type(response, environ)
  30. app.response_class = JsonResponse
  31. api_list = {
  32. 'get': u'get an useful proxy',
  33. # 'refresh': u'refresh proxy pool',
  34. 'get_all': u'get all proxy from proxy pool',
  35. 'delete?proxy=127.0.0.1:8080': u'delete an unable proxy',
  36. 'get_status': u'proxy number'
  37. }
  38. @app.route('/')
  39. def index():
  40. return api_list
  41. @app.route('/get/')
  42. def get():
  43. proxy = ProxyManager().get()
  44. return proxy.info_json if proxy else {"code": 0, "src": "no proxy"}
  45. @app.route('/refresh/')
  46. def refresh():
  47. # TODO refresh会有守护程序定时执行,由api直接调用性能较差,暂不使用
  48. # ProxyManager().refresh()
  49. pass
  50. return 'success'
  51. @app.route('/get_all/')
  52. def getAll():
  53. proxies = ProxyManager().getAll()
  54. return [_.info_dict for _ in proxies]
  55. @app.route('/delete/', methods=['GET'])
  56. def delete():
  57. proxy = request.args.get('proxy')
  58. ProxyManager().delete(proxy)
  59. return {"code": 0, "src": "success"}
  60. @app.route('/get_status/')
  61. def getStatus():
  62. status = ProxyManager().getNumber()
  63. return status
  64. if platform.system() != "Windows":
  65. import gunicorn.app.base
  66. from gunicorn.six import iteritems
  67. class StandaloneApplication(gunicorn.app.base.BaseApplication):
  68. def __init__(self, app, options=None):
  69. self.options = options or {}
  70. self.application = app
  71. super(StandaloneApplication, self).__init__()
  72. def load_config(self):
  73. _config = dict([(key, value) for key, value in iteritems(self.options)
  74. if key in self.cfg.settings and value is not None])
  75. for key, value in iteritems(_config):
  76. self.cfg.set(key.lower(), value)
  77. def load(self):
  78. return self.application
  79. def runFlask():
  80. app.run(host=config.host_ip, port=config.host_port)
  81. def runFlaskWithGunicorn():
  82. _options = {
  83. 'bind': '%s:%s' % (config.host_ip, config.host_port),
  84. 'workers': 4,
  85. 'accesslog': '-', # log to stdout
  86. 'access_log_format': '%(h)s %(l)s %(t)s "%(r)s" %(s)s "%(a)s"'
  87. }
  88. StandaloneApplication(app, _options).run()
  89. if __name__ == '__main__':
  90. if platform.system() == "Windows":
  91. runFlask()
  92. else:
  93. runFlaskWithGunicorn()