提示:本文章包括但不限于注释、代码、摘要等内容均由Newbing及Chatgpt提供,准确性不能完全保证
Python
本段代码实现了一个基于Flask框架的RSS订阅源转化为API,通过接口提供订阅源中指定数量的条目的标题、链接、发布时间和图片链接等信息,同时提供了下载指定条目中的图片和跳转至指定条目链接的功能。以下是代码解析及相关思路。
第一部分,导入所需库,其中requests库用于发送HTTP请求,Flask库用于构建Web应用,feedparser库用于解析RSS订阅源。
第二部分,创建Flask应用程序实例,定义RSS订阅源URL和最大RSS条目数量,并创建了一个RSS条目类和RSS订阅源类。RSS条目类的构造函数用于初始化RSS条目的各个属性,将条目对象转换为字典。RSS订阅源类的构造函数用于解析RSS订阅源并初始化其中的条目列表,将订阅源对象转换为列表字典。
第三部分,处理路由请求。'/config=<reload>'路由处理在订阅源发生变化时重新创建RSS订阅源对象;'/gettur'路由处理返回经过处理的RSS订阅源信息;'/getimg&config=<config>'路由处理提供下载指定序号条目中的图片;'/jumpurl&config=<config>'路由处理提供跳转至指定序号条目链接的功能。其中,'/gettur'和'/getimg&config=<config>'路由将RSS源转化为字典类型,并生成返回的JSON对象。
第四部分,允许跨域请求并返回响应对象。
代码的主要功能是将RSS订阅源转换为API,实现了提供订阅源中指定数量的条目的标题、链接、发布时间和图片链接等信息,同时提供了下载指定条目中的图片和跳转至指定条目链接的功能。其中,通过Flask框架搭建Web应用程序,监听HTTP请求并返回对应响应。整个应用程序的功能,依靠对已有库的调用以及类的定义实现。需要说明的是,本代码还存在一些潜在的问题,如未对请求进行异常处理、缓存清理等,需要进一步完善。
源代码:
import requests # 引入 requests 库,用于发送 HTTP 请求
from flask import Flask, make_response, send_file, redirect # 引入 Flask 框架及其相关模块
import feedparser # 引入 feedparser 库,用于解析 RSS 订阅源
app = Flask(__name__) # 创建 Flask 应用程序实例
rss_url = 'https://lowion.cn/?feed=rss2' # 定义 RSS 订阅源的 URL
MAX_ITEMS = 3 # 定义最大 RSS 条目数量
# 定义 RSS 条目类
class RSSItem:
# 构造函数,用于初始化 RSS 条目的各个属性
def __init__(self, entry):
self.title = entry.get('title', '') # 获取 RSS 条目的标题
self.link = entry.get('link', '') # 获取 RSS 条目的链接
self.pub_date = entry.get('published_parsed', '') # 获取 RSS 条目的发布时间
summary = entry.get('summary', '') # 获取 RSS 条目的摘要
# 获取 RSS 条目的图片 URL,如果摘要中包含图片,则从中提取出来;否则将图片 URL 设为空字符串
self.image_url = summary.split('<img')[1].split('/>')[0].split('src=')[1].split(' ')[0].replace('"','') if '<img' in summary else ''
# 将 RSS 条目对象转换为字典
def to_dict(self):
return {
'title': self.title,
'link': self.link,
'pub_date': self.pub_date,
'image_url': self.image_url
}
# 定义 RSS 订阅源类
class RSSFeed:
# 构造函数,用于解析 RSS 订阅源并初始化其中的条目列表
def __init__(self, url, max_items):
self.feed = feedparser.parse(url) # 解析 RSS 订阅源
self.items = [RSSItem(e) for e in self.feed.entries[:max_items]] # 初始化 RSS 条目列表
# 将 RSS 订阅源对象转换为列表字典
def to_dict(self):
return [i.to_dict() for i in self.items]
feed = RSSFeed(rss_url, MAX_ITEMS) # 创建 RSS 订阅源对象
# 处理 /config=<reload> 路由的请求
@app.route('/config=<reload>')
def reload(reload):
feed = RSSFeed(rss_url, MAX_ITEMS) # 重新创建 RSS 订阅源对象
backjson = {'statuscode':200,'get':reload} # 返回的 JSON 数据
fresponse = make_response(backjson) # 创建响应对象
fresponse.headers['Access-Control-Allow-Origin'] = '*' # 允许跨域请求
return fresponse
# 路由定义,当请求地址为 '/gettur' 时,执行 'main' 函数
@app.route('/gettur')
def main():
# 将 RSS 源转化为字典类型
items_dict = feed.to_dict()
# 生成返回的 JSON 对象,包括状态码、图片、标题、链接、时间等信息
backjson = {
'statuscode':200,
**{f'img{i+1}': items_dict[i]['image_url'] for i in range(MAX_ITEMS)},
**{f'title{i+1}': items_dict[i]['title'] for i in range(MAX_ITEMS)},
**{f'link{i+1}': items_dict[i]['link'] for i in range(MAX_ITEMS)},
**{f'exp{i+1}': str(items_dict[i]['pub_date'][0])+'-'+str(items_dict[i]['pub_date'][1])+'-'+str(items_dict[i]['pub_date'][2]) for i in range(MAX_ITEMS)}
}
# 生成响应对象
fresponse = make_response(backjson)
# 允许跨域访问
fresponse.headers['Access-Control-Allow-Origin'] = '*'
# 返回响应对象
return fresponse
# 路由定义,当请求地址为 '/getimg&config=<config>' 时,执行 'getimg' 函数
@app.route('/getimg&config=<config>')
def getimg(config:str):
# 将 RSS 源转化为字典类型
items_dict = feed.to_dict()
# 获取指定序号的图片链接
image_url = items_dict[int(config) - 1]['image_url']
# 如果有图片链接,则下载图片并返回给客户端
if image_url:
with open('./tmp.png','wb') as f:
f.write(requests.get(image_url).content)
return send_file('./tmp.png')
# 如果没有图片链接,则返回一个状态码为 404 的错误信息
return make_response({'statuscode': 404, 'message': 'Not found'})
# 路由定义,当请求地址为 '/jumpurl&config=<config>' 时,执行 'jumpurl' 函数
@app.route('/jumpurl&config=<config>')
def jumpurl(config:str):
# 将 RSS 源转化为字典类型
items_dict = feed.to_dict()
# 获取指定序号的文章链接
link = items_dict[int(config) - 1]['link']
# 如果有文章链接,则进行跳转
if link:
return redirect(link, 301)
# 如果没有文章链接,则返回一个状态码为 404 的错误信息
return make_response({'statuscode': 404, 'message': 'Not found'})
# 如果该脚本是直接运行的,那么执行以下代码
if __name__ == '__main__':
# 运行 Flask 应用,并监听 0.0.0.0:8662,开启 debug 模式
app.run(debug=True,port=8662,host='0.0.0.0')
我原本的代码如下:
import datetime
import time
import requests
from flask import Flask, make_response,send_file,redirect
import feedparser
link1=''
link2=''
link3=''
title1=''
title2=''
title3=''
imgurl1=''
imgurl2=''
imgurl3=''
exp1=''
exp2=''
exp3=''
class getrss():
def main(self):
self.get()
def get(self):
global link1
global link2
global link3
global title1
global title2
global title3
global imgurl1
global imgurl2
global imgurl3
global exp1
global exp2
global exp3
rss_oschina = feedparser.parse('https://lowion.cn/?feed=rss2')
link1=rss_oschina['entries'][0]['link']
link2=rss_oschina['entries'][1]['link']
link3=rss_oschina['entries'][2]['link']
title1=rss_oschina['entries'][0]['title']
title2=rss_oschina['entries'][1]['title']
title3=rss_oschina['entries'][2]['title']
imgurl1=str(rss_oschina['entries'][0]['summary']).split('<img')[1].split('/>')[0].split('src=')[1].split(' ')[0].replace('"','')
imgurl2=str(rss_oschina['entries'][1]['summary']).split('<img')[1].split('/>')[0].split('src=')[1].split(' ')[0].replace('"','')
imgurl3=str(rss_oschina['entries'][2]['summary']).split('<img')[1].split('/>')[0].split('src=')[1].split(' ')[0].replace('"','')
exp1=str(rss_oschina['entries'][0]['published_parsed']).split('(')[1].replace(')','').split(', ')[0].replace('tm_year=','')+'-'+str(rss_oschina['entries'][0]['published_parsed']).split('(')[1].replace(')','').split(', ')[1].replace('tm_mon=','')+'-'+str(rss_oschina['entries'][0]['published_parsed']).split('(')[1].replace(')','').split(', ')[2].replace('tm_mday=','')
exp2=str(rss_oschina['entries'][1]['published_parsed']).split('(')[1].replace(')','').split(', ')[0].replace('tm_year=','')+'-'+str(rss_oschina['entries'][1]['published_parsed']).split('(')[1].replace(')','').split(', ')[1].replace('tm_mon=','')+'-'+str(rss_oschina['entries'][1]['published_parsed']).split('(')[1].replace(')','').split(', ')[2].replace('tm_mday=','')
exp3=str(rss_oschina['entries'][2]['published_parsed']).split('(')[1].replace(')','').split(', ')[0].replace('tm_year=','')+'-'+str(rss_oschina['entries'][2]['published_parsed']).split('(')[1].replace(')','').split(', ')[1].replace('tm_mon=','')+'-'+str(rss_oschina['entries'][2]['published_parsed']).split('(')[1].replace(')','').split(', ')[2].replace('tm_mday=','')
print(link1)
print(link2)
print(link3)
print(title1)
print(title2)
print(title3)
print(imgurl1)
print(imgurl2)
print(imgurl3)
print(exp1)
print(exp2)
print(exp3)
app = Flask(__name__)
@app.route('/config=<reload>')
def reload(reload):
getrss.main(getrss())
backjson = {'statuscode':200,'get':reload}
fresponse = make_response(backjson) # 防止跨域报错
fresponse.headers['Access-Control-Allow-Origin'] = '*'
return fresponse
@app.route('/gettur')
def main():
if imgurl1=='':
reload('self')
backjson = {'statuscode':200,'img1':imgurl1,'img2':imgurl2,'img3':imgurl3,'exp1':exp1,'exp2':exp2,'exp3':exp3,'link1':link1,'link2':link2,'link3':link3,'title1':title1,'title2':title2,'title3':title3}
fresponse = make_response(backjson) # 防止跨域报错
fresponse.headers['Access-Control-Allow-Origin'] = '*'
return fresponse
@app.route('/getimg&config=<config>')
def getimg(config:str):
if imgurl1=='':
reload('self')
if config=='1':
with open('./tmp.png','wb') as f:
f.write(requests.get(imgurl1).content)
return send_file('./tmp.png')
if config=='2':
with open('./tmp.png','wb') as f:
f.write(requests.get(imgurl2).content)
return send_file('./tmp.png')
if config=='3':
with open('./tmp.png','wb') as f:
f.write(requests.get(imgurl3).content)
return send_file('./tmp.png')
@app.route('/jumpurl&config=<config>')
def jumpurl(config:str):
if imgurl1=='':
reload('self')
if config=='1':
return redirect(link1,301)
if config=='2':
return redirect(link2,301)
if config=='3':
return redirect(link3,301)
if __name__ == '__main__':
app.run(debug=True,port=8662,host='0.0.0.0')
Javascript
这段JavaScript代码是一个简单的倒计时,它使用XMLHttpRequest对象从一个URL获取JSON数据,并在每秒钟更新网页的UI。
该代码开始时定义了一个变量count并将其初始化为10。在函数refresh()中,如果count大于或等于0,则会创建一个XMLHttpRequest对象并将其发送到URL:https://tturl.cdn.lowion.cn/gettur。
如果请求成功(状态码为200),则将返回的JSON数据解析为JavaScript对象,并将其传递给updateUI()函数。updateUI()函数使用JavaScript中的querySelector()方法选择HTML元素,并将它们的innerHTML属性设置为相应的JSON数据字段的值。最后,该代码使用setInterval()函数在每秒钟调用一次refresh()函数,从而每秒钟更新一次UI。
需要注意的是,此代码仅作为演示,使用XMLHttpRequest对象不再是最佳实践,应该使用更现代的fetch API来进行网络请求。
var count = 10;
function refresh() {
if (count >= 0) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'https://tturl.cdn.lowion.cn/gettur', true);
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var json = httpRequest.responseText;
var objs = JSON.parse(json);
updateUI(objs);
}
}
} else {}
}
function updateUI(objs) {
document.querySelector("#showfirstexp").innerHTML = objs.exp1;
document.querySelector("#showsecexp").innerHTML = objs.exp2;
document.querySelector("#showthrexp").innerHTML = objs.exp3;
document.querySelector("#showfirst").innerHTML = objs.title1;
document.querySelector("#showsec").innerHTML = objs.title2;
document.querySelector("#showthr").innerHTML = objs.title3;
}
setInterval(refresh, 1000);
Comments NOTHING