forked from jhao104/proxy_pool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxyApi.py
138 lines (106 loc) · 4.15 KB
/
proxyApi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File Name: ProxyApi.py
Description : WebApi
Author : JHao
date: 2016/12/4
-------------------------------------------------
Change Activity:
2016/12/04: WebApi
2019/08/14: 集成Gunicorn启动方式
2020/06/23: 新增pop接口
2022/07/21: 更新count接口
-------------------------------------------------
"""
__author__ = 'JHao'
import platform
from werkzeug.wrappers import Response
from flask import Flask, jsonify, request
from util.six import iteritems
from helper.proxy import Proxy
from handler.proxyHandler import ProxyHandler
from handler.configHandler import ConfigHandler
app = Flask(__name__)
conf = ConfigHandler()
proxy_handler = ProxyHandler()
class JsonResponse(Response):
@classmethod
def force_type(cls, response, environ=None):
if isinstance(response, (dict, list)):
response = jsonify(response)
return super(JsonResponse, cls).force_type(response, environ)
app.response_class = JsonResponse
api_list = [
{"url": "/get", "params": "type: ''https'|''", "desc": "get a proxy"},
{"url": "/pop", "params": "", "desc": "get and delete a proxy"},
{"url": "/delete", "params": "proxy: 'e.g. 127.0.0.1:8080'", "desc": "delete an unable proxy"},
{"url": "/all", "params": "type: ''https'|''", "desc": "get all proxy from proxy pool"},
{"url": "/count", "params": "", "desc": "return proxy count"}
# 'refresh': 'refresh proxy pool',
]
@app.route('/')
def index():
return {'url': api_list}
@app.route('/get/')
def get():
https = request.args.get("type", "").lower() == 'https'
proxy = proxy_handler.get(https)
return proxy.to_dict if proxy else {"code": 0, "src": "no proxy"}
@app.route('/pop/')
def pop():
https = request.args.get("type", "").lower() == 'https'
proxy = proxy_handler.pop(https)
return proxy.to_dict if proxy else {"code": 0, "src": "no proxy"}
@app.route('/refresh/')
def refresh():
# TODO refresh会有守护程序定时执行,由api直接调用性能较差,暂不使用
return 'success'
@app.route('/all/')
def getAll():
https = request.args.get("type", "").lower() == 'https'
proxies = proxy_handler.getAll(https)
return jsonify([_.to_dict for _ in proxies])
@app.route('/delete/', methods=['GET'])
def delete():
proxy = request.args.get('proxy')
status = proxy_handler.delete(Proxy(proxy))
return {"code": 0, "src": status}
@app.route('/count/')
def getCount():
proxies = proxy_handler.getAll()
http_type_dict = {}
source_dict = {}
for proxy in proxies:
http_type = 'https' if proxy.https else 'http'
http_type_dict[http_type] = http_type_dict.get(http_type, 0) + 1
for source in proxy.source.split('/'):
source_dict[source] = source_dict.get(source, 0) + 1
return {"http_type": http_type_dict, "source": source_dict, "count": len(proxies)}
def runFlask():
if platform.system() == "Windows":
app.run(host=conf.serverHost, port=conf.serverPort)
else:
import gunicorn.app.base
class StandaloneApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(StandaloneApplication, self).__init__()
def load_config(self):
_config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(_config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
_options = {
'bind': '%s:%s' % (conf.serverHost, conf.serverPort),
'workers': 4,
'accesslog': '-', # log to stdout
'access_log_format': '%(h)s %(l)s %(t)s "%(r)s" %(s)s "%(a)s"'
}
StandaloneApplication(app, _options).run()
if __name__ == '__main__':
runFlask()