之前的文章可以看:https://www.lowion.cn/2023/03/1046/ ,这篇文章对之前的屎山代码优化及修复

文末附免费API地址申请教程,API版本源码以后会出

1.个人版代码

import time, feedparser
from flask import Flask, make_response
from datetime import datetime
import pytz

app = Flask(__name__)

suoxieLIB = {'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thu': 4, 'Fri': 5, 'Sat': 6, 'Sun': 7,
             'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10,
             'Nov': 11, 'Dec': 12}

t=0
rss_oschina = feedparser.parse('https://lowion.cn/?feed=rss2')
@app.route('/reload')
def reload():
    global t
    global rss_oschina
    if int(time.time())-t>=900:
        rss_oschina = feedparser.parse('https://lowion.cn/?feed=rss2')  # 获取rss
        t=int(time.time())
        fresponse = make_response({'code':'200','msg':'done','reload':'True'})  # 防止跨域报错
        fresponse.headers['Access-Control-Allow-Origin'] = '*'
        return fresponse
    else:
        fresponse = make_response({'code':'200','msg':'done','reload':'False'})  # 防止跨域报错
        fresponse.headers['Access-Control-Allow-Origin'] = '*'
        return fresponse
@app.route('/')
def start():
    """
    rss_ochina:FEED原文
    datay:日期原文&日期格式化列表
    fresponse:返回数据参数
    dt:当前时间
    zerotime:基准线时间(+0000)
    chattime:本地实际转基准线时间
    timestampNOW:当前时间戳
    timestampARC:最后一篇文章更新时间时间戳
    chageTIME:现在时间和最后一篇文章更新时间的差(秒)
    hchu:计算小时转换成天数的临时变量
    hchuy:计算小时转换成天数余数的临时变量
    """
    global outhour, backjson
    dt = datetime.now()
    # print(f'本地时间:{dt}')
    zerotime = pytz.timezone('Etc/GMT-0')

    chatime = dt.astimezone(zerotime)
    # print(f'基准线时间:{chatime}')

    reload()
    # print('Start')
    datay = rss_oschina['entries'][0]['published'].split(" ")

    for i in suoxieLIB:
        if datay[0].find(i) != -1:
            datay[0] = datay[0].replace(i, str(suoxieLIB[i]))
        if datay[2].find(i) != -1:
            datay[2] = datay[2].replace(i, str(suoxieLIB[i]))
    # print(datay)

    chatime = str(chatime).split(' ')
    chatime[1] = chatime[1].replace('+00:00', '').split(':')
    chatime[1][2] = chatime[1][2].split('.')[0]
    chatime = chatime[0] + ' ' + chatime[1][0] + ':' + chatime[1][1] + ':' + chatime[1][2]

    # print(chatime)
    dt = chatime

    # 转换成时间数组
    timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    # 转换成时间戳
    timestampNOW = time.mktime(timeArray)

    # print(timestampNOW)

    for i in range(0, len(datay)):
        datay[i] = datay[i].replace(',', '')
        datay[i] = str(datay[i])
        if len(datay[i]) == 1:
            datay[i] = '0' + datay[i]

    # print(datay)
    dt = datay[3] + '-' + datay[2] + '-' + datay[1] + ' ' + datay[4]

    # 转换成时间数组
    timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    # 转换成时间戳
    timestampARC = time.mktime(timeArray)
    # print(timestampARC)

    timestampARC = int(timestampARC)
    timestampNOW = int(timestampNOW)

    chageTIME = timestampNOW - timestampARC

    seconds = chageTIME
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    # print("%02d:%02d:%02d" % (h, m, s))
    h=int(h)
    if h>=24:
        huch=int(h/24)
        hchuy=h%24
        backjson = {'days':huch,'hours': hchuy, 'min': m, 'sec': s, 'outhour': 'True','t':chageTIME}
    else:
        backjson = {'hours': h, 'min': m, 'sec': s,'outhour':'False','t':chageTIME}
    fresponse = make_response(backjson)  # 防止跨域报错
    fresponse.headers['Access-Control-Allow-Origin'] = '*'
    return fresponse


if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    app.run(host='0.0.0.0', port=8848)

增加了缓存系统(15分钟),优化了响应速度,这也是之前一直没把这段代码部署到我的博客上的原因

将实时请求改成了时间戳本地处理,二更的内容

2.服务端版

2.1接入

源码以后优化好会出,现在这里放一个申请教程。

首先,如果你在本站没有账号,请先在:https://www.lowion.cn/wp-login.php?action=register注册一个

注册好后,访问:http://archv.api.lowion.cn/register&email=[你注册时的邮箱]&rssurl=[你博客的RSS地址]

注意:博客的rss地址不能直接写入,样例:https://www.lowion.cn/feed → www.lowion.cn-feed,使用api需要博客部署https,因为我懒

完成效果:

调用结果:

可以使用新加的时间戳计算更新时间,球球各位别发请求了服务器要炸了

Javascript调用示例:

function refresh() {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', 'https://archv.api.lowion.cn/usercode=~~~', true);
    httpRequest.send();//第三步:发送请求  将请求参数写在URL中
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4 && httpRequest.status === 200) {
            var json = httpRequest.responseText;
            var objs = eval("(" + json + ")");
            if (objs.outhour==='False'){
                document.querySelector("#updatetime").innerHTML='距离上次更新:'+objs.hours+'小时 '+objs.min+'分钟 '+objs.sec+'秒'
            }else{
                document.querySelector("#updatetime").innerHTML='距离上次更新:'+objs.day+'天 '+objs.hours+'小时 '+objs.min+'分钟 '+objs.sec+'秒'
            }
        }
    }
}

window.setInterval("refresh()", 1000);

注:如果延迟较大,可以将window.setInterval("refresh()", 1000);改成window.setInterval("refresh()", 800);来缓解延迟

效果:

2.2错误码及报错说明

  • 404:一般来说出现在https://archv.api.lowion.cn/register路径,请仔细阅读上方接入说明
  • 503:服务器错误,可以点击左下角联系站长报错
  • 403:权限不足,一般因为没有注册或者注册非法
  • Internal Server Error,服务器错误,请点击左下角联系站长解决
  • 其他报错,请点击左下角联系站长解决