Skip to content

Commit b49b103

Browse files
committed
Merge pull request bear#301 from bear/feature/docs
Documentation Updates
2 parents bcff1c2 + 51afad9 commit b49b103

8 files changed

Lines changed: 237 additions & 31 deletions

doc/getting_started.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Getting Started
2+
===============
3+
4+
Getting your application tokens
5+
+++++++++++++++++++++++++++++++
6+
7+
.. danger::
8+
9+
This section is subject to changes made by Twitter and may not always be completely up-to-date. If you see something change on their end, please create a `new issue on Github <https://github.com/bear/python-twitter/issues/new>`_ or submit a pull request to update it.
10+
11+
12+
In order to use the python-twitter API client, you first need to acquire a set of application tokens. These will be your ``consumer_key`` and ``consumer_secret``, which get passed to ``twitter.Api()`` when starting your application.
13+
14+
Create your app
15+
________________
16+
17+
The first step in doing so is to create a `Twitter App <https://apps.twitter.com/>`_. Click the "Create New App" button and fill out the fields on the next page.
18+
19+
20+
.. image:: python-twitter-app-creation-part1.png
21+
22+
If there are any problems with the information on that page, Twitter will complain and you can fix it. (Make sure to get the name correct - it is unclear if you can change this later.) On the next screen, you'll see the application that you created and some information about it:
23+
24+
Your app
25+
_________
26+
27+
Once your app is created, you'll be directed to a new page showing you some information about it.
28+
29+
.. image:: python-twitter-app-creation-part2.png
30+
31+
Your Keys
32+
_________
33+
34+
Click on the "Keys and Access Tokens" tab on the top there, just under the green notification in the image above.
35+
36+
37+
.. image:: python-twitter-app-creation-part3.png
38+
39+
At this point, you can test out your application using the keys under "Your Application Tokens". The ``twitter.Api()`` object can be created as follows::
40+
41+
import twitter
42+
api = twitter.Api(consumer_key=[consumer key],
43+
consumer_secret=[consumer secret],
44+
access_token_key=[access token]
45+
access_token_secret=[access token secret])
46+
47+
If you are creating an application for end users/consumers, then you will want them to authorize you application, but that is outside the scope of this document.
48+
49+
And that should be it! If you need a little more help, check out the `examples on Github <https://github.com/bear/python-twitter/tree/master/examples>`_. If you have an open source application using python-twitter, send us a link and we'll add a link to it here.

doc/index.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@ Contents:
1313
:maxdepth: 1
1414

1515
installation.rst
16+
getting_started.rst
1617
migration_v30.rst
1718
models.rst
1819
searching.rst
1920
with_django.rst
21+
twitter.rst
2022

2123

2224
Introduction
259 KB
Loading
153 KB
Loading
164 KB
Loading

doc/twitter.rst

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
1-
python-twitter package
2-
=============
1+
Modules Documentation
2+
=====================
33

44

5-
twitter.api
5+
API
66
----------------
77

88
.. automodule:: twitter.api
99
:members:
1010
:undoc-members:
1111
:show-inheritance:
1212

13+
Models
14+
---------------------
15+
1316
.. automodule:: twitter.category
1417
:members:
1518
:undoc-members:
@@ -60,6 +63,10 @@ twitter.api
6063
:undoc-members:
6164
:show-inheritance:
6265

66+
67+
Utilities
68+
---------------------
69+
6370
.. automodule:: twitter.twitter_utils
6471
:members:
6572
:undoc-members:

examples/shorten_url.py

Lines changed: 103 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,77 @@
11
#!/usr/bin/env python
2-
#
3-
# Copyright 2007-2013 The Python-Twitter Developers
4-
#
2+
3+
# Copyright 2007-2016 The Python-Twitter Developers
4+
55
# Licensed under the Apache License, Version 2.0 (the "License");
66
# you may not use this file except in compliance with the License.
77
# You may obtain a copy of the License at
8-
#
8+
99
# http://www.apache.org/licenses/LICENSE-2.0
10-
#
10+
1111
# Unless required by applicable law or agreed to in writing, software
1212
# distributed under the License is distributed on an "AS IS" BASIS,
1313
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
"""A class that defines the default URL Shortener.
18-
19-
TinyURL is provided as the default and as an example.
20-
"""
21-
22-
import urllib
23-
24-
17+
# ----------------------------------------------------------------------
2518
# Change History
2619
#
2720
# 2010-05-16
28-
# TinyURL example and the idea for this comes from a bug filed by
29-
# acolorado with patch provided by ghills. Class implementation
30-
# was done by bear.
21+
# TinyURL example and the idea for this comes from a bug filed by
22+
# acolorado with patch provided by ghills. Class implementation
23+
# was done by @bear.
3124
#
32-
# Issue 19 http://code.google.com/p/python-twitter/issues/detail?id=19
25+
# Issue #19: http://code.google.com/p/python-twitter/issues/detail?id=19
3326
#
27+
# 2016-02-18
28+
# Updated example with code to demonstrate passing a status message through
29+
# a shortener and then off to PostUpdate. Implemenation by @jeremylow from
30+
# bug filed by @immanuelfactor
31+
#
32+
# Issue #298: https://github.com/bear/python-twitter/issues/298
33+
34+
# ----------------------------------------------------------------------
35+
# This file demonstrates how to shorten all URLs contained within a Tweet
36+
# by passing the tweet text to a shortener. In this case, we're using TinyURL
37+
# since it does not require any real authentication for our purposes. If you
38+
# are using a different service to shorten URLs, then you will need to modify
39+
# the ShortenURL class to suit your needs.
40+
41+
# Note that this example shortens all URLs contained within the Tweet text.
42+
43+
# To use this example, replace the W/X/Y/Zs with your keys obtained from
44+
# Twitter, or uncomment the lines for getting an environment variable. If you
45+
# are using a virtualenv on Linux, you can set environment variables in the
46+
# ~/VIRTUALENVDIR/bin/activate script.
47+
48+
# If you need assistance with obtaining keys from Twitter, see the instructions
49+
# in doc/getting_started.rst.
50+
51+
52+
import re
53+
try:
54+
from urllib.request import urlopen
55+
except:
56+
from urllib2 import urlopen
57+
58+
from twitter import Api
59+
from twitter.twitter_utils import URL_REGEXP
3460

3561

3662
class ShortenURL(object):
37-
"""Helper class to make URL Shortener calls if/when required"""
63+
""" A class that defines the default URL Shortener.
64+
65+
TinyURL is provided as the default and as an example helper class to make
66+
URL Shortener calls if/when required. """
3867

3968
def __init__(self,
4069
userid=None,
4170
password=None):
42-
"""Instantiate a new ShortenURL object
43-
71+
"""Instantiate a new ShortenURL object. TinyURL, which is used for this
72+
example, does not require a userid or password, so you can try this
73+
out without specifying either.
74+
4475
Args:
4576
userid: userid for any required authorization call [optional]
4677
password: password for any required authorization call [optional]
@@ -49,24 +80,68 @@ def __init__(self,
4980
self.password = password
5081

5182
def Shorten(self,
52-
longURL):
53-
"""Call TinyURL API and returned shortened URL result
54-
83+
long_url):
84+
""" Call TinyURL API and returned shortened URL result.
85+
5586
Args:
56-
longURL: URL string to shorten
57-
87+
long_url: URL string to shorten
88+
5889
Returns:
5990
The shortened URL as a string
6091
6192
Note:
62-
longURL is required and no checks are made to ensure completeness
93+
long_url is required and no checks are made to ensure completeness
6394
"""
6495

6596
result = None
66-
f = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % longURL)
97+
f = urlopen("http://tinyurl.com/api-create.php?url={0}".format(
98+
long_url))
6799
try:
68100
result = f.read()
69101
finally:
70102
f.close()
71103

72-
return result
104+
# The following check is required for py2/py3 compatibility, since
105+
# urlopen on py3 returns a bytes-object, and urlopen on py2 returns a
106+
# string.
107+
if isinstance(result, bytes):
108+
return result.decode('utf8')
109+
else:
110+
return result
111+
112+
113+
def _get_api():
114+
# Either specify a set of keys here or use os.getenv('CONSUMER_KEY') style
115+
# assignment:
116+
117+
CONSUMER_KEY = 'WWWWWWWW'
118+
# CONSUMER_KEY = os.getenv("CONSUMER_KEY", None)
119+
CONSUMER_SECRET = 'XXXXXXXX'
120+
# CONSUMER_SECRET = os.getenv("CONSUMER_SECRET", None)
121+
ACCESS_TOKEN = 'YYYYYYYY'
122+
# ACCESS_TOKEN = os.getenv("ACCESS_TOKEN", None)
123+
ACCESS_TOKEN_SECRET = 'ZZZZZZZZ'
124+
# ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET", None)
125+
126+
return Api(CONSUMER_KEY,
127+
CONSUMER_SECRET,
128+
ACCESS_TOKEN,
129+
ACCESS_TOKEN_SECRET)
130+
131+
132+
def PostStatusWithShortenedURL(status):
133+
shortener = ShortenURL()
134+
api = _get_api()
135+
136+
# Find all URLs contained within the status message. Value of ``urls`` will
137+
# be a list.
138+
urls = re.findall(URL_REGEXP, status)
139+
140+
for url in urls:
141+
status = status.replace(url, shortener.Shorten(url), 1)
142+
143+
api.PostUpdate(status)
144+
145+
146+
if __name__ == '__main__':
147+
PostStatusWithShortenedURL("this is a test: http://www.example.com/tests")

examples/streaming/track_users.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2007-2016 The Python-Twitter Developers
4+
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
# ----------------------------------------------------------------------
18+
19+
# This file demonstrates how to track mentions of a specific set of users and
20+
# archive those mentions to a local file. The output file will contain one
21+
# JSON string per line per Tweet.
22+
23+
# To use this example, replace the W/X/Y/Zs with your keys obtained from
24+
# Twitter, or uncomment the lines for getting an environment variable. If you
25+
# are using a virtualenv on Linux, you can set environment variables in the
26+
# ~/VIRTUALENVDIR/bin/activate script.
27+
28+
# If you need assistance with obtaining keys from Twitter, see the instructions
29+
# in doc/getting_started.rst.
30+
31+
import os
32+
import json
33+
34+
from twitter import Api
35+
36+
# Either specify a set of keys here or use os.getenv('CONSUMER_KEY') style
37+
# assignment:
38+
39+
CONSUMER_KEY = 'WWWWWWWW'
40+
# CONSUMER_KEY = os.getenv("CONSUMER_KEY", None)
41+
CONSUMER_SECRET = 'XXXXXXXX'
42+
# CONSUMER_SECRET = os.getenv("CONSUMER_SECRET", None)
43+
ACCESS_TOKEN = 'YYYYYYYY'
44+
# ACCESS_TOKEN = os.getenv("ACCESS_TOKEN", None)
45+
ACCESS_TOKEN_SECRET = 'ZZZZZZZZ'
46+
# ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET", None)
47+
48+
# Users to watch for should be a list. This will be joined by Twitter and the
49+
# data returned will be for any tweet mentioning:
50+
# @twitter *OR* @twitterapi *OR* @support.
51+
USERS = ['@twitter',
52+
'@twitterapi',
53+
'@support']
54+
55+
# Since we're going to be using a streaming endpoint, there is no need to worry
56+
# about rate limits.
57+
api = Api(CONSUMER_KEY,
58+
CONSUMER_SECRET,
59+
ACCESS_TOKEN,
60+
ACCESS_TOKEN_SECRET)
61+
62+
63+
def main():
64+
with open('output.txt', 'a') as f:
65+
# api.GetStreamFilter will return a generator that yields one status
66+
# message (i.e., Tweet) at a time as a JSON dictionary.
67+
for line in api.GetStreamFilter(track=USERS):
68+
f.write(json.dumps(line))
69+
f.write('\n')
70+
71+
72+
if __name__ == '__main__':
73+
main()

0 commit comments

Comments
 (0)