kuwo-singers-page-name

1.获取所有singer

from django.shortcuts import HttpResponse
from django.core.cache import cache
import requests, functools
import demjson

def get_singers(request):

      url =

"http://artistlistinfo.kuwo.cn/mb.slist?stype=artistlist&category=0&order=hot&pn=0&rn=100&encoding=utf8"
response = requests.get(url)
return HttpResponse(respone.text, content_type="application/json")

2.自定义一个装饰器

def api(func):
    # functools.wraps防止出错
    @functools.wraps(func)
    def deal_with(*args, **kwargs):
        response_data = demjson.encode(func(*args, **kwargs))
        response = HttpResponse(response_data, content_type='application/json')
        # 解决跨域请求问题
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        response["Access-Control-Max-Age"] = "1000"
        response["Access-Control-Allow-Headers"] = "*"
        return response
    return deal_with

3.给get_singers加装饰器并拼接pic的url

@api
def get_singers(request):
    url = "http://artistlistinfo.kuwo.cn/mb.slist?stype=artistlist&category=0&order=hot&pn=0&rn=100&encoding=utf8"
    response = requests.get(url)
    json_obj = demjson.decode(response.text)
    artistlist = json_obj.get('artistlist', None)
    for artist in artistlist:
        artist['pic'] = 'http://img1.sycdn.kuwo.cn/star/starheads/' + artist.get("pic")
    artist_dict = {
        "artistlist": artistlist
    }
    return artist_dict

4.md5加密接口

import time
import hashlib

def md5(arg):
    h = hashlib.md5()
    h.update(arg.encode("utf-8"))
    return h.hexdigest()

@api
def api_safe(request):
    time_stamp = time.time()
    print(time_stamp)
    auth_key = request.META.get("HTTP_KEY")
    if not auth_key:
        return {'msg': 'you are not client'}
    # auth_key = 32位字符串|时间戳|其它字符
    client_md5_str, client_time = auth_key.split("|")
    client_time = float(client_time)
    if client_time + 100 < time_stamp:
        return {'msg': 'time out'}
    server_md5_str = md5("{}|{}".format(key, client_time))
    client_md5_str = md5("{}|{}".format(client_md5_str, client_time))
    if server_md5_str != client_md5_str:
        return {
            'msg': 'key not right'
        }
    if client_md5_str in visited_api:
        return {'msg': 'you have visited'}
    visited_api[client_md5_str] = client_md5_str
    return {'msg': 'hello world'}

5.设置分页

page = request.GET.get('page', '1')
# isdigit 如果字符串只包含数字则返回Trur,否则False
# if page.isdigit():
#     page = int(page)
# else:
#     page = 1
# 有点复杂了,用‘三元运算符‘
page = int(page) if page.isdigit() else 1
size = 20

……

for artist in artistlist:
    artist['pic'] = 'http://img1.sycdn.kuwo.cn/star/starheads/' + artist.get("pic")

artist_dict = {
    "artistlist": artistlist[(page - 1) * size: page * size]
}
return artist_dict

6.按照歌手名称首字母查询

cname = request.GET.get('cname', 'hot').lower()
if cname in 'q w e r t y u i o p a s d f g h j k l z x c v b n m'.split(' '):
    url = SINGERS_NAME_URL.format(cname)
    response = requests.get(url)
    json_str = response.text
    json_obj = demjson.decode(json_str)
    return json_obj

7.数据持久化---存放在硬盘,不是内存

(1)保存txt,但是数据是固定的,需要自己手动更新,推荐第二种!

response = requests.get(url)
    json_str = response.text
    with open("singers.txt", "w", encoding="utf-8") as f:
         f.write(response.text)
else:
    with open("singers.txt", encoding="utf-8") as f:
         json_str = f.read()

json_obj = demjson.decode(json_str)
artistlist = json_obj.get('artistlist', None)
for artist in artistlist:
    artist['pic'] = 'http://img1.sycdn.kuwo.cn/star/starheads/' + artist.get("pic")

artist_dict = {
    "artistlist": artistlist[(page - 1) * size: page * size]
}
return artist_dict

(2)Django使用Redis数据缓存

   需要先安装redis并启动,网上有详细教程0.0

from django.core.cache import cache #引入缓存模块
response = requests.get(url)
    json_str = response.text
    # with open("singers.txt", "w", encoding="utf-8") as f:
    #     f.write(response.text)
    cache.set('singers.txt', json_str, 10 * 60)
else:
    # with open("singers.txt", encoding="utf-8") as f:
    #     json_str = f.read()
    json_str = cache.get('singers.txt')
json_obj = demjson.decode(json_str)
artistlist = json_obj.get('artistlist', None)
for artist in artistlist:
    artist['pic'] = 'http://img1.sycdn.kuwo.cn/star/starheads/' + artist.get("pic")

artist_dict = {
    "artistlist": artistlist[(page - 1) * size: page * size]
}
return artist_dict

8.得到歌手的数量(根据名称首字母)

pyecharts:后端图表展示库(网上有详细教程,自行查找)

from pyecharts import Bar
def get_singers_num(request):
    list = [chr(x).upper() for x in range(97, 123)]
    total_number = []
    for x in list:
        if not cache.has_key('{}'.format(x)):
            url_x = CHARACTER_SINGER_URL.format(x)
            response = requests.get(url_x)
            json_str = response.text
            cache.set('{}'.format(x), json_str, 5*60)
        else:
            json_str = cache.get('{}'.format(x))
        json_obj = demjson.decode(json_str)
        number = int(json_obj.get('total', 0))
        total_number.append(number)
    bar =Bar('歌手数量柱状图', '小标题')
    bar.add('歌手数量', list, total_number, is_more_utils=True)
    print(list)
    print(total_number)
    bar.render()
    with open('render.html', encoding='utf-8') as f:
        html = f.read()
    return HttpResponse(html)

9.以上项目就完成了。接下来有想法的可以写一个接口文档,我用过apidoc(也可以用word)。

这个自行查找:

如果随便一个人通过这个文档都能获取数据,则它是好文档

如果确实不知道咋写,就参考新浪微博接口文档

 

文档书写方式

1. 使用word文档 操作麻烦,格式难统一,浏览不方便

2. 使用excel表格 操作麻烦,浏览不方便

3. 使用网页 使用ApiDoc或者Mkdocs来制作 推荐写法

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值