This repository was archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrest_server.py
More file actions
97 lines (82 loc) · 2.2 KB
/
rest_server.py
File metadata and controls
97 lines (82 loc) · 2.2 KB
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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Danny0'
import json
import time
import web
from abc import ABCMeta, abstractmethod
from util.func import *
urls = (
"/", "Index",
'/ip', 'Ip',
)
class Api:
__metaclass__ = ABCMeta
def __init__(self):
self.ERROR_CODE = {
"0": "success",
"3000": "miss param",
"3001": "param num can not bigger than 5",
"4003": "no auth",
"5000": "ip pool is empty",
"5001": "request fail",
}
self.params = web.input(num="5")
self.time_start = time.time()
@abstractmethod
def GET(self):
pass
@staticmethod
def set_json_response():
"""
设置响应content-type为json
:return:
"""
web.header('content-type', 'application/json;charset=utf-8', unique=True)
def json(self, errno, data=None):
"""
发送json格式响应
:param errno:
:param data:
:return:
"""
data = data if data else []
self.set_json_response()
res = {
"errno": errno,
"message": self.ERROR_CODE[str(errno)],
"data": data,
"time": round(time.time() - self.time_start, 2)
}
return json.dumps(res)
def result(self, data):
"""
根据查询结果返回json
:param data:
"""
if not data:
return self.json(5001)
else:
return self.json(0, data)
class Ip(Api):
def GET(self):
# 从redis中拿
redis_ins = get_redis_ins()
num = int(self.params.num)
if num > 5:
return self.json(3001)
ips = redis_ins.zrange(REDIS_KEY, 0, num - 1) # 会包含结束index
if not ips:
# 没有可用IP
return self.json(5000)
# 增加使用次数
for ip in ips:
redis_ins.zincrby(REDIS_KEY, ip)
return self.result(ips)
class Index(Api):
def GET(self):
return "proxy rest api"
if __name__ == "__main__":
os.environ["PORT"] = "9090" if os.uname()[0] == "Darwin" else "80"
app = web.application(urls, globals())
app.run()