Use Python's Django framework to create an RSS reader

Source: Internet
Author: User
Tags return tag
Django brings an advanced aggregation build framework that makes it easy to create RSS and Atom feeds.

What is RSS? What is Atom?

RSS and Atom are XML-based formats that you can use to provide a feed that automatically updates your site's content. To learn more about RSS, you can access http://www.whatisrss.com/, and more atom information can be accessed by http://www.atomenabled.org/.

To create a syndication feed (syndication feeds), all you need to do is write a short Python class. You can create as many feeds as you choose.

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

To create a sitemap, you just need to write a sitemap class and then configure your urlconf to point to it.
Initialization

In order to activate 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 that start with "feeds/". (You can modify the "feeds/" prefix to meet your own requirements.)

There is a row in urlconf: {' feed_dict ': feeds}, this parameter can pass the feed content that the corresponding URL needs to publish to the syndication framework

In particular, feed_dict should be a mapping feed slug (short URL tag) to its feed class dictionary you can define feed_dict in the URL configuration itself, here is a complete example of 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, latestentriesbycategoryfeeds = {  ' 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 indicated by Latestentries ' will correspond to ' feeds/latest/.
    2. The contents of Latestentriesbycategory ' will correspond to ' feeds/categories/.

After the above settings are complete, you need to define your own Feed class

A feed class is a simple Python class that is used to represent a syndication feed. A feed may be simple (such as a site news feed, or most basic, the latest entry for a blog), or it may be more complex (for example, a feed that shows all the entries under a category in a blog). This category is a variable).

The Feed class must inherit Django.contrib.syndication.feeds.Feed, which can be anywhere in your code tree
A simple feed

This simple example describes a feeds the latest five blog entries for a given blog:from django.contrib.syndication.feed S import feedfrom mysite.blog.models import Entryclass latestentries (Feed):  title = "My Blog"  link = "/archive/" C3/>description = "The latest news about stuff."  def items (self):    return Entry.objects.order_by ('-pub_date ') [: 5]

The important things to note are as follows:

    • Sub-class Django.contrib.syndication.feeds.Feed.
    • Title, link, and description correspond to a standard RSS, , and tags.
    • Items () is a method that returns a list containing the elements contained in the feed , although the NewsItem object returned by the Djangos database API in the example, items () must not necessarily return an instance of model Although this example returns Entry objects using Django's database API, items () doesn ' t has to return model instances.

There is one more step, in one RSS feed, each with one (title), (link) and (description), we need to tell the framework to put the data into these elements in an RSS feed, with a , , and . We need to the framework "what data" put into those elements.

If you want to specifyAnd , you can create a Django template (see Chapter 4) named Feeds/latest_title.html and Feeds/latest_description.html, which is the slug specified for the corresponding feed in urlconf. Note. The HTML suffix is required. Note the. html extension is required.

The RSS system template renders each entry and needs to pass 2 parameters to the template context variable:

    1. Obj: The current object (returned to one of the items () objects).
    2. Site: A Django.models.core.sites.Site object that represents the current site. This is useful for {{Site.domain}} or {{site.name}}.

If you do not specify a title or description when you create the template, the framework defaults to "{{obj}}" and the object's string representation. (For model objects, this would be the __unicode__ () method.)

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

You have two ways to specify the content. Django first executes the Get_absolute_url () method for each item in the items (). If the method does not exist, it attempts to execute the Item_link () method in the Feed class and passes itself in as the item parameter.

Both Get_absolute_url () and Item_link () should return URLs as Python strings.

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 through parameters.

For example, say your blog offers a RSS feed for every distinct tags you ' ve used to categorize your entries. It would be unwise to create a Feed class for each individual area.

Instead, use the aggregation framework to produce a common source that can return the appropriate 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 "Beats" (area).

Give an example to clarify everything. Here are the specific feeds for each region:

From django.core.exceptions import objectdoesnotexistfrom mysite.blog.models import Entry, Tagclass tagfeed (Feed):  def get_object (self, bits):    # in case of '/feeds/tags/cats/dogs/mice/', or other such    # clutter, check that B Its have 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 ()  D EF 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 for the RSS framework, and we assume that this class is accessed through url/rss/beats/0613/:

The framework obtains the URL/RSS/BEATS/0613/and notes that the slug section of the URL contains more information later. It takes a slash ("/") as a delimiter, divides the remaining string into arguments, and invokes the Get_object () method of the Feed class.

In this example, the added information is [' 0613 ']. For a URL request for/rss/beats/0613/foo/bar/, this information is [' 0613 ', ' foo ', ' Bar '].

Get_object () returns the region 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. No try/except code block appears in the Beat.objects.get () call. The function throws an Beat.doesnotexist exception on an error, and Beat.doesnotexist is a subtype of the objectdoesnotexist exception.

to produce, , and feeds, Django uses the title (), Link (), and Description () methods. In the example above, they are all simple string-type class properties, and this example shows that they can be either a string or a method. For each title, link, and description combination, Django uses the following algorithm:

An attempt was made to invoke a function, and the object returned as Get_object () is passed as a parameter to the obj parameter.

If it is not successful, a method is called without arguments.

is not successful, the Class property is used.

Finally, it is worth noting that the items () in this example use the obj parameter. For the items algorithm, as described in the first step above, you first try items (obj), then items (), and finally the Items Class property (which must be a list).

For full documentation of all methods and properties of the Feed class, refer to the official Django document (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 the situation, add a Feed_type attribute to the Feed class. To change this, add a Feed_type attribute to your feed class:

From Django.utils.feedgenerator import Atom1feedclass myfeed (Feed):  feed_type = atom1feed

Note that you assign a feed_type to a class object, not to an instance of the class. The current legal feed type is shown in the table.

Closed Package

To specify closures (for example, media resource information associated with a feed item such as MP3 feeds), use Item_enclosure_url, Item_enclosure_length, and Item_enclosure_mime_type, Like what

From myproject.models import songclass myfeedwithenclosures (Feed):  title = "Example Feeds with enclosures"  link = "/feeds/example-with-enclosures/"  def items (self):    return Song.objects.all () [:]  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 create a Song object that contains fields with Song_url and song_length (such as the length computed in bytes).
Language

The aggregation framework automatically creates a feed that contains the appropriate label (RSS 2.0) or Xml:lang attribute (Atom). He comes directly from your language_code settings. This comes directly from your language_code setting.
URLs

The link method/property can be returned in the form of an absolute URL (for example, "/blog/") or as a URL for a specified protocol and domain name (for example, "http://www.example.com/blog/"). If link does not return a domain name, the aggregation framework automatically inserts the domain information for the current site according to the site_id setting. (see Chapter, site_id and the Sites framework.)

Atom feeds needs to indicate where feeds is now. The syndication framework populates this automatically.
Release Atom and RSS at the same time

Some developers want to support both Atom and RSS. This is easy to implement in Django: just create a subclass of your feed class, modify the Feed_type, and update the urlconf content. Here's a complete example: Here's a full example:

From django.contrib.syndication.feeds import feedfrom django.utils.feedgenerator import Atom1feedfrom Mysite.blog.models Import Entryclass 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 urlconf that corresponds to it:

From django.conf.urls.defaults import *from myproject.feeds import rsslatestentries, atomlatestentriesfeeds = {  ' RSS ': rsslatestentries,  ' atom ': Atomlatestentries,}urlpatterns = Patterns (',  # ...  (R ' ^feeds/(? P
 
  
   
  . *)/$ ', ' django.contrib.syndication.views.feed ',    {' feed_dict ': Feeds}),  # ...)
 
  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.