1024programmer Java Use Python’s Django framework to create an RSS reader

Use Python’s Django framework to create an RSS reader

Django brings an advanced syndication generation framework that makes creating RSS and Atom feeds very easy.

What is RSS? What is an Atom?

RSS and Atom are both XML-based formats that you can use to provide an automatically updating feed of your site’s content. To learn more about RSS, visit http://www.whatisrss.com/, and for more information about Atom, visit http://www.atomenabled.org/.

To create a syndication feed, all you need to do is write a short python class. You can create as many feeds as you want.

The advanced feed generation framework is a view bound to /feeds/ by default. Django uses the remainder of the URL (everything after /feeds/) to decide which feed to output. /feeds/ ) to determine which feed to return.

To create a sitemap, you simply write a Sitemap class and configure your URLconf to point to it.
Initialization

To enable syndication feeds in your Django site, add the following URLconf:

 (r'^feeds/(?P.*)/$', 'django.contrib.syndication.views.feed',
   {'feed_dict': feeds}
 ),

 

This line tells Django to use the RSS framework to process all URLs starting with “feeds/”. (You can modify the “feeds/” prefix to meet your own requirements.)

There is a line of parameters in URLConf: {‘feed_dict’: feeds}. This parameter can pass the feed content that the corresponding URL needs to publish to the syndication framework

Specifically, feed_dict should be a dictionary mapping the feed’s slug (short URL tag) to its Feed class. You can define the feed_dict in the URL configuration itself. Here is a complete example. You can define the feed_dict in the URLconf itself. Here’s a full example URLconf:

 from django.conf.urls.defaults import *
 from mysite.feeds import LatestEntries, LatestEntriesByCategory

 feeds = {
   'latest': LatestEntries,
   'categories': LatestEntriesByCategory,
 }

 urlpatterns = patterns('',
   #...
   (r'^feeds/(?P.*)/$', 'django.contrib.syndication.views.feed',
     {'feed_dict': feeds}),
   #...
 )

 

The previous example registered two feeds:

  1. The content represented by LatestEntries“ will correspond to “feeds/latest/.
  2. The content of LatestEntriesByCategory“ will correspond to “feeds/categories/.

After the above settings are completed, you need to define the Feed class yourself

A Feed class is a simple Python class used to represent a syndication feed. A feed may be simple (such as a site news feed, or most basic, showing the latest entries of a blog), or it may be more complex (For example, a feed that displays all entries in a certain category of a blog. Here category is a variable).

Feed classes must extend django.contrib.syndication.feeds.Feed, they can be anywhere in your code tree
A simple feed

 This simple example describes a feed of the latest five blog entries for a given blog:

 from django.contrib.syndication.feeds import Feed
 from mysite.blog.models import Entry

 class LatestEntries(Feed):
   title = "My Blog"
   link = "/archive/"
   description = "The latest news about stuff."

   def items(self):
     return Entry.objects.order_by('-pub_date')[:5]

 

Important things to note are as follows:

  • Subclass django.contrib.syndication.feeds.Feed .
  • title , link , and description correspond to the , , and tags in a standard RSS.
  • items() is a method that returns a list for inclusion in the element contained in the feed. Although the example uses the NewsItem object returned by the Djangos database API, items() does not necessarily have to return an instance of the model. Although this example returns Entry objects using Django’s database API, items() doesn’t have to return model instances.

There is another step. In an RSS feed, each (item) has a (title), (link) and (description). We need to tell the framework to put the data into these elements. In an RSS feed, each has a , , and . We need to tell the framework what data to put into those elements.

If you want to specify and , you can create a Django template (see Chapter 4) named feeds/latest_title.html and feeds/latest_description.html , the latter is the slug specified in URLConf for the corresponding feed. Note that the .html suffix is ​​required. Note that the .html extension is required.

To render each item in the RSS system template, you need to pass 2 parameters to the template context variable:

  1. obj: the current object (one of any objects returned by items()).
  2. site : A django.models.core.sites.Site object representing the current site. This is useful for {{ site.domain }} or {{ site.name }}.

If you do not specify a title or description when creating a template, the framework will default to “{{ obj }}”, the character string of the object.String representation. (For model objects, this will be the __unicode__() method.

You can also change the names of these two templates by modifying the two attributes title_template and description_template in the Feed class.

You have two ways to specify the content of . Django first executes the get_absolute_url() method of each item in items(). If this method does not exist, it will try to execute the item_link() method in the Feed class and pass itself in as the item parameter.

Both get_absolute_url() and item_link() should return the URL as a Python string.

For the LatestEntries example mentioned earlier, we can implement a simple feed template. latest_title.html includes:

{{ obj.title }}

and latest_description.html contains:

{{ obj.description }}

It’s so easy!

A more complex feed

The framework supports more complex feeds via parameters.

For example, say your blog offers an RSS feed for every distinct tag you’ve used to categorize your entries. It would be unwise to create a feed class for each separate region.

Instead, use an aggregation framework to generate a generic feed that returns information based on the feeds URL.

Your tag-specific feeds could use URLs like this:

http://example.com/feeds/tags/python/ : Returns recent entries tagged with python

http://example.com/feeds/tags/cats/ : Returns recent entries tagged with cats

The fixed part is the “beats” (area).

An example will clarify everything. Here are the feeds specific to each region:

 from django.core.exceptions import ObjectDoesNotExist
 from mysite.blog.models import Entry, Tag

 class TagFeed(Feed):
   def get_object(self, bits):
     # In case of "/feeds/tags/cats/dogs/mice/", or other such
     # clutter, check that bits has only one member.
     if len(bits) != 1:
       raise ObjectDoesNotExist
     return Tag.objects.get(tag=bits[0])

   def title(self, obj):
     return "My Blog: Entries tagged with %s" % obj.tag

   def link(self, obj):
     return obj.get_absolute_url()

   def description(self, obj):
     return "Entries tagged with %s" % obj.tag

   def items(self, obj):
     entries = Entry.objects.filter(tags__id__exact=obj.id)
     return entries.order_by('-pub_date')[:30]

 

The following is the basic algorithm of the RSS framework. We assume that this class is accessed through the URL /rss/beats/0613/:

The framework gets the URL /rss/beats/0613/ and notices that there is more information after the slug part of the URL. It uses a slash (“/”) as a delimiter, splits the remaining string as a parameter, and calls the get_object() method of the Feed class.

In this example, the added information is [‘0613’] . For a URL request to /rss/beats/0613/foo/bar/, the information is [‘0613’, ‘foo’, ‘bar’] .

get_object() returns the area information based on the given bits value.

In this case, it uses the Django database API to retrieve the Tag. Note that get_object() should raise django.core.exceptions.ObjectDoesNotExist if given invalid parameters. It also does not appear in the Beat.objects.get() call try /except code block. The function throws the Beat.DoesNotExist exception on error, and Beat.DoesNotExist is a subtype of the ObjectDoesNotExist exception.

To generate , , and feeds, Django uses the title() , link() , and description() methods. In the above example, they are all simple class attributes of type string, but this example shows that they can be either strings or methods. For each combination of title , link and description , Django uses the following algorithm:

Attempts to call a function with the object returned by get_object() passed as the obj parameter.

If not successful, a method is called with no parameters.

If that doesn’t work, use class attributes.

Finally, it’s worth noting that items() in this example uses the obj parameter. The algorithm for items is as described in the first step above, first trying items(obj) , then items() , and finally the items class attribute (must be a list).

For complete documentation of all methods and properties of the Feed class, please refer to the official Django documentation (http://www.djangoproject.com/documentation/0.96/syndication_feeds/).
Specify the type of feed

By default, the aggregation framework generates RSS 2.0. To change that, add a feed_type attribute to your Feed class:

 from django.utils.feedgenerator import Atom1Feed

 class MyFeed(Feed):
   feed_type = Atom1Feed

 

Note that you assign feed_type to a class object, not a class instance. The currently legal feed types are as shown in the table.

2015722150842180.jpg (705×179)

Closure

To specify closures (e.g., media resource information associated with feed items such as MP3 feeds), use item_enclosure_url , item_enclosure_length , and item_enclosure_mime_type , as in

 from myproject.models import Song

 class MyFeedWithEnclosures(Feed):
   title = "Example feed with enclosures"
   link = "/feeds/example-with-enclosures/"

   def items(self):
     return Song.objects.all()[:30]

   def item_enclosure_url(self, item):
     return item.song_url

   def item_enclosure_length(self, item):
     return item.song_length

   item_enclosure_mime_type = "audio/mpeg"

 

Of course, you first need to create a Song object containing the fields song_url and song_length (i.e. length in bytes).
Language

The feed automatically created by the aggregation framework contains the appropriate tag (RSS 2.0) or xml:lang attribute (Atom). This comes directly from your LANGUAGE_CODE setting.
URLs

The link method/property can return an absolute URL (e.g., “/blog/” ) or a URL specifying a protocol and domain name (e.g., “http://www.example.com/blog/” ). If link does not return a domain name, the aggregation framework will automatically insert the domain information of the current site according to the SITE_ID setting. (See Chapter 16 for more on SITE_ID and the sites framework.)

Atom feeds require specifying the current location of the feeds. The syndication framework populates this automatically.
Publish Atom and RSS simultaneously

Some developers want to support both Atom and RSS. This is easy to do in Django: just create a subclass of your feed class, then modify the feed_type and update the URLconf content. Here’s a full example:

 from django.contrib.syndication.feeds import Feed
 from django.utils.feedgenerator import Atom1Feed
 from mysite.blog.models import Entry

 class RssLatestEntries(Feed):
   title = "My Blog"
   link = "/archive/"
   description = "The latest news about stuff."

   def items(self):
     return Entry.objects.order_by('-pub_date')[:5]

 class AtomLatestEntries(RssLatestEntries):
   feed_type = Atom1Feed

 

This is the corresponding URLconf:

 from django.conf.urls.defaults import *
 from myproject.feeds import RssLatestEntries, AtomLatestEntries

 feeds = {
   'rss': RssLatestEntries,
   'atom': AtomLatestEntries,
 }

 urlpatterns = patterns('',
   #...
   (r'^feeds/(?P.*)/$', 'django.contrib.syndication.views.feed',
     {'feed_dict': feeds}),
   #...
 )

 

1562215857″ />

Closure

To specify closures (e.g., media resource information associated with feed items such as MP3 feeds), use item_enclosure_url , item_enclosure_length , and item_enclosure_mime_type , as in

 from myproject.models import Song

 class MyFeedWithEnclosures(Feed):
   title = "Example feed with enclosures"
   link = "/feeds/example-with-enclosures/"

   def items(self):
     return Song.objects.all()[:30]

   def item_enclosure_url(self, item):
     return item.song_url

   def item_enclosure_length(self, item):
     return item.song_length

   item_enclosure_mime_type = "audio/mpeg"

 

Of course, you first need to create a Song object containing the fields song_url and song_length (i.e. length in bytes).
Language

The feed automatically created by the aggregation framework contains the appropriate tag (RSS 2.0) or xml:lang attribute (Atom). This comes directly from your LANGUAGE_CODE setting.
URLs

The link method/property can return an absolute URL (e.g., “/blog/” ) or a URL specifying a protocol and domain name (e.g., “http://www.example.com/blog/” ). If link does not return a domain name, the aggregation framework will automatically insert the domain information of the current site according to the SITE_ID setting. (See Chapter 16 for more on SITE_ID and the sites framework.)

Atom feeds require specifying the current location of the feeds. The syndication framework populates this automatically.
Publish Atom and RSS simultaneously

Some developers want to support both Atom and RSS. This is easy to do in Django: just create a subclass of your feed class, then modify the feed_type and update the URLconf content. Here’s a full example:

 from django.contrib.syndication.feeds import Feed
 from django.utils.feedgenerator import Atom1Feed
 from mysite.blog.models import Entry

 class RssLatestEntries(Feed):
   title = "My Blog"
   link = "/archive/"
   description = "The latest news about stuff."

   def items(self):
     return Entry.objects.order_by('-pub_date')[:5]

 class AtomLatestEntries(RssLatestEntries):
   feed_type = Atom1Feed

 

This is the corresponding URLconf:

 from django.conf.urls.defaults import *
 from myproject.feeds import RssLatestEntries, AtomLatestEntries

 feeds = {
   'rss': RssLatestEntries,
   'atom': AtomLatestEntries,
 }

 urlpatterns = patterns('',
   #...
   (r'^feeds/(?P.*)/$', 'django.contrib.syndication.views.feed',
     {'feed_dict': feeds}),
   #...
 )

 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/787622

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索