fix(backend): small edits or new features

- manage CORS
- return feed as XML/RSS or Json
This commit is contained in:
Ewen 2024-05-12 11:29:57 +02:00
parent 3e3879e48e
commit c8370a5418
5 changed files with 47 additions and 6 deletions

View file

@ -1,6 +1,7 @@
import os
from flask import Flask
from flask_cors import CORS
def create_app(test_config=None):
@ -29,4 +30,6 @@ def create_app(test_config=None):
app.register_blueprint(feed.bp)
CORS(app)
return app

View file

@ -2,7 +2,6 @@ from datetime import datetime
import validators
from flask import Blueprint, jsonify, make_response, render_template, request
from werkzeug.exceptions import HTTPException
from api.db import get_db
@ -54,7 +53,13 @@ def parse_page():
raise InvalidParameters("Incorrect URL")
feed = scrape(args)
rss_xml = render_template("rss.xml", feed=feed, build_date=datetime.now())
response = make_response(rss_xml)
response.headers["Content-Type"] = "application/rss+xml"
return response
if args.get("format") and args.get("format") == 'json':
response = make_response(feed.to_json())
response.headers["Content-Type"] = "application/json"
return response
else:
rss_xml = render_template("rss.xml", feed=feed, build_date=datetime.now())
response = make_response(rss_xml)
response.headers["Content-Type"] = "application/rss+xml"
return response

View file

@ -1,4 +1,5 @@
from datetime import datetime
import json
import botasaurus as bt
import dateparser
@ -23,12 +24,29 @@ class FeedItem:
else:
return self.title < other.title
def to_json(self):
return json.dumps(
self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=4
)
class Feed:
def __init__(self, title, url, items):
self.title = title
self.url = url
self.items = items
def to_json(self):
return json.dumps(
self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=4
)
@bt.request(output=None)

16
api/poetry.lock generated
View file

@ -423,6 +423,20 @@ Werkzeug = ">=3.0.0"
async = ["asgiref (>=3.2)"]
dotenv = ["python-dotenv"]
[[package]]
name = "flask-cors"
version = "4.0.1"
description = "A Flask extension adding a decorator for CORS support"
optional = false
python-versions = "*"
files = [
{file = "Flask_Cors-4.0.1-py2.py3-none-any.whl", hash = "sha256:f2a704e4458665580c074b714c4627dd5a306b333deb9074d0b1794dfa2fb677"},
{file = "flask_cors-4.0.1.tar.gz", hash = "sha256:eeb69b342142fdbf4766ad99357a7f3876a2ceb77689dc10ff912aac06c389e4"},
]
[package.dependencies]
Flask = ">=0.9"
[[package]]
name = "flask-sqlalchemy"
version = "3.1.1"
@ -1194,4 +1208,4 @@ h11 = ">=0.9.0,<1"
[metadata]
lock-version = "2.0"
python-versions = "^3.11"
content-hash = "d0e30c9d7e8186fec20b1716f1a47e7e759e26cd68c5af13bd1ef4b9259426dd"
content-hash = "5daa79623cbf7897be36e0f03161d313b789b393341f1848daaf2c1d0013aed8"

View file

@ -16,6 +16,7 @@ requests = "^2.31.0"
botasaurus = "^4.0.14"
dateparser = "^1.2.0"
validators = "^0.28.1"
flask-cors = "^4.0.1"
[build-system]