Моя пользовательская команда django_admin получила ошибку AttributeError: объект не имеет атрибута 'title'

Я работаю над созданием RSS-канала на Django. Всякий раз, когда я пытаюсь запустить пользовательский командный файл (startjobs.py) в командной строке, появляется ошибка:

Job "fetch_talkpython_posts" raised an exception
Traceback (most recent call last):
File "C:\xxx\xxx\anaconda3\lib\site-packages\feedparser\util.py", line 156, in __getattr__ 
  return self.__getitem__(key)
File "C:\xxx\xxx\anaconda3\lib\site-packages\feedparser\util.py", line 113, in __getitem__ 
  return dict.__getitem__(self, key)
KeyError: 'title'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\xxx\xxx\anaconda3\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job
  retval = job.func(*job.args, **job.kwargs)
File "C:\xxx\xxx\django_project\pyagg\content_aggregator\news\management\commands\startjobs.py", line 39, in fetch_talkpython_posts 
  save_new_posts(_feed)
File "C:\xxx\xxx\django_project\pyagg\content_aggregator\news\management\commands\startjobs.py", line 18, in save_new_posts
  feed_title = feed.channel.title
File "C:\xxx\xxx\anaconda3\lib\site-packages\feedparser\util.py", line 158, in __getattr__ 
raise AttributeError("object has no attribute '%s'" % key)
AttributeError: object has no attribute 'title' 

Я не смог понять, почему возникла эта ошибка и что не так с fetch_talkpython_posts(). Любая помощь будет принята с благодарностью.

мой пользовательский командный файл startjobs.py:

import logging

from django.conf import settings
from django.core.management.base import BaseCommand

import feedparser
from dateutil import parser
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from django_apscheduler.jobstores import DjangoJobStore
from django_apscheduler.models import DjangoJobExecution

from news.models import Post

logger = logging.getLogger(__name__)

def save_new_posts(feed):
    feed_title = feed.channel.title
    feed_image = feed.channel.image["href"]

    for item in feed.entries:
        if not Post.objects.filter(link=item.link).exists():
            post = Post(
                title=item.title,
                description=item.description,
                pubdate=parser.parse(item.published),
                link=item.link,
                image=feed_image,
                #p_title=feed_title,
            )
            post.save()

def fetch_realpython_posts():
    _feed = feedparser.parse("https://realpython.com/podcasts/rpp/feed")
    save_new_posts(_feed)

def fetch_talkpython_posts():
    _feed = feedparser.parse("https://talkpython.fm/episodes/rss")
    save_new_posts(_feed)

def delete_old_job_executions(max_age=604_800):
    DjangoJobExecution.objects.delete_old_job_executions(max_age)

class Command(BaseCommand):
    help = "Runs apscheduler."
    def handle(self, *args, **options):
        scheduler = BlockingScheduler(timezone=settings.TIME_ZONE)
        scheduler.add_jobstore(DjangoJobStore(), "default")

        scheduler.add_job(
            fetch_realpython_posts,
            trigger="interval",
            minutes=2,
            id="The Real Python Podcast",
            max_instances=1,
            replace_existing=True,
        )
        logger.info("Added job: The Real Python Podcast.")

        scheduler.add_job(
            fetch_talkpython_posts,
            trigger="interval",
            minutes=2,
            id="Talk Python Feed",
            max_instances=1,
            replace_existing=True,
        )
        logger.info("Added job: Talk Python Feed.")

        scheduler.add_job(
            delete_old_job_executions,
            trigger=CronTrigger(
                day_of_week="mon", hour="00", minute="00"
            ),
            id="Delete Old Job Executions",
            max_instances=1,
            replace_existing=True,
        )
        logger.info("Added weekly job: Delete Old Job Executions.")

        try:
            logger.info("Starting scheduler...")
            scheduler.start()
        except KeyboardInterrupt:
            logger.info("Stopping scheduler...")
            scheduler.shutdown()

Есть идеи, как решить эту проблему? Спасибо

Я полагаю, что проблема в функции save_new_posts(), но я не уверен. Давайте отладим ее дальше. Работает ли функция fetch_realpython_posts()?

Вернуться на верх