proxyApi.py 3.4 KB

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