1
0
mirror of https://github.com/aquatix/digimarks.git synced 2025-12-06 22:05:09 +01:00

Formatting fixes

This commit is contained in:
2025-04-29 21:18:19 +02:00
parent e4d303a72b
commit d89e8be72e

View File

@@ -12,7 +12,6 @@ from urllib.parse import urljoin, urlparse, urlunparse
import bs4 import bs4
import httpx import httpx
from dateutil import tz from dateutil import tz
from fastapi import FastAPI, HTTPException, Request, Response from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import HTMLResponse, RedirectResponse
@@ -20,7 +19,6 @@ from fastapi.templating import Jinja2Templates
from feedgen.feed import FeedGenerator from feedgen.feed import FeedGenerator
from pydantic import DirectoryPath, FilePath from pydantic import DirectoryPath, FilePath
from pydantic_settings import BaseSettings from pydantic_settings import BaseSettings
from requests.exceptions import MissingSchema
from sqlalchemy import VARCHAR, Boolean, Column, DateTime, Integer, Text, create_engine from sqlalchemy import VARCHAR, Boolean, Column, DateTime, Integer, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Mapped, sessionmaker from sqlalchemy.orm import Mapped, sessionmaker
@@ -53,13 +51,15 @@ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() Base = declarative_base()
@asynccontextmanager @asynccontextmanager
async def lifespan(the_app: FastAPI): async def lifespan(the_app: FastAPI):
"""Upon start, initialise an AsyncClient and assign it to an attribute named requests_client on the app object""" """Upon start, initialise an AsyncClient and assign it to an attribute named requests_client on the app object."""
the_app.requests_client = httpx.AsyncClient() the_app.requests_client = httpx.AsyncClient()
yield yield
await the_app.requests_client.aclose() await the_app.requests_client.aclose()
app = FastAPI(lifespan=lifespan) app = FastAPI(lifespan=lifespan)
templates = Jinja2Templates(directory='templates') templates = Jinja2Templates(directory='templates')
@@ -112,9 +112,9 @@ def unique_ever_seen(iterable, key=None):
def clean_tags(tags_list): def clean_tags(tags_list):
"""Generate unique list of the tags. """Generate a unique list of the tags.
:param list tags_list: list with all tags :param list tags_list: List with all tags
:return: deduplicated list of the tags, without leading or trailing whitespace :return: deduplicated list of the tags, without leading or trailing whitespace
:rtype: list :rtype: list
""" """
@@ -235,7 +235,9 @@ class Bookmark(Base):
def set_status_code(self, request: Request) -> int: def set_status_code(self, request: Request) -> int:
"""Check the HTTP status of the url, as it might not exist for example.""" """Check the HTTP status of the url, as it might not exist for example."""
try: try:
result = request.app.requests_client.head(self.url, headers={'User-Agent': DIGIMARKS_USER_AGENT}, timeout=30) result = request.app.requests_client.head(
self.url, headers={'User-Agent': DIGIMARKS_USER_AGENT}, timeout=30
)
self.http_status = result.status_code self.http_status = result.status_code
except httpx.HTTPError as err: except httpx.HTTPError as err:
logger.error('Failed to do head info fetching for %s: %s', self.url, str(err)) logger.error('Failed to do head info fetching for %s: %s', self.url, str(err))
@@ -434,9 +436,9 @@ def _find_bookmarks(user_key: str, filter_text) -> list[Bookmark]:
.where( .where(
Bookmark.userkey == user_key, Bookmark.userkey == user_key,
( (
Bookmark.title.contains(filter_text) Bookmark.title.contains(filter_text)
| Bookmark.url.contains(filter_text) | Bookmark.url.contains(filter_text)
| Bookmark.note.contains(filter_text) | Bookmark.note.contains(filter_text)
), ),
Bookmark.status == Bookmark.VISIBLE, Bookmark.status == Bookmark.VISIBLE,
) )
@@ -513,7 +515,7 @@ def get_bookmarks(request: Request, user_key, filter_method=None, sort_method=No
.order_by(Bookmark.created_date.desc()) .order_by(Bookmark.created_date.desc())
) )
return bookmarks, bookmark_tags, filter_text #, message return bookmarks, bookmark_tags, filter_text # , message
@app.get('/{user_key}', response_class=HTMLResponse) @app.get('/{user_key}', response_class=HTMLResponse)
@@ -659,7 +661,7 @@ def add_bookmark(request: Request, user_key: str):
) )
def update_bookmark(request: Request, user_key: str, url_hash: str=None): def update_bookmark(request: Request, user_key: str, url_hash: str = None):
"""Add (no urlhash) or edit (urlhash is set) a bookmark.""" """Add (no urlhash) or edit (urlhash is set) a bookmark."""
title = request.form.get('title') title = request.form.get('title')
url = request.form.get('url') url = request.form.get('url')
@@ -988,7 +990,7 @@ def add_user(system_key):
new_user.save() new_user.save()
all_tags[new_user.key] = [] all_tags[new_user.key] = []
return {'user': f'/{new_user.key.decode("utf-8")}'} return {'user': f'/{new_user.key.decode("utf-8")}'}
raise HTTPException(status_code=404, detail='I can\'t let you do that Dave') raise HTTPException(status_code=404, detail="I can't let you do that Dave")
@app.route('/<system_key>/refreshfavicons') @app.route('/<system_key>/refreshfavicons')
@@ -1005,7 +1007,7 @@ def refresh_favicons(system_key):
print(e) print(e)
bookmark.set_favicon() bookmark.set_favicon()
return {'message': 'Done refreshing icons'} return {'message': 'Done refreshing icons'}
raise HTTPException(status_code=404, detail='I can\'t let you do that Dave') raise HTTPException(status_code=404, detail="I can't let you do that Dave")
@app.route('/<system_key>/findmissingfavicons') @app.route('/<system_key>/findmissingfavicons')
@@ -1016,7 +1018,7 @@ def find_missing_favicons(request: Request, system_key: str):
for bookmark in bookmarks: for bookmark in bookmarks:
try: try:
if not bookmark.favicon or not os.path.isfile( if not bookmark.favicon or not os.path.isfile(
os.path.join(settings.media_dir, 'favicons', bookmark.favicon) os.path.join(settings.media_dir, 'favicons', bookmark.favicon)
): ):
# This favicon is missing # This favicon is missing
# Clear favicon, so fallback can be used instead of showing a broken image # Clear favicon, so fallback can be used instead of showing a broken image
@@ -1028,7 +1030,8 @@ def find_missing_favicons(request: Request, system_key: str):
except OSError as e: except OSError as e:
print(e) print(e)
return {'message': 'Done finding missing icons'} return {'message': 'Done finding missing icons'}
raise HTTPException(status_code=404, detail='I can\'t let you do that Dave') raise HTTPException(status_code=404, detail="I can't let you do that Dave")
# Initialisation == create the bookmark, user and public tag tables if they do not exist # Initialisation == create the bookmark, user and public tag tables if they do not exist
# TODO: switch to alembic migrations # TODO: switch to alembic migrations