Skip to content

Commit

Permalink
Api 增加 rule 筛选
Browse files Browse the repository at this point in the history
  • Loading branch information
pjialin committed Jul 12, 2019
1 parent d312ef4 commit 3a5d10a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
12 changes: 7 additions & 5 deletions src/app/ip_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,26 @@

class IPFactory:
@classmethod
async def get_random_ip(cls, https: bool = False) -> IPData:
ips = await cls.get_ips(https=https)
ip = random.choice(ips)
if not ip:
async def get_random_ip(cls, https: bool = False, rule: str = None) -> IPData:
ips = await cls.get_ips(https=https, rule=rule)
if not ips:
return None
ip = random.choice(ips)
assert isinstance(ip, IPData), 'Error format'
Logger.info('[factory] get ip %s', ip.to_str())
return ip

@classmethod
async def get_ips(cls, http: bool = True, https: bool = False, delay: int = None):
async def get_ips(cls, http: bool = True, https: bool = False, delay: int = None, rule: str = None):
keys = []
if http:
keys.append(Config.REDIS_KEY_ABLE_HTTP)
if https:
keys.append(Config.REDIS_KEY_ABLE_HTTPS)
if delay:
keys.append(Config.REDIS_KEY_NET_DELAY % delay)
if rule:
keys.append(Config.REDIS_KEY_ABLE_RULES % rule)
with await Redis.share() as redis:
ips = await redis.sinter(*keys)
ips = [IPData.with_str(ip.decode()) for ip in ips]
Expand Down
19 changes: 11 additions & 8 deletions src/app/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@ def run(self):

@app.route('/get_ip')
async def get_ip(request):
ip = await IPFactory.get_random_ip(bool(request.raw_args.get('https', False)))
return json({
'ip': ip.ip,
'port': ip.port,
# 'https': ip.https,
'http': ip.to_http(),
})
is_https = bool(request.raw_args.get('https', False))
rule = request.raw_args.get('rule')
ip = await IPFactory.get_random_ip(https=is_https, rule=rule)
if ip:
return json({'ip': ip.ip, 'port': ip.port,
# 'https': ip.https,
'http': ip.to_http(),
})
else:
return json({'msg': 'The ip pool is empty. '})


if __name__ == '__main__':
Web().start()
Web().start()

0 comments on commit 3a5d10a

Please sign in to comment.