Commit 9fede231 authored by Aaron1011's avatar Aaron1011
Browse files

Merge pull request #392 from tweepy/new_docs

Create new docs
parents 9f06a21b db3f6b2f
......@@ -12,119 +12,88 @@ PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
mkdir -p $(BUILDDIR)/html
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
mkdir -p $(BUILDDIR)/dirhtml
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
mkdir -p $(BUILDDIR)/pickle
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
mkdir -p $(BUILDDIR)/json
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
mkdir -p $(BUILDDIR)/htmlhelp
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
mkdir -p $(BUILDDIR)/qthelp
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Tweepy.qhcp"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/tweepy.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Tweepy.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Tweepy"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Tweepy"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/tweepy.qhc"
latex:
mkdir -p $(BUILDDIR)/latex
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
mkdir -p $(BUILDDIR)/changes
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
mkdir -p $(BUILDDIR)/linkcheck
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
mkdir -p $(BUILDDIR)/doctest
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
This diff is collapsed.
.. _auth_tutorial:
***********************
Authentication Tutorial
***********************
Introduction
============
Tweepy supports oauth authentication. Authentication is
handled by the tweepy.AuthHandler class.
OAuth Authentication
====================
Tweepy tries to make OAuth as painless as possible for you. To begin
the process we need to register our client application with
Twitter. Create a new application and once you
are done you should have your consumer token and secret. Keep these
two handy, you'll need them.
The next step is creating an OAuthHandler instance. Into this we pass
our consumer token and secret which was given to us in the previous
paragraph::
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
If you have a web application and are using a callback URL that needs
to be supplied dynamically you would pass it in like so::
auth = tweepy.OAuthHandler(consumer_token, consumer_secret,
callback_url)
If the callback URL will not be changing, it is best to just configure
it statically on twitter.com when setting up your application's
profile.
Unlike basic auth, we must do the OAuth "dance" before we can start
using the API. We must complete the following steps:
#. Get a request token from twitter
#. Redirect user to twitter.com to authorize our application
#. If using a callback, twitter will redirect the user to
us. Otherwise the user must manually supply us with the verifier
code.
#. Exchange the authorized request token for an access token.
So let's fetch our request token to begin the dance::
try:
redirect_url = auth.get_authorization_url()
except tweepy.TweepError:
print 'Error! Failed to get request token.'
This call requests the token from twitter and returns to us the
authorization URL where the user must be redirect to authorize us. Now
if this is a desktop application we can just hang onto our
OAuthHandler instance until the user returns back. In a web
application we will be using a callback request. So we must store the
request token in the session since we will need it inside the callback
URL request. Here is a pseudo example of storing the request token in
a session::
session.set('request_token', (auth.request_token.key,
auth.request_token.secret))
So now we can redirect the user to the URL returned to us earlier from
the get_authorization_url() method.
If this is a desktop application (or any application not using
callbacks) we must query the user for the "verifier code" that twitter
will supply them after they authorize us. Inside a web application
this verifier value will be supplied in the callback request from
twitter as a GET query parameter in the URL.
.. code-block :: python
# Example using callback (web app)
verifier = request.GET.get('oauth_verifier')
# Example w/o callback (desktop)
verifier = raw_input('Verifier:')
The final step is exchanging the request token for an access
token. The access token is the "key" for opening the Twitter API
treasure box. To fetch this token we do the following::
# Let's say this is a web app, so we need to re-build the auth handler
# first...
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
token = session.get('request_token')
session.delete('request_token')
auth.set_request_token(token[0], token[1])
try:
auth.get_access_token(verifier)
except tweepy.TweepError:
print 'Error! Failed to get access token.'
It is a good idea to save the access token for later use. You do not
need to re-fetch it each time. Twitter currently does not expire the
tokens, so the only time it would ever go invalid is if the user
revokes our application access. To store the access token depends on
your application. Basically you need to store 2 string values: key and
secret::
auth.access_token.key
auth.access_token.secret
You can throw these into a database, file, or where ever you store
your data. To re-build an OAuthHandler from this stored access token
you would do this::
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
So now that we have our OAuthHandler equipped with an access token, we
are ready for business::
api = tweepy.API(auth)
api.update_status('tweepy + oauth!')
.. _code_snippet:
*************
Code Snippets
*************
Introduction
============
Here are some code snippets to help you out with using Tweepy. Feel
free to contribute your own snippets or improve the ones here!
OAuth
=====
.. code-block :: python
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
# Redirect user to Twitter to authorize
redirect_user(auth.get_authorization_url())
# Get access token
auth.get_access_token("verifier_value")
# Construct the API instance
api = tweepy.API(auth)
Pagination
==========
.. code-block :: python
# Iterate through all of the authenticated user's friends
for friend in tweepy.Cursor(api.friends).items():
# Process the friend here
process_friend(friend)
# Iterate through the first 200 statuses in the friends timeline
for status in tweepy.Cursor(api.friends_timeline).items(200):
# Process the status here
process_status(status)
FollowAll
=========
This snippet will follow every follower of the authenticated user.
.. code-block :: python
for follower in tweepy.Cursor(api.followers).items():
follower.follow()
# -*- coding: utf-8 -*-
#
# Tweepy documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 15 18:57:17 2011.
# tweepy documentation build configuration file, created by
# sphinx-quickstart on Sun Dec 6 11:13:52 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
......@@ -16,32 +16,30 @@ import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.append(os.path.abspath('.'))
sys.path.append(os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
#templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Tweepy'
copyright = u'2011, Joshua Roesslein'
project = u'tweepy'
copyright = u'2009, Joshua Roesslein'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
......@@ -65,9 +63,12 @@ release = __version__
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
......@@ -92,8 +93,8 @@ pygments_style = 'sphinx'
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
......@@ -123,7 +124,7 @@ html_theme = 'default'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
......@@ -141,7 +142,7 @@ html_static_path = ['_static']
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
......@@ -152,22 +153,16 @@ html_static_path = ['_static']
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Tweepydoc'
htmlhelp_basename = 'tweepydoc'
# -- Options for LaTeX output --------------------------------------------------
......@@ -181,7 +176,7 @@ htmlhelp_basename = 'Tweepydoc'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Tweepy.tex', u'Tweepy Documentation',
('index', 'tweepy.tex', u'tweepy Documentation',
u'Joshua Roesslein', 'manual'),
]
......@@ -193,12 +188,6 @@ latex_documents = [
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
......@@ -206,14 +195,4 @@ latex_documents = [
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'tweepy', u'Tweepy Documentation',
[u'Joshua Roesslein'], 1)
]
#latex_use_modindex = True
.. _cursor_tutorial:
***************
Cursor Tutorial
***************
This tutorial describes details on pagination with Cursor objects.
Introduction
============
We use pagination a lot in Twitter API development. Iterating through
timelines, user lists, direct messages, etc. In order to perform
pagination we must supply a page/cursor parameter with each of our
requests. The problem here is this requires a lot of boiler plate code
just to manage the pagination loop. To help make pagination easier and
require less code Tweepy has the Cursor object.
Old way vs Cursor way
---------------------
First let's demonstrate iterating the statues in the authenticated
user's timeline. Here is how we would do it the "old way" before
Cursor object was introduced::
page = 1
while True:
statuses = api.user_timeline(page=page)
if statuses:
for status in statuses:
# process status here
process_status(status)
else:
# All done
break
page += 1 # next page
As you can see we must manage the "page" parameter manually in our
pagination loop. Now here is the version of the code using Cursor
object::
for status in Cursor(api.user_timeline).items():
# process status here
process_status(status)
Now that looks much better! Cursor handles all the pagination work for
us behind the scene so our code can now focus entirely on processing
the results.
Passing parameters into the API method
--------------------------------------
What if you need to pass in parameters to the API method?
.. code-block :: python
api.user_timeline(id="twitter")
Since we pass Cursor the callable, we can not pass the parameters
directly into the method. Instead we pass the parameters into the
Cursor constructor method::
Cursor(api.user_timeline, id="twitter")
Now Cursor will pass the parameter into the method for us when ever it
makes a request.
Items or Pages
--------------
So far we have just demonstrated pagination iterating per an
item. What if instead you want to process per a page of results? You
would use the pages() method::
for page in Cursor(api.user_timeline).pages():
# page is a list of statuses
process_page(page)
Limits
------
What if you only want n items or pages returned? You pass into the items() or pages() methods the limit you want to impose.
.. code-block :: python
# Only iterate through the first 200 statuses
for status in Cursor(api.user_timeline).items(200):
process_status(status)
# Only iterate through the first 3 pages
for page in Cursor(api.user_timeline).pages(3):
process_page(page)
.. _getting_started:
***************
Getting started
***************
Introduction
============
If you are new to Tweepy, this is the place to begin. The goal of this
tutorial is to get you set-up and rolling with Tweepy. We won't go
into too much detail here, just some important basics.
Hello Tweepy
============
.. code-block :: python
import tweepy
public_tweets = tweepy.api.public_timeline()
for tweet in public_tweets:
print tweet.text
This example will download the public timeline tweets and print each
one of their texts to the console. tweepy.api in the above code
snippet is an unauthenticated instance of the tweepy API class. The
API class contains all the methods for access the Twitter API. By
unauthenticated means there is no user associated with this
instance. So you may only do unauthenticated API calls with this
instance. For example the following would fail::
tweepy.api.update_status('will not work!')
The :ref:`auth_tutorial` goes into more details about authentication.
API
===
The API class provides access to the entire twitter RESTful API
methods. Each method can accept various parameters and return
responses. For more information about these methods please refer to
:ref:`API Reference <api_reference>`.
Models
======
When we invoke an API method most of the time returned back to us will
be a Tweepy model class instance. This will contain the data returned
from Twitter which we can then use inside our application. For example
the following code returns to us an User model::
# Get the User object for twitter...
user = tweepy.api.get_user('twitter')
Models container the data and some helper methods which we can then
use::
print user.screen_name
print user.followers_count
for friend in user.friends():
print friend.screen_name
For more information about models please see ModelsReference.
.. Tweepy documentation master file, created by
sphinx-quickstart on Fri Apr 15 18:57:17 2011.
.. tweepy documentation master file, created by
sphinx-quickstart on Sun Dec 6 11:13:52 2009.