Skip to content

Commit

Permalink
Optimized the performance and security of the query short code method
Browse files Browse the repository at this point in the history
  • Loading branch information
skyxv committed Dec 19, 2019
1 parent de9346d commit cfe484e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
27 changes: 19 additions & 8 deletions apps/urls/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from apps.utils.redis.client import redis_cli
from apps.utils.ip_query import ip_query
from apps.utils.transfer_url import get_id


class LinkMapManager(models.Manager):
Expand All @@ -24,17 +25,27 @@ def get_map_by_code(self, user, code):
return self.filter(code=code, created_by=user).first()

def get_url_by_code(self, code):
"""
先查短码对应的值是否为约定0值,如果是,则代表之前访问过的该短码不存在,直接返回空
值不为0, 如果缓存中有短码对应的长网址,则直接返回,如果缓存中没有,
则先转换得到id, 再去数据库中查,如果有,设置缓存后返回长网址,
如果没有,将该短码在缓存中的值设置为0(即标识为数据库中尚未存在状态)
"""
cache_url = redis_cli.get_data(code)
if cache_url != 0:
return cache_url
else:
link_map = self.filter(code=code).first()
if link_map:
redis_cli.set_data(link_map.code, link_map.url)
return link_map.url
# 将数据库中没有的短码也放在缓存中,用0标识数据库中尚未存在该值
if cache_url is not None:
return cache_url
else:
redis_cli.set_data(code, 0)
id_ = get_id(code)
link_map = self.filter(pk=id_).first()
if link_map:
redis_cli.set_data(link_map.code, link_map.url)
return link_map.url
# 将数据库中没有的短码也放在缓存中,用0标识数据库中尚未存在该值
else:
redis_cli.set_data(code, 0)
else: # 查到值为0则表示数据库中尚未存在, 直接返回空,不查询数据库。这个else其实可以直接不写,这里是为了更清晰
return None

def add_hit_count(self, code):
"""
Expand Down
12 changes: 12 additions & 0 deletions apps/utils/transfer_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ def _ten2any(n, b=64):
return res[::-1]


def _any2ten(code, b=64):
result = 0
for i in range(len(code)):
result *= b
result += _alpha.index(code[i])
return result


def get_code(n):
return _ten2any(n, 62)


def get_id(code):
return _any2ten(code, 62)

0 comments on commit cfe484e

Please sign in to comment.