code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
from pysqlite2 import dbapi2 as sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table person(firstname, lastname)")
# Fill the table
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
# Print the table contents
for row in con.execute("select firstname, lastname from person"):
print row
# Using a dummy WHERE clause to not let SQLite take the shortcut table deletes.
print "I just deleted", con.execute("delete from person where 1=1").rowcount, "rows"
| Python |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
locals())
print cur.fetchone()
| Python |
# Not referenced from the documentation, but builds the database file the other
# code snippets expect.
from pysqlite2 import dbapi2 as sqlite3
import os
DB_FILE = "mydb"
if os.path.exists(DB_FILE):
os.remove(DB_FILE)
con = sqlite3.connect(DB_FILE)
cur = con.cursor()
cur.execute("""
create table people
(
name_last varchar(20),
age integer
)
""")
cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)")
cur.execute("insert into people (name_last, age) values ('Putin', 51)")
con.commit()
cur.close()
con.close()
| Python |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
{"who": who, "age": age})
print cur.fetchone()
| Python |
from pysqlite2 import dbapi2 as sqlite3
import datetime
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),))
dt = cur.fetchone()[0]
print dt, type(dt)
| Python |
from pysqlite2 import dbapi2 as sqlite3
def char_generator():
import string
for c in string.letters[:26]:
yield (c,)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from characters")
print cur.fetchall()
| Python |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
newPeople = (
('Lebed' , 53),
('Zhirinovsky' , 57),
)
for person in newPeople:
cur.execute("insert into people (name_last, age) values (?, ?)", person)
# The changes will not be saved unless the transaction is committed explicitly:
con.commit()
| Python |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return "%f;%f" % (self.x, self.y)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
| Python |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return "(%f;%f)" % (self.x, self.y)
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
def convert_point(s):
x, y = map(float, s.split(";"))
return Point(x, y)
# Register the adapter
sqlite3.register_adapter(Point, adapt_point)
# Register the converter
sqlite3.register_converter("point", convert_point)
p = Point(4.0, -3.2)
#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print "with declared types:", cur.fetchone()[0]
cur.close()
con.close()
#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print "with column names:", cur.fetchone()[0]
cur.close()
con.close()
| Python |
from pysqlite2 import dbapi2 as sqlite3
class IterChars:
def __init__(self):
self.count = ord('a')
def __iter__(self):
return self
def next(self):
if self.count > ord('z'):
raise StopIteration
self.count += 1
return (chr(self.count - 1),) # this is a 1-tuple
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)
cur.execute("select c from characters")
print cur.fetchall()
| Python |
from pysqlite2 import dbapi2 as sqlite3
import apsw
apsw_con = apsw.Connection(":memory:")
apsw_con.createscalarfunction("times_two", lambda x: 2*x, 1)
# Create pysqlite connection from APSW connection
con = sqlite3.connect(apsw_con)
result = con.execute("select times_two(15)").fetchone()[0]
assert result == 30
con.close()
| Python |
from pysqlite2 import dbapi2 as sqlite3
import datetime, time
def adapt_datetime(ts):
return time.mktime(ts.timetuple())
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
con = sqlite3.connect(":memory:")
cur = con.cursor()
now = datetime.datetime.now()
cur.execute("select ?", (now,))
print cur.fetchone()[0]
| Python |
# Author: Paul Kippes <kippesp@gmail.com>
import unittest
from pysqlite2 import dbapi2 as sqlite
class DumpTests(unittest.TestCase):
def setUp(self):
self.cx = sqlite.connect(":memory:")
self.cu = self.cx.cursor()
def tearDown(self):
self.cx.close()
def CheckTableDump(self):
expected_sqls = [
"CREATE TABLE t1(id integer primary key, s1 text, " \
"t1_i1 integer not null, i2 integer, unique (s1), " \
"constraint t1_idx1 unique (i2));"
,
"INSERT INTO \"t1\" VALUES(1,'foo',10,20);"
,
"INSERT INTO \"t1\" VALUES(2,'foo2',30,30);"
,
"CREATE TABLE t2(id integer, t2_i1 integer, " \
"t2_i2 integer, primary key (id)," \
"foreign key(t2_i1) references t1(t1_i1));"
,
"CREATE TRIGGER trigger_1 update of t1_i1 on t1 " \
"begin " \
"update t2 set t2_i1 = new.t1_i1 where t2_i1 = old.t1_i1; " \
"end;"
,
"CREATE VIEW v1 as select * from t1 left join t2 " \
"using (id);"
]
[self.cu.execute(s) for s in expected_sqls]
i = self.cx.iterdump()
actual_sqls = [s for s in i]
expected_sqls = ['BEGIN TRANSACTION;'] + expected_sqls + \
['COMMIT;']
[self.assertEqual(expected_sqls[i], actual_sqls[i])
for i in xrange(len(expected_sqls))]
def suite():
return unittest.TestSuite(unittest.makeSuite(DumpTests, "Check"))
def test():
runner = unittest.TextTestRunner()
runner.run(suite())
if __name__ == "__main__":
test()
| Python |
# Mimic the sqlite3 console shell's .dump command
# Author: Paul Kippes <kippesp@gmail.com>
def _iterdump(connection):
"""
Returns an iterator to the dump of the database in an SQL text format.
Used to produce an SQL dump of the database. Useful to save an in-memory
database for later restoration. This function should not be called
directly but instead called from the Connection method, iterdump().
"""
cu = connection.cursor()
yield('BEGIN TRANSACTION;')
# sqlite_master table contains the SQL CREATE statements for the database.
q = """
SELECT name, type, sql
FROM sqlite_master
WHERE sql NOT NULL AND
type == 'table'
"""
schema_res = cu.execute(q)
for table_name, type, sql in schema_res.fetchall():
if table_name == 'sqlite_sequence':
yield('DELETE FROM sqlite_sequence;')
elif table_name == 'sqlite_stat1':
yield('ANALYZE sqlite_master;')
elif table_name.startswith('sqlite_'):
continue
# NOTE: Virtual table support not implemented
#elif sql.startswith('CREATE VIRTUAL TABLE'):
# qtable = table_name.replace("'", "''")
# yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
# "VALUES('table','%s','%s',0,'%s');" %
# qtable,
# qtable,
# sql.replace("''"))
else:
yield('%s;' % sql)
# Build the insert statement for each row of the current table
res = cu.execute("PRAGMA table_info('%s')" % table_name)
column_names = [str(table_info[1]) for table_info in res.fetchall()]
q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES("
q += ",".join(["'||quote(" + col + ")||'" for col in column_names])
q += ")' FROM '%(tbl_name)s'"
query_res = cu.execute(q % {'tbl_name': table_name})
for row in query_res:
yield("%s;" % row[0])
# Now when the type is 'index', 'trigger', or 'view'
q = """
SELECT name, type, sql
FROM sqlite_master
WHERE sql NOT NULL AND
type IN ('index', 'trigger', 'view')
"""
schema_res = cu.execute(q)
for name, type, sql in schema_res.fetchall():
yield('%s;' % sql)
yield('COMMIT;')
| Python |
#coding:utf8
from bottle import route, run, debug, template, request, validate, error, response, redirect
from y_common import *
from weibopy.auth import WebOAuthHandler
from weibopy import oauth
@route('/login')
def login():
redirect('/sina/login')
@route('/sina/login')
def sina_login():
auth = WebOAuthHandler(sina_consumer_key, sina_consumer_secret)
auth_url = auth.get_authorization_url_with_callback(baseurl + "/sina/callback/")
redirect(auth_url)
@route('/sina/callback/:request_token')
def sina_callback(request_token):
oauth_verifier = request.GET.get('oauth_verifier', None)
auth = WebOAuthHandler(sina_consumer_key, sina_consumer_secret, oauth.OAuthToken.from_string(request_token))
token = auth.get_access_token(oauth_verifier)
response.set_cookie("ybole_auth", token, secret = gng_secret)
redirect('/')
| Python |
from bottle import route, run, debug, template, request, validate, error, response, redirect
@route('/apply/sent')
@route('/apply/sent/show')
def apply_sent_show():
return template('home')
@route('/apply/sent/add/:tweet_id')
def apply_sent_add(tweet_id):
return template('home')
@route('/apply/sent/exist/:tweet_id')
def apply_sent_exist(tweet_id):
return template('home')
@route('/apply/sent/count')
def apply_sent_count():
return template('home')
@route('/apply/sent/delete/:tweet_id')
def apply_sent_delete(tweet_id):
return template('home')
| Python |
from bottle import route, run, debug, template, request, validate, error, response, redirect
@route('/')
@route('/home')
def home():
return template('home')
#return 'Ybole - Python backend ... Coming soon!'
| Python |
from bottle import route, run, debug, template, request, validate, error, response, redirect
@route('/admin/')
def admin():
return template("home")
@route('/admin/tag')
def admin_tag():
return template("home")
@route('/admin/tag/edit')
def admin_tag():
return template("home")
| Python |
import re, base64, json
baseurl = "http://www.ybole.com:81"
gng_secret = "HUSTGNGisVeryGelivable"
sina_consumer_key= "961495784"
sina_consumer_secret ="47d9d806a1dc04cc758be6f7213465bc"
def htmlEncode(str):
""" Returns the HTML encoded version of the given string. This is useful to
display a plain ASCII text string on a web page."""
htmlCodes = [
['&', '&'],
['<', '<'],
['>', '>'],
['"', '"'],
]
for orig, repl in htmlCodes:
str = str.replace(orig, repl)
return str
def jsonencode(x):
data = dict(x)
return json.dumps(data)
| Python |
#coding:utf8
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from urllib2 import Request, urlopen
import base64
from weibopy import oauth
from weibopy.error import WeibopError
from weibopy.api import API
class AuthHandler(object):
def apply_auth(self, url, method, headers, parameters):
"""Apply authentication headers to request"""
raise NotImplementedError
def get_username(self):
"""Return the username of the authenticated user"""
raise NotImplementedError
class BasicAuthHandler(AuthHandler):
def __init__(self, username, password):
self.username = username
self._b64up = base64.b64encode('%s:%s' % (username, password))
def apply_auth(self, url, method, headers, parameters):
headers['Authorization'] = 'Basic %s' % self._b64up
def get_username(self):
return self.username
class OAuthHandler(AuthHandler):
"""OAuth authentication handler"""
OAUTH_HOST = 'api.t.sina.com.cn'
OAUTH_ROOT = '/oauth/'
def __init__(self, consumer_key, consumer_secret, callback=None, secure=False):
self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.request_token = None
self.access_token = None
self.callback = callback
self.username = None
self.secure = secure
def _get_oauth_url(self, endpoint):
if self.secure:
prefix = 'https://'
else:
prefix = 'http://'
return prefix + self.OAUTH_HOST + self.OAUTH_ROOT + endpoint
def apply_auth(self, url, method, headers, parameters):
request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer, http_url=url, http_method=method,
token=self.access_token, parameters=parameters
)
request.sign_request(self._sigmethod, self._consumer, self.access_token)
headers.update(request.to_header())
def _get_request_token(self):
try:
url = self._get_oauth_url('request_token')
request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer, http_url=url, callback=self.callback
)
request.sign_request(self._sigmethod, self._consumer, None)
resp = urlopen(Request(url, headers=request.to_header()))
return oauth.OAuthToken.from_string(resp.read())
except Exception, e:
raise WeibopError(e)
def set_request_token(self, key, secret):
self.request_token = oauth.OAuthToken(key, secret)
def set_access_token(self, key, secret):
self.access_token = oauth.OAuthToken(key, secret)
def get_authorization_url(self, signin_with_twitter=False):
"""Get the authorization URL to redirect the user"""
try:
# get the request token
self.request_token = self._get_request_token()
# build auth request and return as url
if signin_with_twitter:
url = self._get_oauth_url('authenticate')
else:
url = self._get_oauth_url('authorize')
request = oauth.OAuthRequest.from_token_and_callback(
token=self.request_token, http_url=url
)
return request.to_url()
except Exception, e:
raise WeibopError(e)
def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
# build request
request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer,
token=self.request_token, http_url=url,
verifier=str(verifier)
)
request.sign_request(self._sigmethod, self._consumer, self.request_token)
# send request
resp = urlopen(Request(url, headers=request.to_header()))
self.access_token = oauth.OAuthToken.from_string(resp.read())
#print 'Access token key: '+ str(self.access_token.key)
#print 'Access token secret: '+ str(self.access_token.secret)
return self.access_token
except Exception, e:
raise WeibopError(e)
def setToken(self, token, tokenSecret):
self.access_token = oauth.OAuthToken(token, tokenSecret)
def get_username(self):
if self.username is None:
api = API(self)
user = api.verify_credentials()
if user:
self.username = user.screen_name
else:
raise WeibopError("Unable to get username, invalid oauth token!")
return self.username
class WebOAuthHandler(OAuthHandler):
"""继承自OAuthHandler,提供Web应用方法。"""
def __init__(self, consumer_key, consumer_secret, access_token=None):
OAuthHandler.__init__(self, consumer_key, consumer_secret)
if access_token is not None:
self.set_access_token(access_token.key, access_token.secret)
self.api = API(self)
def get_authorization_url_with_callback(self, callback, signin_with_twitter=False):
"""Get the authorization URL to redirect the user"""
try:
# get the request token
self.request_token = self._get_request_token()
# build auth request and return as url
if signin_with_twitter:
url = self._get_oauth_url('authenticate')
else:
url = self._get_oauth_url('authorize')
request = oauth.OAuthRequest.from_token_and_callback(
token=self.request_token, callback=callback+oauth.OAuthToken.to_string(self.request_token), http_url=url
)
return request.to_url()
except Exception, e:
raise WeibopError(e)
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
class WeibopError(Exception):
"""Weibopy exception"""
def __init__(self, reason):
try:
self.reason = reason.encode('utf-8')
except:
self.reason = reason
def __str__(self):
return self.reason
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from weibopy.utils import parse_datetime, parse_html_value, parse_a_href, \
parse_search_datetime, unescape_html
class ResultSet(list):
"""A list like object that holds results from a Twitter API query."""
class Model(object):
def __init__(self, api=None):
self._api = api
def __getstate__(self):
# pickle
pickle = dict(self.__dict__)
del pickle['_api'] # do not pickle the API reference
return pickle
@classmethod
def parse(cls, api, json):
"""Parse a JSON object into a model instance."""
raise NotImplementedError
@classmethod
def parse_list(cls, api, json_list):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
for obj in json_list:
results.append(cls.parse(api, obj))
return results
class Status(Model):
@classmethod
def parse(cls, api, json):
status = cls(api)
for k, v in json.items():
if k == 'user':
user = User.parse(api, v)
setattr(status, 'author', user)
setattr(status, 'user', user) # DEPRECIATED
elif k == 'screen_name':
setattr(status, k, v)
elif k == 'created_at':
setattr(status, k, parse_datetime(v))
elif k == 'source':
if '<' in v:
setattr(status, k, parse_html_value(v))
setattr(status, 'source_url', parse_a_href(v))
else:
setattr(status, k, v)
elif k == 'retweeted_status':
setattr(status, k, User.parse(api, v))
elif k == 'geo':
setattr(status, k, Geo.parse(api, v))
else:
setattr(status, k, v)
return status
def destroy(self):
return self._api.destroy_status(self.id)
def retweet(self):
return self._api.retweet(self.id)
def retweets(self):
return self._api.retweets(self.id)
def favorite(self):
return self._api.create_favorite(self.id)
class Geo(Model):
@classmethod
def parse(cls, api, json):
geo = cls(api)
if json is not None:
for k, v in json.items():
setattr(geo, k, v)
return geo
class Comments(Model):
@classmethod
def parse(cls, api, json):
comments = cls(api)
for k, v in json.items():
if k == 'user':
user = User.parse(api, v)
setattr(comments, 'author', user)
setattr(comments, 'user', user)
elif k == 'status':
status = Status.parse(api, v)
setattr(comments, 'user', status)
elif k == 'created_at':
setattr(comments, k, parse_datetime(v))
elif k == 'reply_comment':
setattr(comments, k, User.parse(api, v))
else:
setattr(comments, k, v)
return comments
def destroy(self):
return self._api.destroy_status(self.id)
def retweet(self):
return self._api.retweet(self.id)
def retweets(self):
return self._api.retweets(self.id)
def favorite(self):
return self._api.create_favorite(self.id)
class User(Model):
@classmethod
def parse(cls, api, json):
user = cls(api)
for k, v in json.items():
if k == 'created_at':
setattr(user, k, parse_datetime(v))
elif k == 'status':
setattr(user, k, Status.parse(api, v))
elif k == 'screen_name':
setattr(user, k, v)
elif k == 'following':
# twitter sets this to null if it is false
if v is True:
setattr(user, k, True)
else:
setattr(user, k, False)
else:
setattr(user, k, v)
return user
@classmethod
def parse_list(cls, api, json_list):
if isinstance(json_list, list):
item_list = json_list
else:
item_list = json_list['users']
results = ResultSet()
for obj in item_list:
results.append(cls.parse(api, obj))
return results
def timeline(self, **kargs):
return self._api.user_timeline(user_id=self.id, **kargs)
def friends(self, **kargs):
return self._api.friends(user_id=self.id, **kargs)
def followers(self, **kargs):
return self._api.followers(user_id=self.id, **kargs)
def follow(self):
self._api.create_friendship(user_id=self.id)
self.following = True
def unfollow(self):
self._api.destroy_friendship(user_id=self.id)
self.following = False
def lists_memberships(self, *args, **kargs):
return self._api.lists_memberships(user=self.screen_name, *args, **kargs)
def lists_subscriptions(self, *args, **kargs):
return self._api.lists_subscriptions(user=self.screen_name, *args, **kargs)
def lists(self, *args, **kargs):
return self._api.lists(user=self.screen_name, *args, **kargs)
def followers_ids(self, *args, **kargs):
return self._api.followers_ids(user_id=self.id, *args, **kargs)
class DirectMessage(Model):
@classmethod
def parse(cls, api, json):
dm = cls(api)
for k, v in json.items():
if k == 'sender' or k == 'recipient':
setattr(dm, k, User.parse(api, v))
elif k == 'created_at':
setattr(dm, k, parse_datetime(v))
else:
setattr(dm, k, v)
return dm
class Friendship(Model):
@classmethod
def parse(cls, api, json):
source = cls(api)
for k, v in json['source'].items():
setattr(source, k, v)
# parse target
target = cls(api)
for k, v in json['target'].items():
setattr(target, k, v)
return source, target
class SavedSearch(Model):
@classmethod
def parse(cls, api, json):
ss = cls(api)
for k, v in json.items():
if k == 'created_at':
setattr(ss, k, parse_datetime(v))
else:
setattr(ss, k, v)
return ss
def destroy(self):
return self._api.destroy_saved_search(self.id)
class SearchResult(Model):
@classmethod
def parse(cls, api, json):
result = cls()
for k, v in json.items():
if k == 'created_at':
setattr(result, k, parse_search_datetime(v))
elif k == 'source':
setattr(result, k, parse_html_value(unescape_html(v)))
else:
setattr(result, k, v)
return result
@classmethod
def parse_list(cls, api, json_list, result_set=None):
results = ResultSet()
results.max_id = json_list.get('max_id')
results.since_id = json_list.get('since_id')
results.refresh_url = json_list.get('refresh_url')
results.next_page = json_list.get('next_page')
results.results_per_page = json_list.get('results_per_page')
results.page = json_list.get('page')
results.completed_in = json_list.get('completed_in')
results.query = json_list.get('query')
for obj in json_list['results']:
results.append(cls.parse(api, obj))
return results
class List(Model):
@classmethod
def parse(cls, api, json):
lst = List(api)
for k,v in json.items():
if k == 'user':
setattr(lst, k, User.parse(api, v))
else:
setattr(lst, k, v)
return lst
@classmethod
def parse_list(cls, api, json_list, result_set=None):
results = ResultSet()
for obj in json_list['lists']:
results.append(cls.parse(api, obj))
return results
def update(self, **kargs):
return self._api.update_list(self.slug, **kargs)
def destroy(self):
return self._api.destroy_list(self.slug)
def timeline(self, **kargs):
return self._api.list_timeline(self.user.screen_name, self.slug, **kargs)
def add_member(self, id):
return self._api.add_list_member(self.slug, id)
def remove_member(self, id):
return self._api.remove_list_member(self.slug, id)
def members(self, **kargs):
return self._api.list_members(self.user.screen_name, self.slug, **kargs)
def is_member(self, id):
return self._api.is_list_member(self.user.screen_name, self.slug, id)
def subscribe(self):
return self._api.subscribe_list(self.user.screen_name, self.slug)
def unsubscribe(self):
return self._api.unsubscribe_list(self.user.screen_name, self.slug)
def subscribers(self, **kargs):
return self._api.list_subscribers(self.user.screen_name, self.slug, **kargs)
def is_subscribed(self, id):
return self._api.is_subscribed_list(self.user.screen_name, self.slug, id)
class JSONModel(Model):
@classmethod
def parse(cls, api, json):
lst = JSONModel(api)
for k,v in json.items():
setattr(lst, k, v)
return lst
class IDSModel(Model):
@classmethod
def parse(cls, api, json):
ids = IDSModel(api)
for k, v in json.items():
setattr(ids, k, v)
return ids
class Counts(Model):
@classmethod
def parse(cls, api, json):
ids = Counts(api)
for k, v in json.items():
setattr(ids, k, v)
return ids
class ModelFactory(object):
"""
Used by parsers for creating instances
of models. You may subclass this factory
to add your own extended models.
"""
status = Status
comments = Comments
user = User
direct_message = DirectMessage
friendship = Friendship
saved_search = SavedSearch
search_result = SearchResult
list = List
json = JSONModel
ids_list = IDSModel
counts = Counts
| Python |
"""
The MIT License
Copyright (c) 2007 Leah Culver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import cgi
import urllib
import time
import random
import urlparse
import hmac
import binascii
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class OAuthError(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occured.'):
self.message = message
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s, safe='~')
def _utf8_str(s):
"""Convert unicode to utf-8."""
if isinstance(s, unicode):
return s.encode("utf-8")
else:
return str(s)
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class OAuthConsumer(object):
"""Consumer of OAuth authentication.
OAuthConsumer is a data type that represents the identity of the Consumer
via its shared secret with the Service Provider.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
class OAuthToken(object):
"""OAuthToken is a data type that represents an End User via either an access
or request token.
key -- the token
secret -- the token secret
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
def from_string(s):
""" Returns a token from something like:
oauth_token_secret=xxx&oauth_token=xxx
"""
params = cgi.parse_qs(s, keep_blank_values=False)
key = params['oauth_token'][0]
secret = params['oauth_token_secret'][0]
token = OAuthToken(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
from_string = staticmethod(from_string)
def __str__(self):
return self.to_string()
class OAuthRequest(object):
"""OAuthRequest represents the request and can be serialized.
OAuth parameters:
- oauth_consumer_key
- oauth_token
- oauth_signature_method
- oauth_signature
- oauth_timestamp
- oauth_nonce
- oauth_version
- oauth_verifier
... any additional parameters, as defined by the Service Provider.
"""
parameters = None # OAuth parameters.
http_method = HTTP_METHOD
http_url = None
version = VERSION
def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None):
self.http_method = http_method
self.http_url = http_url
self.parameters = parameters or {}
def set_parameter(self, parameter, value):
self.parameters[parameter] = value
def get_parameter(self, parameter):
try:
return self.parameters[parameter]
except:
raise OAuthError('Parameter not found: %s' % parameter)
def _get_timestamp_nonce(self):
return self.get_parameter('oauth_timestamp'), self.get_parameter(
'oauth_nonce')
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
parameters = {}
for k, v in self.parameters.iteritems():
# Ignore oauth parameters.
if k.find('oauth_') < 0:
parameters[k] = v
return parameters
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
auth_header = 'OAuth realm="%s"' % realm
# Add the oauth parameters.
if self.parameters:
for k, v in self.parameters.iteritems():
if k[:6] == 'oauth_':
auth_header += ', %s="%s"' % (k, escape(str(v)))
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \
for k, v in self.parameters.iteritems()])
def to_url(self):
"""Serialize as a URL for a GET request."""
return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata())
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
params = self.parameters
try:
# Exclude the signature if it exists.
del params['oauth_signature']
except:
pass
# Escape key values before sorting.
key_values = [(escape(_utf8_str(k)), escape(_utf8_str(v))) \
for k,v in params.items()]
# Sort lexicographically, first after key, then after value.
key_values.sort()
# Combine key value pairs into a string.
return '&'.join(['%s=%s' % (k, v) for k, v in key_values])
def get_normalized_http_method(self):
"""Uppercases the http method."""
return self.http_method.upper()
def get_normalized_http_url(self):
"""Parses the URL and rebuilds it to be scheme://host/path."""
parts = urlparse.urlparse(self.http_url)
scheme, netloc, path = parts[:3]
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
return '%s://%s%s' % (scheme, netloc, path)
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of build_signature."""
# Set the signature method.
self.set_parameter('oauth_signature_method',
signature_method.get_name())
# Set the signature.
self.set_parameter('oauth_signature',self.build_signature(signature_method, consumer, token))
def build_signature(self, signature_method, consumer, token):
"""Calls the build signature method within the signature method."""
return signature_method.build_signature(self, consumer, token)
def from_request(http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = OAuthRequest._split_header(auth_header)
parameters.update(header_params)
except:
raise OAuthError('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = OAuthRequest._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = OAuthRequest._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return OAuthRequest(http_method, http_url, parameters)
return None
from_request = staticmethod(from_request)
def from_consumer_and_token(oauth_consumer, token=None,
callback=None, verifier=None, http_method=HTTP_METHOD,
http_url=None, parameters=None):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': oauth_consumer.key,
'oauth_timestamp': generate_timestamp(),
'oauth_nonce': generate_nonce(),
'oauth_version': OAuthRequest.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.callback:
parameters['oauth_callback'] = token.callback
# 1.0a support for verifier.
if verifier:
parameters['oauth_verifier'] = verifier
elif callback:
# 1.0a support for callback in the request token request.
parameters['oauth_callback'] = callback
return OAuthRequest(http_method, http_url, parameters)
from_consumer_and_token = staticmethod(from_consumer_and_token)
def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD,
http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return OAuthRequest(http_method, http_url, parameters)
from_token_and_callback = staticmethod(from_token_and_callback)
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
_split_header = staticmethod(_split_header)
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = cgi.parse_qs(param_str, keep_blank_values=False)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
_split_url_string = staticmethod(_split_url_string)
class OAuthServer(object):
"""A worker to check the validity of a request against a data store."""
timestamp_threshold = 300 # In seconds, five minutes.
version = VERSION
signature_methods = None
data_store = None
def __init__(self, data_store=None, signature_methods=None):
self.data_store = data_store
self.signature_methods = signature_methods or {}
def set_data_store(self, data_store):
self.data_store = data_store
def get_data_store(self):
return self.data_store
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.get_name()] = signature_method
return self.signature_methods
def fetch_request_token(self, oauth_request):
"""Processes a request_token request and returns the
request token on success.
"""
try:
# Get the request token for authorization.
token = self._get_token(oauth_request, 'request')
except OAuthError:
# No token required for the initial token request.
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
callback = self.get_callback(oauth_request)
except OAuthError:
callback = None # 1.0, no callback specified.
self._check_signature(oauth_request, consumer, None)
# Fetch a new token.
token = self.data_store.fetch_request_token(consumer, callback)
return token
def fetch_access_token(self, oauth_request):
"""Processes an access_token request and returns the
access token on success.
"""
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
verifier = self._get_verifier(oauth_request)
except OAuthError:
verifier = None
# Get the request token.
token = self._get_token(oauth_request, 'request')
self._check_signature(oauth_request, consumer, token)
new_token = self.data_store.fetch_access_token(consumer, token, verifier)
return new_token
def verify_request(self, oauth_request):
"""Verifies an api call and checks all the parameters."""
# -> consumer and token
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
# Get the access token.
token = self._get_token(oauth_request, 'access')
self._check_signature(oauth_request, consumer, token)
parameters = oauth_request.get_nonoauth_parameters()
return consumer, token, parameters
def authorize_token(self, token, user):
"""Authorize a request token."""
return self.data_store.authorize_request_token(token, user)
def get_callback(self, oauth_request):
"""Get the callback URL."""
return oauth_request.get_parameter('oauth_callback')
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _get_version(self, oauth_request):
"""Verify the correct version request for this server."""
try:
version = oauth_request.get_parameter('oauth_version')
except:
version = VERSION
if version and version != self.version:
raise OAuthError('OAuth version %s not supported.' % str(version))
return version
def _get_signature_method(self, oauth_request):
"""Figure out the signature with some defaults."""
try:
signature_method = oauth_request.get_parameter(
'oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise OAuthError('Signature method %s not supported try one of the '
'following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_consumer(self, oauth_request):
consumer_key = oauth_request.get_parameter('oauth_consumer_key')
consumer = self.data_store.lookup_consumer(consumer_key)
if not consumer:
raise OAuthError('Invalid consumer.')
return consumer
def _get_token(self, oauth_request, token_type='access'):
"""Try to find the token for the provided request token key."""
token_field = oauth_request.get_parameter('oauth_token')
token = self.data_store.lookup_token(token_type, token_field)
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return token
def _get_verifier(self, oauth_request):
return oauth_request.get_parameter('oauth_verifier')
def _check_signature(self, oauth_request, consumer, token):
timestamp, nonce = oauth_request._get_timestamp_nonce()
self._check_timestamp(timestamp)
self._check_nonce(consumer, token, nonce)
signature_method = self._get_signature_method(oauth_request)
try:
signature = oauth_request.get_parameter('oauth_signature')
except:
raise OAuthError('Missing signature.')
# Validate the signature.
valid_sig = signature_method.check_signature(oauth_request, consumer,
token, signature)
if not valid_sig:
key, base = signature_method.build_signature_base_string(
oauth_request, consumer, token)
raise OAuthError('Invalid signature. Expected signature base '
'string: %s' % base)
built = signature_method.build_signature(oauth_request, consumer, token)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = abs(now - timestamp)
if lapsed > self.timestamp_threshold:
raise OAuthError('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' %
(timestamp, now, self.timestamp_threshold))
def _check_nonce(self, consumer, token, nonce):
"""Verify that the nonce is uniqueish."""
nonce = self.data_store.lookup_nonce(consumer, token, nonce)
if nonce:
raise OAuthError('Nonce already used: %s' % str(nonce))
class OAuthClient(object):
"""OAuthClient is a worker to attempt to execute a request."""
consumer = None
token = None
def __init__(self, oauth_consumer, oauth_token):
self.consumer = oauth_consumer
self.token = oauth_token
def get_consumer(self):
return self.consumer
def get_token(self):
return self.token
def fetch_request_token(self, oauth_request):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_access_token(self, oauth_request):
"""-> OAuthToken."""
raise NotImplementedError
def access_resource(self, oauth_request):
"""-> Some protected resource."""
raise NotImplementedError
class OAuthDataStore(object):
"""A database abstraction used to lookup consumers and tokens."""
def lookup_consumer(self, key):
"""-> OAuthConsumer."""
raise NotImplementedError
def lookup_token(self, oauth_consumer, token_type, token_token):
"""-> OAuthToken."""
raise NotImplementedError
def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_request_token(self, oauth_consumer, oauth_callback):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
"""-> OAuthToken."""
raise NotImplementedError
def authorize_request_token(self, oauth_token, user):
"""-> OAuthToken."""
raise NotImplementedError
class OAuthSignatureMethod(object):
"""A strategy class that implements a signature method."""
def get_name(self):
"""-> str."""
raise NotImplementedError
def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token):
"""-> str key, str raw."""
raise NotImplementedError
def build_signature(self, oauth_request, oauth_consumer, oauth_token):
"""-> str."""
raise NotImplementedError
def check_signature(self, oauth_request, consumer, token, signature):
built = self.build_signature(oauth_request, consumer, token)
return built == signature
class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod):
def get_name(self):
return 'HMAC-SHA1'
def build_signature_base_string(self, oauth_request, consumer, token):
sig = (
escape(oauth_request.get_normalized_http_method()),
escape(oauth_request.get_normalized_http_url()),
escape(oauth_request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
#print "OAuth base string:" + str(sig)
raw = '&'.join(sig)
return key, raw
def build_signature(self, oauth_request, consumer, token):
"""Builds the base signature string."""
key, raw = self.build_signature_base_string(oauth_request, consumer,
token)
# HMAC object.
try:
import hashlib # 2.5
hashed = hmac.new(key, raw, hashlib.sha1)
except:
import sha # Deprecated
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod):
def get_name(self):
return 'PLAINTEXT'
def build_signature_base_string(self, oauth_request, consumer, token):
"""Concatenates the consumer key and secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def build_signature(self, oauth_request, consumer, token):
key, raw = self.build_signature_base_string(oauth_request, consumer,
token)
return key | Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from weibopy.models import ModelFactory
from weibopy.utils import import_simplejson
from weibopy.error import WeibopError
class Parser(object):
def parse(self, method, payload):
"""
Parse the response payload and return the result.
Returns a tuple that contains the result data and the cursors
(or None if not present).
"""
raise NotImplementedError
def parse_error(self, method, payload):
"""
Parse the error message from payload.
If unable to parse the message, throw an exception
and default error message will be used.
"""
raise NotImplementedError
class JSONParser(Parser):
payload_format = 'json'
def __init__(self):
self.json_lib = import_simplejson()
def parse(self, method, payload):
try:
json = self.json_lib.loads(payload)
except Exception, e:
print "Failed to parse JSON payload:"+ str(payload)
raise WeibopError('Failed to parse JSON payload: %s' % e)
#if isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
# cursors = json['previous_cursor'], json['next_cursor']
# return json, cursors
#else:
return json
def parse_error(self, method, payload):
return self.json_lib.loads(payload)
class ModelParser(JSONParser):
def __init__(self, model_factory=None):
JSONParser.__init__(self)
self.model_factory = model_factory or ModelFactory
def parse(self, method, payload):
try:
if method.payload_type is None: return
model = getattr(self.model_factory, method.payload_type)
except AttributeError:
raise WeibopError('No model for this payload type: %s' % method.payload_type)
json = JSONParser.parse(self, method, payload)
if isinstance(json, tuple):
json, cursors = json
else:
cursors = None
if method.payload_list:
result = model.parse_list(method.api, json)
else:
result = model.parse(method.api, json)
if cursors:
return result, cursors
else:
return result
| Python |
# Copyright 2010 Joshua Roesslein
# See LICENSE for details.
from datetime import datetime
import time
import htmlentitydefs
import re
def parse_datetime(str):
# We must parse datetime this way to work in python 2.4
#return datetime(*(time.strptime(str, '%a %b %d %H:%M:%S +0800 %Y')[0:6]))
#Changed by Felix Yan
try:
a = time.strptime(str, '%a %b %d %H:%M:%S +0800 %Y')[0:6]
except:
print "Error: " + str
a = ""
if len(a)<6:
raise ValueError
else:
return datetime(*a)
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def parse_a_href(atag):
start = atag.find('"') + 1
end = atag.find('"', start)
return atag[start:end]
def parse_search_datetime(str):
# python 2.4
return datetime(*(time.strptime(str, '%a, %d %b %Y %H:%M:%S +0000')[0:6]))
def unescape_html(text):
"""Created by Fredrik Lundh (http://effbot.org/zone/re-sub.htm#unescape-html)"""
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, unicode):
arg = arg.encode('utf-8')
elif not isinstance(arg, str):
arg = str(arg)
return arg
def import_simplejson():
try:
import simplejson as json
except ImportError:
try:
import json # Python 2.6+
except ImportError:
try:
from django.utils import simplejson as json # Google App Engine
except ImportError:
raise ImportError, "Can't load a json library"
return json
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from weibopy.error import WeibopError
from weibopy.utils import convert_to_utf8_str
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', False)
search_api = config.get('search_api', False)
def __init__(self, api, args, kargs):
# If authentication is required and no credentials
# are provided, throw an error.
if self.require_auth and not api.auth:
raise WeibopError('Authentication required!')
self.api = api
self.post_data = kargs.pop('post_data', None)
self.retry_count = kargs.pop('retry_count', api.retry_count)
self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_api:
self.api_root = api.search_root
else:
self.api_root = api.api_root
# Perform any path variable substitution
self.build_path()
if api.secure:
self.scheme = 'https://'
else:
self.scheme = 'http://'
if self.search_api:
self.host = api.search_host
else:
self.host = api.host
# Manually set Host header to fix an issue in python 2.5
# or older where Host is set including the 443 port.
# This causes Twitter to issue 301 redirect.
# See Issue http://github.com/joshthecoder/tweepy/issues/#issue/12
self.headers['Host'] = self.host
def build_parameters(self, args, kargs):
self.parameters = {}
for idx, arg in enumerate(args):
try:
self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
except IndexError:
raise WeibopError('Too many parameters supplied!')
for k, arg in kargs.items():
if arg is None:
continue
if k in self.parameters:
raise WeibopError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
if name == 'user' and self.api.auth:
value = self.api.auth.get_username()
else:
try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise WeibopError('No parameter value found for path variable: %s' % name)
del self.parameters[name]
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if self.api.source is not None:
self.parameters.setdefault('source',self.api.source)
if len(self.parameters):
if self.method == 'GET':
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
else:
self.headers.setdefault("User-Agent","python")
if self.post_data is None:
self.headers.setdefault("Accept","text/html")
self.headers.setdefault("Content-Type","application/x-www-form-urlencoded")
self.post_data = urllib.urlencode(self.parameters)
# Query the cache if one is available
# and this request uses a GET method.
if self.api.cache and self.method == 'GET':
cache_result = self.api.cache.get(url)
# if cache result found and not expired, return it
if cache_result:
# must restore api reference
if isinstance(cache_result, list):
for result in cache_result:
result._api = self.api
else:
cache_result._api = self.api
return cache_result
#urllib.urlencode(self.parameters)
# Continue attempting request until successful
# or maximum number of retries is reached.
sTime = time.time()
retries_performed = 0
while retries_performed < self.retry_count + 1:
# Open connection
# FIXME: add timeout
if self.api.secure:
conn = httplib.HTTPSConnection(self.host)
else:
conn = httplib.HTTPConnection(self.host)
# Apply authentication
if self.api.auth:
self.api.auth.apply_auth(
self.scheme + self.host + url,
self.method, self.headers, self.parameters
)
# Execute request
try:
conn.request(self.method, url, headers=self.headers, body=self.post_data)
resp = conn.getresponse()
except Exception, e:
raise WeibopError('Failed to send request: %s' % e + "url=" + str(url) +",self.headers="+ str(self.headers))
# Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(self.retry_delay)
retries_performed += 1
# If an error was returned, throw an exception
body = resp.read()
self.api.last_response = resp
if self.api.log is not None:
requestUrl = "URL:http://"+ self.host + url
eTime = '%.0f' % ((time.time() - sTime) * 1000)
postData = ""
if self.post_data is not None:
postData = ",post:"+ self.post_data[0:500]
self.api.log.debug(requestUrl +",time:"+ str(eTime)+ postData+",result:"+ body )
if resp.status != 200:
try:
json = self.api.parser.parse_error(self, body)
error_code = json['error_code']
error = json['error']
error_msg = 'error_code:' + error_code +','+ error
except Exception:
error_msg = "Twitter error response: status code = %s" % resp.status
raise WeibopError(error_msg)
# Parse the response payload
result = self.api.parser.parse(self, body)
conn.close()
# Store result into cache if one is available.
if self.api.cache and self.method == 'GET' and result:
self.api.cache.store(url, result)
return result
def _call(api, *args, **kargs):
method = APIMethod(api, args, kargs)
return method.execute()
# Set pagination mode
if 'cursor' in APIMethod.allowed_param:
_call.pagination_mode = 'cursor'
elif 'page' in APIMethod.allowed_param:
_call.pagination_mode = 'page'
return _call
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
weibo API library
"""
__version__ = '1.5'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from weibopy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, ModelFactory, IDSModel
from weibopy.error import WeibopError
from weibopy.api import API
from weibopy.cache import Cache, MemoryCache, FileCache
from weibopy.auth import BasicAuthHandler, OAuthHandler
from weibopy.streaming import Stream, StreamListener
from weibopy.cursor import Cursor
# Global, unauthenticated instance of API
api = API()
def debug(enable=True, level=1):
import httplib
httplib.HTTPConnection.debuglevel = level
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
from socket import timeout
from threading import Thread
from time import sleep
import urllib
from weibopy.auth import BasicAuthHandler
from weibopy.models import Status
from weibopy.api import API
from weibopy.error import WeibopError
from weibopy.utils import import_simplejson
json = import_simplejson()
STREAM_VERSION = 1
class StreamListener(object):
def __init__(self, api=None):
self.api = api or API()
def on_data(self, data):
"""Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data. Return False to stop stream and close connection.
"""
if 'in_reply_to_status_id' in data:
status = Status.parse(self.api, json.loads(data))
if self.on_status(status) is False:
return False
elif 'delete' in data:
delete = json.loads(data)['delete']['status']
if self.on_delete(delete['id'], delete['user_id']) is False:
return False
elif 'limit' in data:
if self.on_limit(json.loads(data)['limit']['track']) is False:
return False
def on_status(self, status):
"""Called when a new status arrives"""
return
def on_delete(self, status_id, user_id):
"""Called when a delete notice arrives for a status"""
return
def on_limit(self, track):
"""Called when a limitation notice arrvies"""
return
def on_error(self, status_code):
"""Called when a non-200 status code is returned"""
return False
def on_timeout(self):
"""Called when stream connection times out"""
return
class Stream(object):
host = 'stream.twitter.com'
def __init__(self, username, password, listener, timeout=5.0, retry_count = None,
retry_time = 10.0, snooze_time = 5.0, buffer_size=1500, headers=None):
self.auth = BasicAuthHandler(username, password)
self.running = False
self.timeout = timeout
self.retry_count = retry_count
self.retry_time = retry_time
self.snooze_time = snooze_time
self.buffer_size = buffer_size
self.listener = listener
self.api = API()
self.headers = headers or {}
self.body = None
def _run(self):
# setup
self.auth.apply_auth(None, None, self.headers, None)
# enter loop
error_counter = 0
conn = None
while self.running:
if self.retry_count and error_counter > self.retry_count:
# quit if error count greater than retry count
break
try:
conn = httplib.HTTPConnection(self.host)
conn.connect()
conn.sock.settimeout(self.timeout)
conn.request('POST', self.url, self.body, headers=self.headers)
resp = conn.getresponse()
if resp.status != 200:
if self.listener.on_error(resp.status) is False:
break
error_counter += 1
sleep(self.retry_time)
else:
error_counter = 0
self._read_loop(resp)
except timeout:
if self.listener.on_timeout() == False:
break
if self.running is False:
break
conn.close()
sleep(self.snooze_time)
except Exception:
# any other exception is fatal, so kill loop
break
# cleanup
self.running = False
if conn:
conn.close()
def _read_loop(self, resp):
data = ''
while self.running:
if resp.isclosed():
break
# read length
length = ''
while True:
c = resp.read(1)
if c == '\n':
break
length += c
length = length.strip()
if length.isdigit():
length = int(length)
else:
continue
# read data and pass into listener
data = resp.read(length)
if self.listener.on_data(data) is False:
self.running = False
def _start(self, async):
self.running = True
if async:
Thread(target=self._run).start()
else:
self._run()
def firehose(self, count=None, async=False):
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/firehose.json?delimited=length' % STREAM_VERSION
if count:
self.url += '&count=%s' % count
self._start(async)
def retweet(self, async=False):
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/retweet.json?delimited=length' % STREAM_VERSION
self._start(async)
def sample(self, count=None, async=False):
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/sample.json?delimited=length' % STREAM_VERSION
if count:
self.url += '&count=%s' % count
self._start(async)
def filter(self, follow=None, track=None, async=False):
params = {}
self.headers['Content-type'] = "application/x-www-form-urlencoded"
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
if follow:
params['follow'] = ','.join(map(str, follow))
if track:
params['track'] = ','.join(map(str, track))
self.body = urllib.urlencode(params)
self._start(async)
def disconnect(self):
if self.running is False:
return
self.running = False
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import os
import mimetypes
from weibopy.binder import bind_api
from weibopy.error import WeibopError
from weibopy.parsers import ModelParser
class API(object):
"""Twitter API"""
def __init__(self, auth_handler=None,
host='api.t.sina.com.cn', search_host='api.t.sina.com.cn',
cache=None, secure=False, api_root='', search_root='',
retry_count=0, retry_delay=0, retry_errors=None,source=None,
parser=None, log = None):
self.auth = auth_handler
self.host = host
if source == None:
if auth_handler != None:
self.source = self.auth._consumer.key
else:
self.source = source
self.search_host = search_host
self.api_root = api_root
self.search_root = search_root
self.cache = cache
self.secure = secure
self.retry_count = retry_count
self.retry_delay = retry_delay
self.retry_errors = retry_errors
self.parser = parser or ModelParser()
self.log = log
""" statuses/public_timeline """
public_timeline = bind_api(
path = '/statuses/public_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = []
)
""" statuses/home_timeline """
home_timeline = bind_api(
path = '/statuses/home_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/friends_timeline """
friends_timeline = bind_api(
path = '/statuses/friends_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/comment """
comment = bind_api(
path = '/statuses/comment.json',
method = 'POST',
payload_type = 'comments',
allowed_param = ['id', 'cid', 'comment'],
require_auth = True
)
""" statuses/comment_destroy """
comment_destroy = bind_api(
path = '/statuses/comment_destroy/{id}.json',
method = 'POST',
payload_type = 'comments',
allowed_param = ['id'],
require_auth = True
)
""" statuses/comments_timeline """
comments = bind_api(
path = '/statuses/comments.json',
payload_type = 'comments', payload_list = True,
allowed_param = ['id', 'count', 'page'],
require_auth = True
)
""" statuses/comments_timeline """
comments_timeline = bind_api(
path = '/statuses/comments_timeline.json',
payload_type = 'comments', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/comments_by_me """
comments_by_me = bind_api(
path = '/statuses/comments_by_me.json',
payload_type = 'comments', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/user_timeline """
user_timeline = bind_api(
path = '/statuses/user_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = ['id', 'user_id', 'screen_name', 'since_id',
'max_id', 'count', 'page']
)
""" statuses/mentions """
mentions = bind_api(
path = '/statuses/mentions.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/counts """
counts = bind_api(
path = '/statuses/counts.json',
payload_type = 'counts', payload_list = True,
allowed_param = ['ids'],
require_auth = True
)
""" statuses/unread """
unread = bind_api(
path = '/statuses/unread.json',
payload_type = 'counts'
)
""" statuses/retweeted_by_me """
retweeted_by_me = bind_api(
path = '/statuses/retweeted_by_me.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/retweeted_to_me """
retweeted_to_me = bind_api(
path = '/statuses/retweeted_to_me.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/retweets_of_me """
retweets_of_me = bind_api(
path = '/statuses/retweets_of_me.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/show """
get_status = bind_api(
path = '/statuses/show.json',
payload_type = 'status',
allowed_param = ['id']
)
""" statuses/update """
update_status = bind_api(
path = '/statuses/update.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['status', 'lat', 'long', 'source'],
require_auth = True
)
""" statuses/upload """
def upload(self, filename, status, lat=None, long=None, source=None):
if source is None:
source=self.source
headers, post_data = API._pack_image(filename, 1024, source=source, status=status, lat=lat, long=long, contentname="pic")
args = [status]
allowed_param = ['status']
if lat is not None:
args.append(lat)
allowed_param.append('lat')
if long is not None:
args.append(long)
allowed_param.append('long')
if source is not None:
args.append(source)
allowed_param.append('source')
return bind_api(
path = '/statuses/upload.json',
method = 'POST',
payload_type = 'status',
require_auth = True,
allowed_param = allowed_param
)(self, *args, post_data=post_data, headers=headers)
""" statuses/reply """
reply = bind_api(
path = '/statuses/reply.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id', 'cid','comment'],
require_auth = True
)
""" statuses/repost """
repost = bind_api(
path = '/statuses/repost.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id', 'status'],
require_auth = True
)
""" statuses/destroy """
destroy_status = bind_api(
path = '/statuses/destroy/{id}.json',
method = 'DELETE',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" statuses/retweet """
retweet = bind_api(
path = '/statuses/retweet/{id}.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" statuses/retweets """
retweets = bind_api(
path = '/statuses/retweets/{id}.json',
payload_type = 'status', payload_list = True,
allowed_param = ['id', 'count'],
require_auth = True
)
""" users/show """
get_user = bind_api(
path = '/users/show.json',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name']
)
""" Get the authenticated user """
def me(self):
return self.get_user(screen_name=self.auth.get_username())
""" users/search """
search_users = bind_api(
path = '/users/search.json',
payload_type = 'user', payload_list = True,
require_auth = True,
allowed_param = ['q', 'per_page', 'page']
)
""" statuses/friends """
friends = bind_api(
path = '/statuses/friends.json',
payload_type = 'user', payload_list = True,
allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor']
)
""" statuses/followers """
followers = bind_api(
path = '/statuses/followers.json',
payload_type = 'user', payload_list = True,
allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor']
)
""" direct_messages """
direct_messages = bind_api(
path = '/direct_messages.json',
payload_type = 'direct_message', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" direct_messages/sent """
sent_direct_messages = bind_api(
path = '/direct_messages/sent.json',
payload_type = 'direct_message', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" direct_messages/new """
new_direct_message = bind_api(
path = '/direct_messages/new.json',
method = 'POST',
payload_type = 'direct_message',
allowed_param = ['id', 'screen_name', 'user_id', 'text'],
require_auth = True
)
""" direct_messages/destroy """
destroy_direct_message = bind_api(
path = '/direct_messages/destroy/{id}.json',
method = 'DELETE',
payload_type = 'direct_message',
allowed_param = ['id'],
require_auth = True
)
""" friendships/create """
create_friendship = bind_api(
path = '/friendships/create.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name', 'follow'],
require_auth = True
)
""" friendships/destroy """
destroy_friendship = bind_api(
path = '/friendships/destroy.json',
method = 'DELETE',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" friendships/exists """
exists_friendship = bind_api(
path = '/friendships/exists.json',
payload_type = 'json',
allowed_param = ['user_a', 'user_b']
)
""" friendships/show """
show_friendship = bind_api(
path = '/friendships/show.json',
payload_type = 'friendship',
allowed_param = ['source_id', 'source_screen_name',
'target_id', 'target_screen_name']
)
""" friends/ids """
friends_ids = bind_api(
path = '/friends/ids.json',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name', 'cursor', 'count'],
require_auth = True
)
""" followers/ids """
followers_ids = bind_api(
path = '/followers/ids.json',
payload_type = 'json',
allowed_param = ['id', 'page'],
)
""" account/verify_credentials """
def verify_credentials(self):
try:
return bind_api(
path = '/account/verify_credentials.json',
payload_type = 'user',
require_auth = True
)(self)
except WeibopError:
return False
""" account/rate_limit_status """
rate_limit_status = bind_api(
path = '/account/rate_limit_status.json',
payload_type = 'json'
)
""" account/update_delivery_device """
set_delivery_device = bind_api(
path = '/account/update_delivery_device.json',
method = 'POST',
allowed_param = ['device'],
payload_type = 'user',
require_auth = True
)
""" account/update_profile_colors """
update_profile_colors = bind_api(
path = '/account/update_profile_colors.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['profile_background_color', 'profile_text_color',
'profile_link_color', 'profile_sidebar_fill_color',
'profile_sidebar_border_color'],
require_auth = True
)
""" account/update_profile_image """
def update_profile_image(self, filename):
headers, post_data = API._pack_image(filename=filename, max_size=700, source=self.source)
return bind_api(
path = '/account/update_profile_image.json',
method = 'POST',
payload_type = 'user',
require_auth = True
)(self, post_data=post_data, headers=headers)
""" account/update_profile_background_image """
def update_profile_background_image(self, filename, *args, **kargs):
headers, post_data = API._pack_image(filename, 800)
bind_api(
path = '/account/update_profile_background_image.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['tile'],
require_auth = True
)(self, post_data=post_data, headers=headers)
""" account/update_profile """
update_profile = bind_api(
path = '/account/update_profile.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['name', 'url', 'location', 'description'],
require_auth = True
)
""" favorites """
favorites = bind_api(
path = '/favorites/{id}.json',
payload_type = 'status', payload_list = True,
allowed_param = ['id', 'page']
)
""" favorites/create """
create_favorite = bind_api(
path = '/favorites/create/{id}.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" favorites/destroy """
destroy_favorite = bind_api(
path = '/favorites/destroy/{id}.json',
method = 'DELETE',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" notifications/follow """
enable_notifications = bind_api(
path = '/notifications/follow.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" notifications/leave """
disable_notifications = bind_api(
path = '/notifications/leave.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" blocks/create """
create_block = bind_api(
path = '/blocks/create.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" blocks/destroy """
destroy_block = bind_api(
path = '/blocks/destroy.json',
method = 'DELETE',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" blocks/exists """
def exists_block(self, *args, **kargs):
try:
bind_api(
path = '/blocks/exists.json',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)(self, *args, **kargs)
except WeibopError:
return False
return True
""" blocks/blocking """
blocks = bind_api(
path = '/blocks/blocking.json',
payload_type = 'user', payload_list = True,
allowed_param = ['page'],
require_auth = True
)
""" blocks/blocking/ids """
blocks_ids = bind_api(
path = '/blocks/blocking/ids.json',
payload_type = 'json',
require_auth = True
)
""" statuses/repost """
report_spam = bind_api(
path = '/report_spam.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" saved_searches """
saved_searches = bind_api(
path = '/saved_searches.json',
payload_type = 'saved_search', payload_list = True,
require_auth = True
)
""" saved_searches/show """
get_saved_search = bind_api(
path = '/saved_searches/show/{id}.json',
payload_type = 'saved_search',
allowed_param = ['id'],
require_auth = True
)
""" saved_searches/create """
create_saved_search = bind_api(
path = '/saved_searches/create.json',
method = 'POST',
payload_type = 'saved_search',
allowed_param = ['query'],
require_auth = True
)
""" saved_searches/destroy """
destroy_saved_search = bind_api(
path = '/saved_searches/destroy/{id}.json',
method = 'DELETE',
payload_type = 'saved_search',
allowed_param = ['id'],
require_auth = True
)
""" help/test """
def test(self):
try:
bind_api(
path = '/help/test.json',
)(self)
except WeibopError:
return False
return True
def create_list(self, *args, **kargs):
return bind_api(
path = '/%s/lists.json' % self.auth.get_username(),
method = 'POST',
payload_type = 'list',
allowed_param = ['name', 'mode', 'description'],
require_auth = True
)(self, *args, **kargs)
def destroy_list(self, slug):
return bind_api(
path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
method = 'DELETE',
payload_type = 'list',
require_auth = True
)(self)
def update_list(self, slug, *args, **kargs):
return bind_api(
path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
method = 'POST',
payload_type = 'list',
allowed_param = ['name', 'mode', 'description'],
require_auth = True
)(self, *args, **kargs)
lists = bind_api(
path = '/{user}/lists.json',
payload_type = 'list', payload_list = True,
allowed_param = ['user', 'cursor'],
require_auth = True
)
lists_memberships = bind_api(
path = '/{user}/lists/memberships.json',
payload_type = 'list', payload_list = True,
allowed_param = ['user', 'cursor'],
require_auth = True
)
lists_subscriptions = bind_api(
path = '/{user}/lists/subscriptions.json',
payload_type = 'list', payload_list = True,
allowed_param = ['user', 'cursor'],
require_auth = True
)
list_timeline = bind_api(
path = '/{owner}/lists/{slug}/statuses.json',
payload_type = 'status', payload_list = True,
allowed_param = ['owner', 'slug', 'since_id', 'max_id', 'count', 'page']
)
get_list = bind_api(
path = '/{owner}/lists/{slug}.json',
payload_type = 'list',
allowed_param = ['owner', 'slug']
)
def add_list_member(self, slug, *args, **kargs):
return bind_api(
path = '/%s/%s/members.json' % (self.auth.get_username(), slug),
method = 'POST',
payload_type = 'list',
allowed_param = ['id'],
require_auth = True
)(self, *args, **kargs)
def remove_list_member(self, slug, *args, **kargs):
return bind_api(
path = '/%s/%s/members.json' % (self.auth.get_username(), slug),
method = 'DELETE',
payload_type = 'list',
allowed_param = ['id'],
require_auth = True
)(self, *args, **kargs)
list_members = bind_api(
path = '/{owner}/{slug}/members.json',
payload_type = 'user', payload_list = True,
allowed_param = ['owner', 'slug', 'cursor']
)
def is_list_member(self, owner, slug, user_id):
try:
return bind_api(
path = '/%s/%s/members/%s.json' % (owner, slug, user_id),
payload_type = 'user'
)(self)
except WeibopError:
return False
subscribe_list = bind_api(
path = '/{owner}/{slug}/subscribers.json',
method = 'POST',
payload_type = 'list',
allowed_param = ['owner', 'slug'],
require_auth = True
)
unsubscribe_list = bind_api(
path = '/{owner}/{slug}/subscribers.json',
method = 'DELETE',
payload_type = 'list',
allowed_param = ['owner', 'slug'],
require_auth = True
)
list_subscribers = bind_api(
path = '/{owner}/{slug}/subscribers.json',
payload_type = 'user', payload_list = True,
allowed_param = ['owner', 'slug', 'cursor']
)
def is_subscribed_list(self, owner, slug, user_id):
try:
return bind_api(
path = '/%s/%s/subscribers/%s.json' % (owner, slug, user_id),
payload_type = 'user'
)(self)
except WeibopError:
return False
""" trends/available """
trends_available = bind_api(
path = '/trends/available.json',
payload_type = 'json',
allowed_param = ['lat', 'long']
)
""" trends/location """
trends_location = bind_api(
path = '/trends/{woeid}.json',
payload_type = 'json',
allowed_param = ['woeid']
)
""" search """
search = bind_api(
search_api = True,
path = '/search.json',
payload_type = 'search_result', payload_list = True,
allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user']
)
search.pagination_mode = 'page'
""" trends """
trends = bind_api(
search_api = True,
path = '/trends.json',
payload_type = 'json'
)
""" trends/current """
trends_current = bind_api(
search_api = True,
path = '/trends/current.json',
payload_type = 'json',
allowed_param = ['exclude']
)
""" trends/daily """
trends_daily = bind_api(
search_api = True,
path = '/trends/daily.json',
payload_type = 'json',
allowed_param = ['date', 'exclude']
)
""" trends/weekly """
trends_weekly = bind_api(
search_api = True,
path = '/trends/weekly.json',
payload_type = 'json',
allowed_param = ['date', 'exclude']
)
""" Internal use only """
@staticmethod
def _pack_image(filename, max_size, source=None, status=None, lat=None, long=None, contentname="image"):
"""Pack image from file into multipart-formdata post body"""
# image must be less than 700kb in size
try:
if os.path.getsize(filename) > (max_size * 1024):
raise WeibopError('File is too big, must be less than 700kb.')
#except os.error, e:
except os.error:
raise WeibopError('Unable to access file')
# image must be gif, jpeg, or png
file_type = mimetypes.guess_type(filename)
if file_type is None:
raise WeibopError('Could not determine file type')
file_type = file_type[0]
if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
raise WeibopError('Invalid file type for image: %s' % file_type)
# build the mulitpart-formdata body
fp = open(filename, 'rb')
BOUNDARY = 'Tw3ePy'
body = []
if status is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="status"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(status)
if source is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="source"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(source)
if lat is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="lat"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(lat)
if long is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="long"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(long)
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="'+ contentname +'"; filename="%s"' % filename)
body.append('Content-Type: %s' % file_type)
body.append('Content-Transfer-Encoding: binary')
body.append('')
body.append(fp.read())
body.append('--' + BOUNDARY + '--')
body.append('')
fp.close()
body.append('--' + BOUNDARY + '--')
body.append('')
body = '\r\n'.join(body)
# build headers
headers = {
'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
'Content-Length': len(body)
}
return headers, body
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from weibopy.error import WeibopError
class Cursor(object):
"""Pagination helper class"""
def __init__(self, method, *args, **kargs):
if hasattr(method, 'pagination_mode'):
if method.pagination_mode == 'cursor':
self.iterator = CursorIterator(method, args, kargs)
else:
self.iterator = PageIterator(method, args, kargs)
else:
raise WeibopError('This method does not perform pagination')
def pages(self, limit=0):
"""Return iterator for pages"""
if limit > 0:
self.iterator.limit = limit
return self.iterator
def items(self, limit=0):
"""Return iterator for items in each page"""
i = ItemIterator(self.iterator)
i.limit = limit
return i
class BaseIterator(object):
def __init__(self, method, args, kargs):
self.method = method
self.args = args
self.kargs = kargs
self.limit = 0
def next(self):
raise NotImplementedError
def prev(self):
raise NotImplementedError
def __iter__(self):
return self
class CursorIterator(BaseIterator):
def __init__(self, method, args, kargs):
BaseIterator.__init__(self, method, args, kargs)
self.next_cursor = -1
self.prev_cursor = 0
self.count = 0
def next(self):
if self.next_cursor == 0 or (self.limit and self.count == self.limit):
raise StopIteration
data, cursors = self.method(
cursor=self.next_cursor, *self.args, **self.kargs
)
self.prev_cursor, self.next_cursor = cursors
if len(data) == 0:
raise StopIteration
self.count += 1
return data
def prev(self):
if self.prev_cursor == 0:
raise WeibopError('Can not page back more, at first page')
data, self.next_cursor, self.prev_cursor = self.method(
cursor=self.prev_cursor, *self.args, **self.kargs
)
self.count -= 1
return data
class PageIterator(BaseIterator):
def __init__(self, method, args, kargs):
BaseIterator.__init__(self, method, args, kargs)
self.current_page = 0
def next(self):
self.current_page += 1
items = self.method(page=self.current_page, *self.args, **self.kargs)
if len(items) == 0 or (self.limit > 0 and self.current_page > self.limit):
raise StopIteration
return items
def prev(self):
if (self.current_page == 1):
raise WeibopError('Can not page back more, at first page')
self.current_page -= 1
return self.method(page=self.current_page, *self.args, **self.kargs)
class ItemIterator(BaseIterator):
def __init__(self, page_iterator):
self.page_iterator = page_iterator
self.limit = 0
self.current_page = None
self.page_index = -1
self.count = 0
def next(self):
if self.limit > 0 and self.count == self.limit:
raise StopIteration
if self.current_page is None or self.page_index == len(self.current_page) - 1:
# Reached end of current page, get the next page...
self.current_page = self.page_iterator.next()
self.page_index = -1
self.page_index += 1
self.count += 1
return self.current_page[self.page_index]
def prev(self):
if self.current_page is None:
raise WeibopError('Can not go back more, at first page')
if self.page_index == 0:
# At the beginning of the current page, move to next...
self.current_page = self.page_iterator.prev()
self.page_index = len(self.current_page)
if self.page_index == 0:
raise WeibopError('No more items')
self.page_index -= 1
self.count -= 1
return self.current_page[self.page_index]
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import time
import threading
import os
import cPickle as pickle
try:
import hashlib
except ImportError:
# python 2.4
import md5 as hashlib
try:
import fcntl
except ImportError:
# Probably on a windows system
# TODO: use win32file
pass
class Cache(object):
"""Cache interface"""
def __init__(self, timeout=60):
"""Initialize the cache
timeout: number of seconds to keep a cached entry
"""
self.timeout = timeout
def store(self, key, value):
"""Add new record to cache
key: entry key
value: data of entry
"""
raise NotImplementedError
def get(self, key, timeout=None):
"""Get cached entry if exists and not expired
key: which entry to get
timeout: override timeout with this value [optional]
"""
raise NotImplementedError
def count(self):
"""Get count of entries currently stored in cache"""
raise NotImplementedError
def cleanup(self):
"""Delete any expired entries in cache."""
raise NotImplementedError
def flush(self):
"""Delete all cached entries"""
raise NotImplementedError
class MemoryCache(Cache):
"""In-memory cache"""
def __init__(self, timeout=60):
Cache.__init__(self, timeout)
self._entries = {}
self.lock = threading.Lock()
def __getstate__(self):
# pickle
return {'entries': self._entries, 'timeout': self.timeout}
def __setstate__(self, state):
# unpickle
self.lock = threading.Lock()
self._entries = state['entries']
self.timeout = state['timeout']
def _is_expired(self, entry, timeout):
return timeout > 0 and (time.time() - entry[0]) >= timeout
def store(self, key, value):
self.lock.acquire()
self._entries[key] = (time.time(), value)
self.lock.release()
def get(self, key, timeout=None):
self.lock.acquire()
try:
# check to see if we have this key
entry = self._entries.get(key)
if not entry:
# no hit, return nothing
return None
# use provided timeout in arguments if provided
# otherwise use the one provided during init.
if timeout is None:
timeout = self.timeout
# make sure entry is not expired
if self._is_expired(entry, timeout):
# entry expired, delete and return nothing
del self._entries[key]
return None
# entry found and not expired, return it
return entry[1]
finally:
self.lock.release()
def count(self):
return len(self._entries)
def cleanup(self):
self.lock.acquire()
try:
for k, v in self._entries.items():
if self._is_expired(v, self.timeout):
del self._entries[k]
finally:
self.lock.release()
def flush(self):
self.lock.acquire()
self._entries.clear()
self.lock.release()
class FileCache(Cache):
"""File-based cache"""
# locks used to make cache thread-safe
cache_locks = {}
def __init__(self, cache_dir, timeout=60):
Cache.__init__(self, timeout)
if os.path.exists(cache_dir) is False:
os.mkdir(cache_dir)
self.cache_dir = cache_dir
if cache_dir in FileCache.cache_locks:
self.lock = FileCache.cache_locks[cache_dir]
else:
self.lock = threading.Lock()
FileCache.cache_locks[cache_dir] = self.lock
if os.name == 'posix':
self._lock_file = self._lock_file_posix
self._unlock_file = self._unlock_file_posix
elif os.name == 'nt':
self._lock_file = self._lock_file_win32
self._unlock_file = self._unlock_file_win32
else:
print 'Warning! FileCache locking not supported on this system!'
self._lock_file = self._lock_file_dummy
self._unlock_file = self._unlock_file_dummy
def _get_path(self, key):
md5 = hashlib.md5()
md5.update(key)
return os.path.join(self.cache_dir, md5.hexdigest())
def _lock_file_dummy(self, path, exclusive=True):
return None
def _unlock_file_dummy(self, lock):
return
def _lock_file_posix(self, path, exclusive=True):
lock_path = path + '.lock'
if exclusive is True:
f_lock = open(lock_path, 'w')
fcntl.lockf(f_lock, fcntl.LOCK_EX)
else:
f_lock = open(lock_path, 'r')
fcntl.lockf(f_lock, fcntl.LOCK_SH)
if os.path.exists(lock_path) is False:
f_lock.close()
return None
return f_lock
def _unlock_file_posix(self, lock):
lock.close()
def _lock_file_win32(self, path, exclusive=True):
# TODO: implement
return None
def _unlock_file_win32(self, lock):
# TODO: implement
return
def _delete_file(self, path):
os.remove(path)
if os.path.exists(path + '.lock'):
os.remove(path + '.lock')
def store(self, key, value):
path = self._get_path(key)
self.lock.acquire()
try:
# acquire lock and open file
f_lock = self._lock_file(path)
datafile = open(path, 'wb')
# write data
pickle.dump((time.time(), value), datafile)
# close and unlock file
datafile.close()
self._unlock_file(f_lock)
finally:
self.lock.release()
def get(self, key, timeout=None):
return self._get(self._get_path(key), timeout)
def _get(self, path, timeout):
if os.path.exists(path) is False:
# no record
return None
self.lock.acquire()
try:
# acquire lock and open
f_lock = self._lock_file(path, False)
datafile = open(path, 'rb')
# read pickled object
created_time, value = pickle.load(datafile)
datafile.close()
# check if value is expired
if timeout is None:
timeout = self.timeout
if timeout > 0 and (time.time() - created_time) >= timeout:
# expired! delete from cache
value = None
self._delete_file(path)
# unlock and return result
self._unlock_file(f_lock)
return value
finally:
self.lock.release()
def count(self):
c = 0
for entry in os.listdir(self.cache_dir):
if entry.endswith('.lock'):
continue
c += 1
return c
def cleanup(self):
for entry in os.listdir(self.cache_dir):
if entry.endswith('.lock'):
continue
self._get(os.path.join(self.cache_dir, entry), None)
def flush(self):
for entry in os.listdir(self.cache_dir):
if entry.endswith('.lock'):
continue
self._delete_file(os.path.join(self.cache_dir, entry))
| Python |
#coding:utf8
import os, sys
from bottle import route, run, debug, template, request, validate, error, response, redirect
# only needed when you run Bottle on mod_wsgi
from bottle import default_app
from y_home import *
from y_apply import *
from y_admin import *
from y_login import *
#reload(sys)
#sys.setdefaultencoding('utf-8')
debug(True)
def main():
run(reloader=True);
if __name__ == "__main__":
# Interactive mode
main()
else:
# Mod WSGI launch
os.chdir(os.path.dirname(__file__))
application = default_app()
| Python |
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies other than the
Python Standard Library.
Homepage and documentation: http://bottle.paws.de/
Licence (MIT)
-------------
Copyright (c) 2009, Marcel Hellkamp.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Example
-------
This is an example::
from bottle import route, run, request, response, static_file, abort
@route('/')
def hello_world():
return 'Hello World!'
@route('/hello/:name')
def hello_name(name):
return 'Hello %s!' % name
@route('/hello', method='POST')
def hello_post():
name = request.POST['name']
return 'Hello %s!' % name
@route('/static/:filename#.*#')
def static(filename):
return static_file(filename, root='/path/to/static/files/')
run(host='localhost', port=8080)
"""
from __future__ import with_statement
__author__ = 'Marcel Hellkamp'
__version__ = '0.8.5'
__license__ = 'MIT'
import base64
import cgi
import email.utils
import functools
import hmac
import inspect
import itertools
import mimetypes
import os
import re
import subprocess
import sys
import thread
import threading
import time
import tokenize
import tempfile
from Cookie import SimpleCookie
from tempfile import TemporaryFile
from traceback import format_exc
from urllib import quote as urlquote
from urlparse import urlunsplit, urljoin
try:
from collections import MutableMapping as DictMixin
except ImportError: # pragma: no cover
from UserDict import DictMixin
try:
from urlparse import parse_qs
except ImportError: # pragma: no cover
from cgi import parse_qs
try:
import cPickle as pickle
except ImportError: # pragma: no cover
import pickle
try:
try:
from json import dumps as json_dumps
except ImportError: # pragma: no cover
from simplejson import dumps as json_dumps
except ImportError: # pragma: no cover
json_dumps = None
if sys.version_info >= (3,0,0): # pragma: no cover
# See Request.POST
from io import BytesIO
from io import TextIOWrapper
class NCTextIOWrapper(TextIOWrapper):
''' Garbage collecting an io.TextIOWrapper(buffer) instance closes the
wrapped buffer. This subclass keeps it open. '''
def close(self): pass
StringType = bytes
def touni(x, enc='utf8'): # Convert anything to unicode (py3)
return str(x, encoding=enc) if isinstance(x, bytes) else str(x)
else:
from StringIO import StringIO as BytesIO
from types import StringType
NCTextIOWrapper = None
def touni(x, enc='utf8'): # Convert anything to unicode (py2)
return x if isinstance(x, unicode) else unicode(str(x), encoding=enc)
def tob(data, enc='utf8'): # Convert strings to bytes (py2 and py3)
return data.encode(enc) if isinstance(data, unicode) else data
# Background compatibility
import warnings
def depr(message, critical=False):
if critical: raise DeprecationWarning(message)
warnings.warn(message, DeprecationWarning, stacklevel=3)
# Exceptions and Events
class BottleException(Exception):
""" A base class for exceptions used by bottle. """
pass
class HTTPResponse(BottleException):
""" Used to break execution and immediately finish the response """
def __init__(self, output='', status=200, header=None):
super(BottleException, self).__init__("HTTP Response %d" % status)
self.status = int(status)
self.output = output
self.headers = HeaderDict(header) if header else None
def apply(self, response):
if self.headers:
for key, value in self.headers.iterallitems():
response.headers[key] = value
response.status = self.status
class HTTPError(HTTPResponse):
""" Used to generate an error page """
def __init__(self, code=500, output='Unknown Error', exception=None, traceback=None, header=None):
super(HTTPError, self).__init__(output, code, header)
self.exception = exception
self.traceback = traceback
def __repr__(self):
return ''.join(ERROR_PAGE_TEMPLATE.render(e=self))
# Routing
class RouteError(BottleException):
""" This is a base class for all routing related exceptions """
class RouteSyntaxError(RouteError):
""" The route parser found something not supported by this router """
class RouteBuildError(RouteError):
""" The route could not been build """
class Route(object):
''' Represents a single route and can parse the dynamic route syntax '''
syntax = re.compile(r'(.*?)(?<!\\):([a-zA-Z_]+)?(?:#(.*?)#)?')
default = '[^/]+'
def __init__(self, route, target=None, name=None, static=False):
""" Create a Route. The route string may contain `:key`,
`:key#regexp#` or `:#regexp#` tokens for each dynamic part of the
route. These can be escaped with a backslash infront of the `:`
and are compleately ignored if static is true. A name may be used
to refer to this route later (depends on Router)
"""
self.route = route
self.target = target
self.name = name
if static:
self.route = self.route.replace(':','\\:')
self._tokens = None
def tokens(self):
""" Return a list of (type, value) tokens. """
if not self._tokens:
self._tokens = list(self.tokenise(self.route))
return self._tokens
@classmethod
def tokenise(cls, route):
''' Split a string into an iterator of (type, value) tokens. '''
match = None
for match in cls.syntax.finditer(route):
pre, name, rex = match.groups()
if pre: yield ('TXT', pre.replace('\\:',':'))
if rex and name: yield ('VAR', (rex, name))
elif name: yield ('VAR', (cls.default, name))
elif rex: yield ('ANON', rex)
if not match:
yield ('TXT', route.replace('\\:',':'))
elif match.end() < len(route):
yield ('TXT', route[match.end():].replace('\\:',':'))
def group_re(self):
''' Return a regexp pattern with named groups '''
out = ''
for token, data in self.tokens():
if token == 'TXT': out += re.escape(data)
elif token == 'VAR': out += '(?P<%s>%s)' % (data[1], data[0])
elif token == 'ANON': out += '(?:%s)' % data
return out
def flat_re(self):
''' Return a regexp pattern with non-grouping parentheses '''
rf = lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:'
return re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', rf, self.group_re())
def format_str(self):
''' Return a format string with named fields. '''
out, i = '', 0
for token, value in self.tokens():
if token == 'TXT': out += value.replace('%','%%')
elif token == 'ANON': out += '%%(anon%d)s' % i; i+=1
elif token == 'VAR': out += '%%(%s)s' % value[1]
return out
@property
def static(self):
return not self.is_dynamic()
def is_dynamic(self):
''' Return true if the route contains dynamic parts '''
for token, value in self.tokens():
if token != 'TXT':
return True
return False
def __repr__(self):
return "<Route(%s) />" % repr(self.route)
def __eq__(self, other):
return self.route == other.route
class Router(object):
''' A route associates a string (e.g. URL) with an object (e.g. function)
Some dynamic routes may extract parts of the string and provide them as
a dictionary. This router matches a string against multiple routes and
returns the associated object along with the extracted data.
'''
def __init__(self):
self.routes = [] # List of all installed routes
self.named = {} # Cache for named routes and their format strings
self.static = {} # Cache for static routes
self.dynamic = [] # Search structure for dynamic routes
def add(self, route, target=None, **ka):
""" Add a route->target pair or a :class:`Route` object to the Router.
Return the Route object. See :class:`Route` for details.
"""
if not isinstance(route, Route):
route = Route(route, target, **ka)
if self.get_route(route):
return RouteError('Route %s is not uniqe.' % route)
self.routes.append(route)
return route
def get_route(self, route, target=None, **ka):
''' Get a route from the router by specifying either the same
parameters as in :meth:`add` or comparing to an instance of
:class:`Route`. Note that not all parameters are considered by the
compare function. '''
if not isinstance(route, Route):
route = Route(route, **ka)
for known in self.routes:
if route == known:
return known
return None
def match(self, uri):
''' Match an URI and return a (target, urlargs) tuple '''
if uri in self.static:
return self.static[uri], {}
for combined, subroutes in self.dynamic:
match = combined.match(uri)
if not match: continue
target, args_re = subroutes[match.lastindex - 1]
args = args_re.match(uri).groupdict() if args_re else {}
return target, args
return None, {}
def build(self, _name, **args):
''' Build an URI out of a named route and values for te wildcards. '''
try:
return self.named[_name] % args
except KeyError:
raise RouteBuildError("No route found with name '%s'." % _name)
def compile(self):
''' Build the search structures. Call this before actually using the
router.'''
self.named = {}
self.static = {}
self.dynamic = []
for route in self.routes:
if route.name:
self.named[route.name] = route.format_str()
if route.static:
self.static[route.route] = route.target
continue
gpatt = route.group_re()
fpatt = route.flat_re()
try:
gregexp = re.compile('^(%s)$' % gpatt) if '(?P' in gpatt else None
combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, fpatt)
self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1])
self.dynamic[-1][1].append((route.target, gregexp))
except (AssertionError, IndexError), e: # AssertionError: Too many groups
self.dynamic.append((re.compile('(^%s$)'%fpatt),[(route.target, gregexp)]))
except re.error, e:
raise RouteSyntaxError("Could not add Route: %s (%s)" % (route, e))
def __eq__(self, other):
return self.routes == other.routes
# WSGI abstraction: Application, Request and Response objects
class Bottle(object):
""" WSGI application """
def __init__(self, catchall=True, autojson=True, config=None):
""" Create a new bottle instance.
You usually don't do that. Use `bottle.app.push()` instead.
"""
self.routes = Router()
self.mounts = {}
self.error_handler = {}
self.catchall = catchall
self.config = config or {}
self.serve = True
self.castfilter = []
if autojson and json_dumps:
self.add_filter(dict, dict2json)
def optimize(self, *a, **ka):
depr("Bottle.optimize() is obsolete.")
def mount(self, app, script_path):
''' Mount a Bottle application to a specific URL prefix '''
if not isinstance(app, Bottle):
raise TypeError('Only Bottle instances are supported for now.')
script_path = '/'.join(filter(None, script_path.split('/')))
path_depth = script_path.count('/') + 1
if not script_path:
raise TypeError('Empty script_path. Perhaps you want a merge()?')
for other in self.mounts:
if other.startswith(script_path):
raise TypeError('Conflict with existing mount: %s' % other)
@self.route('/%s/:#.*#' % script_path, method="ANY")
def mountpoint():
request.path_shift(path_depth)
return app.handle(request.path, request.method)
self.mounts[script_path] = app
def add_filter(self, ftype, func):
''' Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applied to it. '''
if not isinstance(ftype, type):
raise TypeError("Expected type object, got %s" % type(ftype))
self.castfilter = [(t, f) for (t, f) in self.castfilter if t != ftype]
self.castfilter.append((ftype, func))
self.castfilter.sort()
def match_url(self, path, method='GET'):
""" Find a callback bound to a path and a specific HTTP method.
Return (callback, param) tuple or raise HTTPError.
method: HEAD falls back to GET. All methods fall back to ANY.
"""
path, method = path.strip().lstrip('/'), method.upper()
callbacks, args = self.routes.match(path)
if not callbacks:
raise HTTPError(404, "Not found: " + path)
if method in callbacks:
return callbacks[method], args
if method == 'HEAD' and 'GET' in callbacks:
return callbacks['GET'], args
if 'ANY' in callbacks:
return callbacks['ANY'], args
allow = [m for m in callbacks if m != 'ANY']
if 'GET' in allow and 'HEAD' not in allow:
allow.append('HEAD')
raise HTTPError(405, "Method not allowed.",
header=[('Allow',",".join(allow))])
def get_url(self, routename, **kargs):
""" Return a string that matches a named route """
scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
location = self.routes.build(routename, **kargs).lstrip('/')
return urljoin(urljoin('/', scriptname), location)
def route(self, path=None, method='GET', **kargs):
""" Decorator: bind a function to a GET request path.
If the path parameter is None, the signature of the decorated
function is used to generate the paths. See yieldroutes()
for details.
The method parameter (default: GET) specifies the HTTP request
method to listen to. You can specify a list of methods too.
"""
def wrapper(callback):
routes = [path] if path else yieldroutes(callback)
methods = method.split(';') if isinstance(method, str) else method
for r in routes:
for m in methods:
r, m = r.strip().lstrip('/'), m.strip().upper()
old = self.routes.get_route(r, **kargs)
if old:
old.target[m] = callback
else:
self.routes.add(r, {m: callback}, **kargs)
self.routes.compile()
return callback
return wrapper
def get(self, path=None, method='GET', **kargs):
""" Decorator: Bind a function to a GET request path.
See :meth:'route' for details. """
return self.route(path, method, **kargs)
def post(self, path=None, method='POST', **kargs):
""" Decorator: Bind a function to a POST request path.
See :meth:'route' for details. """
return self.route(path, method, **kargs)
def put(self, path=None, method='PUT', **kargs):
""" Decorator: Bind a function to a PUT request path.
See :meth:'route' for details. """
return self.route(path, method, **kargs)
def delete(self, path=None, method='DELETE', **kargs):
""" Decorator: Bind a function to a DELETE request path.
See :meth:'route' for details. """
return self.route(path, method, **kargs)
def error(self, code=500):
""" Decorator: Registrer an output handler for a HTTP error code"""
def wrapper(handler):
self.error_handler[int(code)] = handler
return handler
return wrapper
def handle(self, url, method):
""" Execute the handler bound to the specified url and method and return
its output. If catchall is true, exceptions are catched and returned as
HTTPError(500) objects. """
if not self.serve:
return HTTPError(503, "Server stopped")
try:
handler, args = self.match_url(url, method)
return handler(**args)
except HTTPResponse, e:
return e
except Exception, e:
if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\
or not self.catchall:
raise
return HTTPError(500, 'Unhandled exception', e, format_exc(10))
def _cast(self, out, request, response, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Filtered types (recursive, because they may return anything)
for testtype, filterfunc in self.castfilter:
if isinstance(out, testtype):
return self._cast(filterfunc(out), request, response)
# Empty output is done here
if not out:
response.headers['Content-Length'] = 0
return []
# Join lists of byte or unicode strings. Mixed lists are NOT supported
if isinstance(out, (tuple, list))\
and isinstance(out[0], (StringType, unicode)):
out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
# Encode unicode strings
if isinstance(out, unicode):
out = out.encode(response.charset)
# Byte Strings are just returned
if isinstance(out, StringType):
response.headers['Content-Length'] = str(len(out))
return [out]
# HTTPError or HTTPException (recursive, because they may wrap anything)
if isinstance(out, HTTPError):
out.apply(response)
return self._cast(self.error_handler.get(out.status, repr)(out), request, response)
if isinstance(out, HTTPResponse):
out.apply(response)
return self._cast(out.output, request, response)
# File-like objects.
if hasattr(out, 'read'):
if 'wsgi.file_wrapper' in request.environ:
return request.environ['wsgi.file_wrapper'](out)
elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
return WSGIFileWrapper(out)
# Handle Iterables. We peek into them to detect their inner type.
try:
out = iter(out)
first = out.next()
while not first:
first = out.next()
except StopIteration:
return self._cast('', request, response)
except HTTPResponse, e:
first = e
except Exception, e:
first = HTTPError(500, 'Unhandled exception', e, format_exc(10))
if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\
or not self.catchall:
raise
# These are the inner types allowed in iterator or generator objects.
if isinstance(first, HTTPResponse):
return self._cast(first, request, response)
if isinstance(first, StringType):
return itertools.chain([first], out)
if isinstance(first, unicode):
return itertools.imap(lambda x: x.encode(response.charset),
itertools.chain([first], out))
return self._cast(HTTPError(500, 'Unsupported response type: %s'\
% type(first)), request, response)
def __call__(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
environ['bottle.app'] = self
request.bind(environ)
response.bind(self)
out = self.handle(request.path, request.method)
out = self._cast(out, request, response)
# rfc2616 section 4.3
if response.status in (100, 101, 204, 304) or request.method == 'HEAD':
out = []
status = '%d %s' % (response.status, HTTP_CODES[response.status])
start_response(status, response.headerlist)
return out
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception, e:
if not self.catchall:
raise
err = '<h1>Critical error while processing request: %s</h1>' \
% environ.get('PATH_INFO', '/')
if DEBUG:
err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e)
err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10)
environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html
start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')])
return [tob(err)]
class Request(threading.local, DictMixin):
""" Represents a single HTTP request using thread-local attributes.
The Request object wraps a WSGI environment and can be used as such.
"""
def __init__(self, environ=None, config=None):
""" Create a new Request instance.
You usually don't do this but use the global `bottle.request`
instance instead.
"""
self.bind(environ or {}, config)
def bind(self, environ, config=None):
""" Bind a new WSGI enviroment.
This is done automatically for the global `bottle.request`
instance on every request.
"""
self.environ = environ
self.config = config or {}
# These attributes are used anyway, so it is ok to compute them here
self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/')
self.method = environ.get('REQUEST_METHOD', 'GET').upper()
@property
def _environ(self):
depr("Request._environ renamed to Request.environ")
return self.environ
def copy(self):
''' Returns a copy of self '''
return Request(self.environ.copy(), self.config)
def path_shift(self, shift=1):
''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:param shift: The number of path fragments to shift. May be negative to
change the shift direction. (default: 1)
'''
script_name = self.environ.get('SCRIPT_NAME','/')
self['SCRIPT_NAME'], self.path = path_shift(script_name, self.path, shift)
self['PATH_INFO'] = self.path
def __getitem__(self, key): return self.environ[key]
def __delitem__(self, key): self[key] = ""; del(self.environ[key])
def __iter__(self): return iter(self.environ)
def __len__(self): return len(self.environ)
def keys(self): return self.environ.keys()
def __setitem__(self, key, value):
""" Shortcut for Request.environ.__setitem__ """
self.environ[key] = value
todelete = []
if key in ('PATH_INFO','REQUEST_METHOD'):
self.bind(self.environ, self.config)
elif key == 'wsgi.input': todelete = ('body','forms','files','params')
elif key == 'QUERY_STRING': todelete = ('get','params')
elif key.startswith('HTTP_'): todelete = ('headers', 'cookies')
for key in todelete:
if 'bottle.' + key in self.environ:
del self.environ['bottle.' + key]
@property
def query_string(self):
""" The content of the QUERY_STRING environment variable. """
return self.environ.get('QUERY_STRING', '')
@property
def fullpath(self):
""" Request path including SCRIPT_NAME (if present) """
return self.environ.get('SCRIPT_NAME', '').rstrip('/') + self.path
@property
def url(self):
""" Full URL as requested by the client (computed).
This value is constructed out of different environment variables
and includes scheme, host, port, scriptname, path and query string.
"""
scheme = self.environ.get('wsgi.url_scheme', 'http')
host = self.environ.get('HTTP_X_FORWARDED_HOST', self.environ.get('HTTP_HOST', None))
if not host:
host = self.environ.get('SERVER_NAME')
port = self.environ.get('SERVER_PORT', '80')
if scheme + port not in ('https443', 'http80'):
host += ':' + port
parts = (scheme, host, urlquote(self.fullpath), self.query_string, '')
return urlunsplit(parts)
@property
def content_length(self):
""" Content-Length header as an integer, -1 if not specified """
return int(self.environ.get('CONTENT_LENGTH','') or -1)
@property
def header(self):
''' :class:`HeaderDict` filled with request headers.
HeaderDict keys are case insensitive str.title()d
'''
if 'bottle.headers' not in self.environ:
header = self.environ['bottle.headers'] = HeaderDict()
for key, value in self.environ.iteritems():
if key.startswith('HTTP_'):
key = key[5:].replace('_','-').title()
header[key] = value
return self.environ['bottle.headers']
@property
def GET(self):
""" The QUERY_STRING parsed into a MultiDict.
Keys and values are strings. Multiple values per key are possible.
See MultiDict for details.
"""
if 'bottle.get' not in self.environ:
data = parse_qs(self.query_string, keep_blank_values=True)
get = self.environ['bottle.get'] = MultiDict()
for key, values in data.iteritems():
for value in values:
get[key] = value
return self.environ['bottle.get']
@property
def POST(self):
""" Property: The HTTP POST body parsed into a MultiDict.
This supports urlencoded and multipart POST requests. Multipart
is commonly used for file uploads and may result in some of the
values being cgi.FieldStorage objects instead of strings.
Multiple values per key are possible. See MultiDict for details.
"""
if 'bottle.post' not in self.environ:
self.environ['bottle.post'] = MultiDict()
self.environ['bottle.forms'] = MultiDict()
self.environ['bottle.files'] = MultiDict()
safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
if key in self.environ: safe_env[key] = self.environ[key]
if NCTextIOWrapper:
fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n')
# TODO: Content-Length may be wrong now. Does cgi.FieldStorage
# use it at all? I think not, because all tests pass.
else:
fb = self.body
data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True)
for item in data.list or []:
if item.filename:
self.environ['bottle.post'][item.name] = item
self.environ['bottle.files'][item.name] = item
else:
self.environ['bottle.post'][item.name] = item.value
self.environ['bottle.forms'][item.name] = item.value
return self.environ['bottle.post']
@property
def forms(self):
""" Property: HTTP POST form data parsed into a MultiDict. """
if 'bottle.forms' not in self.environ: self.POST
return self.environ['bottle.forms']
@property
def files(self):
""" Property: HTTP POST file uploads parsed into a MultiDict. """
if 'bottle.files' not in self.environ: self.POST
return self.environ['bottle.files']
@property
def params(self):
""" A combined MultiDict with POST and GET parameters. """
if 'bottle.params' not in self.environ:
self.environ['bottle.params'] = MultiDict(self.GET)
self.environ['bottle.params'].update(dict(self.forms))
return self.environ['bottle.params']
@property
def body(self):
""" The HTTP request body as a seekable buffer object.
This property returns a copy of the `wsgi.input` stream and should
be used instead of `environ['wsgi.input']`.
"""
if 'bottle.body' not in self.environ:
maxread = max(0, self.content_length)
stream = self.environ['wsgi.input']
body = BytesIO() if maxread < MEMFILE_MAX else TemporaryFile(mode='w+b')
while maxread > 0:
part = stream.read(min(maxread, MEMFILE_MAX))
if not part: #TODO: Wrong content_length. Error? Do nothing?
break
body.write(part)
maxread -= len(part)
self.environ['wsgi.input'] = body
self.environ['bottle.body'] = body
self.environ['bottle.body'].seek(0)
return self.environ['bottle.body']
@property
def auth(self): #TODO: Tests and docs. Add support for digest. namedtuple?
""" HTTP authorisation data as a (user, passwd) tuple. (experimental)
This implementation currently only supports basic auth and returns
None on errors.
"""
return parse_auth(self.environ.get('HTTP_AUTHORIZATION',''))
@property
def COOKIES(self):
""" Cookie information parsed into a dictionary.
Secure cookies are NOT decoded automatically. See
Request.get_cookie() for details.
"""
if 'bottle.cookies' not in self.environ:
raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
self.environ['bottle.cookies'] = {}
for cookie in raw_dict.itervalues():
self.environ['bottle.cookies'][cookie.key] = cookie.value
return self.environ['bottle.cookies']
def get_cookie(self, name, secret=None):
""" Return the (decoded) value of a cookie. """
value = self.COOKIES.get(name)
dec = cookie_decode(value, secret) if secret else None
return dec or value
@property
def is_ajax(self):
''' True if the request was generated using XMLHttpRequest '''
#TODO: write tests
return self.header.get('X-Requested-With') == 'XMLHttpRequest'
class Response(threading.local):
""" Represents a single HTTP response using thread-local attributes.
"""
def __init__(self, config=None):
self.bind(config)
def bind(self, config=None):
""" Resets the Response object to its factory defaults. """
self._COOKIES = None
self.status = 200
self.headers = HeaderDict()
self.content_type = 'text/html; charset=UTF-8'
self.config = config or {}
@property
def header(self):
depr("Response.header renamed to Response.headers")
return self.headers
def copy(self):
''' Returns a copy of self '''
copy = Response(self.config)
copy.status = self.status
copy.headers = self.headers.copy()
copy.content_type = self.content_type
return copy
def wsgiheader(self):
''' Returns a wsgi conform list of header/value pairs. '''
for c in self.COOKIES.values():
if c.OutputString() not in self.headers.getall('Set-Cookie'):
self.headers.append('Set-Cookie', c.OutputString())
# rfc2616 section 10.2.3, 10.3.5
if self.status in (204, 304) and 'content-type' in self.headers:
del self.headers['content-type']
if self.status == 304:
for h in ('allow', 'content-encoding', 'content-language',
'content-length', 'content-md5', 'content-range',
'content-type', 'last-modified'): # + c-location, expires?
if h in self.headers:
del self.headers[h]
return list(self.headers.iterallitems())
headerlist = property(wsgiheader)
@property
def charset(self):
""" Return the charset specified in the content-type header.
This defaults to `UTF-8`.
"""
if 'charset=' in self.content_type:
return self.content_type.split('charset=')[-1].split(';')[0].strip()
return 'UTF-8'
@property
def COOKIES(self):
""" A dict-like SimpleCookie instance. Use Response.set_cookie() instead. """
if not self._COOKIES:
self._COOKIES = SimpleCookie()
return self._COOKIES
def set_cookie(self, key, value, secret=None, **kargs):
""" Add a new cookie with various options.
If the cookie value is not a string, a secure cookie is created.
Possible options are:
expires, path, comment, domain, max_age, secure, version, httponly
See http://de.wikipedia.org/wiki/HTTP-Cookie#Aufbau for details
"""
if not isinstance(value, basestring):
if not secret:
raise TypeError('Cookies must be strings when secret is not set')
value = cookie_encode(value, secret).decode('ascii') #2to3 hack
self.COOKIES[key] = value
for k, v in kargs.iteritems():
self.COOKIES[key][k.replace('_', '-')] = v
def get_content_type(self):
""" Current 'Content-Type' header. """
return self.headers['Content-Type']
def set_content_type(self, value):
self.headers['Content-Type'] = value
content_type = property(get_content_type, set_content_type, None,
get_content_type.__doc__)
# Data Structures
class MultiDict(DictMixin):
""" A dict that remembers old values for each key """
# collections.MutableMapping would be better for Python >= 2.6
def __init__(self, *a, **k):
self.dict = dict()
for k, v in dict(*a, **k).iteritems():
self[k] = v
def __len__(self): return len(self.dict)
def __iter__(self): return iter(self.dict)
def __contains__(self, key): return key in self.dict
def __delitem__(self, key): del self.dict[key]
def keys(self): return self.dict.keys()
def __getitem__(self, key): return self.get(key, KeyError, -1)
def __setitem__(self, key, value): self.append(key, value)
def append(self, key, value): self.dict.setdefault(key, []).append(value)
def replace(self, key, value): self.dict[key] = [value]
def getall(self, key): return self.dict.get(key) or []
def get(self, key, default=None, index=-1):
if key not in self.dict and default != KeyError:
return [default][index]
return self.dict[key][index]
def iterallitems(self):
for key, values in self.dict.iteritems():
for value in values:
yield key, value
class HeaderDict(MultiDict):
""" Same as :class:`MultiDict`, but title()s the keys and overwrites by default. """
def __contains__(self, key): return MultiDict.__contains__(self, self.httpkey(key))
def __getitem__(self, key): return MultiDict.__getitem__(self, self.httpkey(key))
def __delitem__(self, key): return MultiDict.__delitem__(self, self.httpkey(key))
def __setitem__(self, key, value): self.replace(key, value)
def get(self, key, default=None, index=-1): return MultiDict.get(self, self.httpkey(key), default, index)
def append(self, key, value): return MultiDict.append(self, self.httpkey(key), str(value))
def replace(self, key, value): return MultiDict.replace(self, self.httpkey(key), str(value))
def getall(self, key): return MultiDict.getall(self, self.httpkey(key))
def httpkey(self, key): return str(key).replace('_','-').title()
class AppStack(list):
""" A stack implementation. """
def __call__(self):
""" Return the current default app. """
return self[-1]
def push(self, value=None):
""" Add a new Bottle instance to the stack """
if not isinstance(value, Bottle):
value = Bottle()
self.append(value)
return value
class WSGIFileWrapper(object):
def __init__(self, fp, buffer_size=1024*64):
self.fp, self.buffer_size = fp, buffer_size
for attr in ('fileno', 'close', 'read', 'readlines'):
if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))
def __iter__(self):
read, buff = self.fp.read, self.buffer_size
while True:
part = read(buff)
if not part: break
yield part
# Module level functions
# Output filter
def dict2json(d):
response.content_type = 'application/json'
return json_dumps(d)
def abort(code=500, text='Unknown Error: Appliction stopped.'):
""" Aborts execution and causes a HTTP error. """
raise HTTPError(code, text)
def redirect(url, code=303):
""" Aborts execution and causes a 303 redirect """
scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/'
location = urljoin(request.url, urljoin(scriptname, url))
raise HTTPResponse("", status=code, header=dict(Location=location))
def send_file(*a, **k): #BC 0.6.4
""" Raises the output of static_file(). (deprecated) """
raise static_file(*a, **k)
def static_file(filename, root, guessmime=True, mimetype=None, download=False):
""" Opens a file in a safe way and returns a HTTPError object with status
code 200, 305, 401 or 404. Sets Content-Type, Content-Length and
Last-Modified header. Obeys If-Modified-Since header and HEAD requests.
"""
root = os.path.abspath(root) + os.sep
filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
header = dict()
if not filename.startswith(root):
return HTTPError(403, "Access denied.")
if not os.path.exists(filename) or not os.path.isfile(filename):
return HTTPError(404, "File does not exist.")
if not os.access(filename, os.R_OK):
return HTTPError(403, "You do not have permission to access this file.")
if not mimetype and guessmime:
header['Content-Type'] = mimetypes.guess_type(filename)[0]
else:
header['Content-Type'] = mimetype if mimetype else 'text/plain'
if download == True:
download = os.path.basename(filename)
if download:
header['Content-Disposition'] = 'attachment; filename="%s"' % download
stats = os.stat(filename)
lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
header['Last-Modified'] = lm
ims = request.environ.get('HTTP_IF_MODIFIED_SINCE')
if ims:
ims = ims.split(";")[0].strip() # IE sends "<date>; length=146"
ims = parse_date(ims)
if ims is not None and ims >= int(stats.st_mtime):
header['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
return HTTPResponse(status=304, header=header)
header['Content-Length'] = stats.st_size
if request.method == 'HEAD':
return HTTPResponse('', header=header)
else:
return HTTPResponse(open(filename, 'rb'), header=header)
# Utilities
def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
DEBUG = bool(mode)
def parse_date(ims):
""" Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
except (TypeError, ValueError, IndexError):
return None
def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
name, pwd = base64.b64decode(data).split(':', 1)
return name, pwd
except (KeyError, ValueError, TypeError):
return None
def _lscmp(a, b):
''' Compares two strings in a cryptographically save way:
Runtime is not affected by a common prefix. '''
return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b)
def cookie_encode(data, key):
''' Encode and sign a pickle-able object. Return a string '''
msg = base64.b64encode(pickle.dumps(data, -1))
sig = base64.b64encode(hmac.new(key, msg).digest())
return tob('!') + sig + tob('?') + msg
def cookie_decode(data, key):
''' Verify and decode an encoded string. Return an object or None'''
data = tob(data)
if cookie_is_encoded(data):
sig, msg = data.split(tob('?'), 1)
if _lscmp(sig[1:], base64.b64encode(hmac.new(key, msg).digest())):
return pickle.loads(base64.b64decode(msg))
return None
def cookie_is_encoded(data):
''' Return True if the argument looks like a encoded cookie.'''
return bool(data.startswith(tob('!')) and tob('?') in data)
def tonativefunc(enc='utf-8'):
''' Returns a function that turns everything into 'native' strings using enc '''
if sys.version_info >= (3,0,0):
return lambda x: x.decode(enc) if isinstance(x, bytes) else str(x)
return lambda x: x.encode(enc) if isinstance(x, unicode) else str(x)
def yieldroutes(func):
""" Return a generator for routes that match the signature (name, args)
of the func parameter. This may yield more than one route if the function
takes optional keyword arguments. The output is best described by example:
a() -> '/a'
b(x, y) -> '/b/:x/:y'
c(x, y=5) -> '/c/:x' and '/c/:x/:y'
d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y'
"""
path = func.__name__.replace('__','/').lstrip('/')
spec = inspect.getargspec(func)
argc = len(spec[0]) - len(spec[3] or [])
path += ('/:%s' * argc) % tuple(spec[0][:argc])
yield path
for arg in spec[0][argc:]:
path += '/:%s' % arg
yield path
def path_shift(script_name, path_info, shift=1):
''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift. May be negative to
change ths shift direction. (default: 1)
'''
if shift == 0: return script_name, path_info
pathlist = path_info.strip('/').split('/')
scriptlist = script_name.strip('/').split('/')
if pathlist and pathlist[0] == '': pathlist = []
if scriptlist and scriptlist[0] == '': scriptlist = []
if shift > 0 and shift <= len(pathlist):
moved = pathlist[:shift]
scriptlist = scriptlist + moved
pathlist = pathlist[shift:]
elif shift < 0 and shift >= -len(scriptlist):
moved = scriptlist[shift:]
pathlist = moved + pathlist
scriptlist = scriptlist[:shift]
else:
empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
raise AssertionError("Cannot shift. Nothing left from %s" % empty)
new_script_name = '/' + '/'.join(scriptlist)
new_path_info = '/' + '/'.join(pathlist)
if path_info.endswith('/') and pathlist: new_path_info += '/'
return new_script_name, new_path_info
# Decorators
#TODO: Replace default_app() with app()
def validate(**vkargs):
"""
Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403).
"""
def decorator(func):
def wrapper(**kargs):
for key, value in vkargs.iteritems():
if key not in kargs:
abort(403, 'Missing parameter: %s' % key)
try:
kargs[key] = value(kargs[key])
except ValueError:
abort(403, 'Wrong parameter format for: %s' % key)
return func(**kargs)
return wrapper
return decorator
route = functools.wraps(Bottle.route)(lambda *a, **ka: app().route(*a, **ka))
get = functools.wraps(Bottle.get)(lambda *a, **ka: app().get(*a, **ka))
post = functools.wraps(Bottle.post)(lambda *a, **ka: app().post(*a, **ka))
put = functools.wraps(Bottle.put)(lambda *a, **ka: app().put(*a, **ka))
delete = functools.wraps(Bottle.delete)(lambda *a, **ka: app().delete(*a, **ka))
error = functools.wraps(Bottle.error)(lambda *a, **ka: app().error(*a, **ka))
url = functools.wraps(Bottle.get_url)(lambda *a, **ka: app().get_url(*a, **ka))
mount = functools.wraps(Bottle.mount)(lambda *a, **ka: app().mount(*a, **ka))
def default():
depr("The default() decorator is deprecated. Use @error(404) instead.")
return error(404)
# Server adapter
class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **kargs):
self.options = kargs
self.host = host
self.port = int(port)
def run(self, handler): # pragma: no cover
pass
def __repr__(self):
args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()])
return "%s(%s)" % (self.__class__.__name__, args)
class CGIServer(ServerAdapter):
quiet = True
def run(self, handler): # pragma: no cover
from wsgiref.handlers import CGIHandler
CGIHandler().run(handler) # Just ignore host and port here
class FlupFCGIServer(ServerAdapter):
def run(self, handler): # pragma: no cover
import flup.server.fcgi
flup.server.fcgi.WSGIServer(handler, bindAddress=(self.host, self.port)).run()
class WSGIRefServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from wsgiref.simple_server import make_server, WSGIRequestHandler
if self.quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw): pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.serve_forever()
class CherryPyServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from cherrypy import wsgiserver
server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler)
server.start()
class PasteServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from paste import httpserver
from paste.translogger import TransLogger
app = TransLogger(handler)
httpserver.serve(app, host=self.host, port=str(self.port), **self.options)
class FapwsServer(ServerAdapter):
"""
Extremly fast webserver using libev.
See http://william-os4y.livejournal.com/
"""
def run(self, handler): # pragma: no cover
import fapws._evwsgi as evwsgi
from fapws import base
evwsgi.start(self.host, self.port)
evwsgi.set_base_module(base)
def app(environ, start_response):
environ['wsgi.multiprocess'] = False
return handler(environ, start_response)
evwsgi.wsgi_cb(('',app))
evwsgi.run()
class TornadoServer(ServerAdapter):
""" Untested. As described here:
http://github.com/facebook/tornado/blob/master/tornado/wsgi.py#L187 """
def run(self, handler): # pragma: no cover
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
container = tornado.wsgi.WSGIContainer(handler)
server = tornado.httpserver.HTTPServer(container)
server.listen(port=self.port)
tornado.ioloop.IOLoop.instance().start()
class AppEngineServer(ServerAdapter):
""" Untested. """
quiet = True
def run(self, handler):
from google.appengine.ext.webapp import util
util.run_wsgi_app(handler)
class TwistedServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from twisted.web import server, wsgi
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
thread_pool = ThreadPool()
thread_pool.start()
reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
reactor.listenTCP(self.port, factory, interface=self.host)
reactor.run()
class DieselServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(handler, port=self.port)
app.run()
class GunicornServer(ServerAdapter):
""" Untested. """
def run(self, handler):
import gunicorn.arbiter
gunicorn.arbiter.Arbiter((self.host, self.port), 4, handler).run()
class EventletServer(ServerAdapter):
""" Untested """
def run(self, handler):
from eventlet import wsgi, listen
wsgi.server(listen((self.host, self.port)), handler)
class RocketServer(ServerAdapter):
""" Untested. As requested in issue 63
http://github.com/defnull/bottle/issues/#issue/63 """
def run(self, handler):
from rocket import Rocket
server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
server.start()
class AutoServer(ServerAdapter):
""" Untested. """
adapters = [CherryPyServer, PasteServer, TwistedServer, WSGIRefServer]
def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(handler)
except ImportError:
pass
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, **kargs):
""" Runs bottle as a web server. """
app = app if app else default_app()
# Instantiate server, if it is a class instead of an instance
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise RuntimeError("Server must be a subclass of WSGIAdapter")
server.quiet = server.quiet or quiet
if not server.quiet and not os.environ.get('BOTTLE_CHILD'):
print "Bottle server starting up (using %s)..." % repr(server)
print "Listening on http://%s:%d/" % (server.host, server.port)
print "Use Ctrl-C to quit."
print
try:
if reloader:
interval = min(interval, 1)
if os.environ.get('BOTTLE_CHILD'):
_reloader_child(server, app, interval)
else:
_reloader_observer(server, app, interval)
else:
server.run(app)
except KeyboardInterrupt: pass
if not server.quiet and not os.environ.get('BOTTLE_CHILD'):
print "Shutting down..."
class FileCheckerThread(threading.Thread):
''' Thread that periodically checks for changed module files. '''
def __init__(self, lockfile, interval):
threading.Thread.__init__(self)
self.lockfile, self.interval = lockfile, interval
#1: lockfile to old; 2: lockfile missing
#3: module file changed; 5: external exit
self.status = 0
def run(self):
exists = os.path.exists
mtime = lambda path: os.stat(path).st_mtime
files = dict()
for module in sys.modules.values():
try:
path = inspect.getsourcefile(module)
if path and exists(path): files[path] = mtime(path)
except TypeError: pass
while not self.status:
for path, lmtime in files.iteritems():
if not exists(path) or mtime(path) > lmtime:
self.status = 3
if not exists(self.lockfile):
self.status = 2
elif mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 1
if not self.status:
time.sleep(self.interval)
if self.status != 5:
thread.interrupt_main()
def _reloader_child(server, app, interval):
''' Start the server and check for modified files in a background thread.
As soon as an update is detected, KeyboardInterrupt is thrown in
the main thread to exit the server loop. The process exists with status
code 3 to request a reload by the observer process. If the lockfile
is not modified in 2*interval second or missing, we assume that the
observer process died and exit with status code 1 or 2.
'''
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
try:
bgcheck.start()
server.run(app)
except KeyboardInterrupt, e: pass
bgcheck.status, status = 5, bgcheck.status
bgcheck.join() # bgcheck.status == 5 --> silent exit
if status: sys.exit(status)
def _reloader_observer(server, app, interval):
''' Start a child process with identical commandline arguments and restart
it as long as it exists with status code 3. Also create a lockfile and
touch it (update mtime) every interval seconds.
'''
fd, lockfile = tempfile.mkstemp(prefix='bottle-reloader.', suffix='.lock')
os.close(fd) # We only need this file to exist. We never write to it
try:
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
environ['BOTTLE_CHILD'] = 'true'
environ['BOTTLE_LOCKFILE'] = lockfile
p = subprocess.Popen(args, env=environ)
while p.poll() is None: # Busy wait...
os.utime(lockfile, None) # I am alive!
time.sleep(interval)
if p.poll() != 3:
if os.path.exists(lockfile): os.unlink(lockfile)
sys.exit(p.poll())
elif not server.quiet:
print "Reloading server..."
except KeyboardInterrupt: pass
if os.path.exists(lockfile): os.unlink(lockfile)
# Templates
class TemplateError(HTTPError):
def __init__(self, message):
HTTPError.__init__(self, 500, message)
class BaseTemplate(object):
""" Base class and minimal API for template adapters """
extentions = ['tpl','html','thtml','stpl']
settings = {} #used in prepare()
defaults = {} #used in render()
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
""" Create a new template.
If the source parameter (str or buffer) is missing, the name argument
is used to guess a template filename. Subclasses can assume that
self.source and/or self.filename are set. Both are strings.
The lookup, encoding and settings parameters are stored as instance
variables.
The lookup parameter stores a list containing directory paths.
The encoding parameter should be used to decode byte strings or files.
The settings parameter contains a dict for engine-specific settings.
"""
self.name = name
self.source = source.read() if hasattr(source, 'read') else source
self.filename = source.filename if hasattr(source, 'filename') else None
self.lookup = map(os.path.abspath, lookup)
self.encoding = encoding
self.settings = self.settings.copy() # Copy from class variable
self.settings.update(settings) # Apply
if not self.source and self.name:
self.filename = self.search(self.name, self.lookup)
if not self.filename:
raise TemplateError('Template %s not found.' % repr(name))
if not self.source and not self.filename:
raise TemplateError('No template specified.')
self.prepare(**self.settings)
@classmethod
def search(cls, name, lookup=[]):
""" Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit. """
if os.path.isfile(name): return name
for spath in lookup:
fname = os.path.join(spath, name)
if os.path.isfile(fname):
return fname
for ext in cls.extentions:
if os.path.isfile('%s.%s' % (fname, ext)):
return '%s.%s' % (fname, ext)
@classmethod
def global_config(cls, key, *args):
''' This reads or sets the global settings stored in class.settings. '''
if args:
cls.settings[key] = args[0]
else:
return cls.settings[key]
def prepare(self, **options):
""" Run preparations (parsing, caching, ...).
It should be possible to call this again to refresh a template or to
update settings.
"""
raise NotImplementedError
def render(self, **args):
""" Render the template with the specified local variables and return
a single byte or unicode string. If it is a byte string, the encoding
must match self.encoding. This method must be thread-safe!
"""
raise NotImplementedError
class MakoTemplate(BaseTemplate):
def prepare(self, **options):
from mako.template import Template
from mako.lookup import TemplateLookup
options.update({'input_encoding':self.encoding})
#TODO: This is a hack... http://github.com/defnull/bottle/issues#issue/8
mylookup = TemplateLookup(directories=['.']+self.lookup, **options)
if self.source:
self.tpl = Template(self.source, lookup=mylookup)
else: #mako cannot guess extentions. We can, but only at top level...
name = self.name
if not os.path.splitext(name)[1]:
name += os.path.splitext(self.filename)[1]
self.tpl = mylookup.get_template(name)
def render(self, **args):
_defaults = self.defaults.copy()
_defaults.update(args)
return self.tpl.render(**_defaults)
class CheetahTemplate(BaseTemplate):
def prepare(self, **options):
from Cheetah.Template import Template
self.context = threading.local()
self.context.vars = {}
options['searchList'] = [self.context.vars]
if self.source:
self.tpl = Template(source=self.source, **options)
else:
self.tpl = Template(file=self.filename, **options)
def render(self, **args):
self.context.vars.update(self.defaults)
self.context.vars.update(args)
out = str(self.tpl)
self.context.vars.clear()
return [out]
class Jinja2Template(BaseTemplate):
def prepare(self, filters=None, tests=None, **kwargs):
from jinja2 import Environment, FunctionLoader
if 'prefix' in kwargs: # TODO: to be removed after a while
raise RuntimeError('The keyword argument `prefix` has been removed. '
'Use the full jinja2 environment name line_statement_prefix instead.')
self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
if filters: self.env.filters.update(filters)
if tests: self.env.tests.update(tests)
if self.source:
self.tpl = self.env.from_string(self.source)
else:
self.tpl = self.env.get_template(self.filename)
def render(self, **args):
_defaults = self.defaults.copy()
_defaults.update(args)
return self.tpl.render(**_defaults).encode("utf-8")
def loader(self, name):
fname = self.search(name, self.lookup)
if fname:
with open(fname, "rb") as f:
return f.read().decode(self.encoding)
class SimpleTemplate(BaseTemplate):
blocks = ('if','elif','else','try','except','finally','for','while','with','def','class')
dedent_blocks = ('elif', 'else', 'except', 'finally')
def prepare(self, escape_func=cgi.escape, noescape=False):
self.cache = {}
if self.source:
self.code = self.translate(self.source)
self.co = compile(self.code, '<string>', 'exec')
else:
self.code = self.translate(open(self.filename).read())
self.co = compile(self.code, self.filename, 'exec')
enc = self.encoding
self._str = lambda x: touni(x, enc)
self._escape = lambda x: escape_func(touni(x, enc))
if noescape:
self._str, self._escape = self._escape, self._str
def translate(self, template):
stack = [] # Current Code indentation
lineno = 0 # Current line of code
ptrbuffer = [] # Buffer for printable strings and token tuple instances
codebuffer = [] # Buffer for generated python code
touni = functools.partial(unicode, encoding=self.encoding)
multiline = dedent = False
def yield_tokens(line):
for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)):
if i % 2:
if part.startswith('!'): yield 'RAW', part[1:]
else: yield 'CMD', part
else: yield 'TXT', part
def split_comment(codeline):
""" Removes comments from a line of code. """
line = codeline.splitlines()[0]
try:
tokens = list(tokenize.generate_tokens(iter(line).next))
except tokenize.TokenError:
return line.rsplit('#',1) if '#' in line else (line, '')
for token in tokens:
if token[0] == tokenize.COMMENT:
start, end = token[2][1], token[3][1]
return codeline[:start] + codeline[end:], codeline[start:end]
return line, ''
def flush(): # Flush the ptrbuffer
if not ptrbuffer: return
cline = ''
for line in ptrbuffer:
for token, value in line:
if token == 'TXT': cline += repr(value)
elif token == 'RAW': cline += '_str(%s)' % value
elif token == 'CMD': cline += '_escape(%s)' % value
cline += ', '
cline = cline[:-2] + '\\\n'
cline = cline[:-2]
if cline[:-1].endswith('\\\\\\\\\\n'):
cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr'
cline = '_printlist([' + cline + '])'
del ptrbuffer[:] # Do this before calling code() again
code(cline)
def code(stmt):
for line in stmt.splitlines():
codebuffer.append(' ' * len(stack) + line.strip())
for line in template.splitlines(True):
lineno += 1
line = line if isinstance(line, unicode)\
else unicode(line, encoding=self.encoding)
if lineno <= 2:
m = re.search(r"%.*coding[:=]\s*([-\w\.]+)", line)
if m: self.encoding = m.group(1)
if m: line = line.replace('coding','coding (removed)')
if line.strip()[:2].count('%') == 1:
line = line.split('%',1)[1].lstrip() # Full line following the %
cline = split_comment(line)[0].strip()
cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0]
flush() ##encodig (TODO: why?)
if cmd in self.blocks or multiline:
cmd = multiline or cmd
dedent = cmd in self.dedent_blocks # "else:"
if dedent and not oneline and not multiline:
cmd = stack.pop()
code(line)
oneline = not cline.endswith(':') # "if 1: pass"
multiline = cmd if cline.endswith('\\') else False
if not oneline and not multiline:
stack.append(cmd)
elif cmd == 'end' and stack:
code('#end(%s) %s' % (stack.pop(), line.strip()[3:]))
elif cmd == 'include':
p = cline.split(None, 2)[1:]
if len(p) == 2:
code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1]))
elif p:
code("_=_include(%s, _stdout)" % repr(p[0]))
else: # Empty %include -> reverse of %rebase
code("_printlist(_base)")
elif cmd == 'rebase':
p = cline.split(None, 2)[1:]
if len(p) == 2:
code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1]))
elif p:
code("globals()['_rebase']=(%s, {})" % repr(p[0]))
else:
code(line)
else: # Line starting with text (not '%') or '%%' (escaped)
if line.strip().startswith('%%'):
line = line.replace('%%', '%', 1)
ptrbuffer.append(yield_tokens(line))
flush()
return '\n'.join(codebuffer) + '\n'
def subtemplate(self, _name, _stdout, **args):
if _name not in self.cache:
self.cache[_name] = self.__class__(name=_name, lookup=self.lookup)
return self.cache[_name].execute(_stdout, **args)
def execute(self, _stdout, **args):
env = self.defaults.copy()
env.update({'_stdout': _stdout, '_printlist': _stdout.extend,
'_include': self.subtemplate, '_str': self._str,
'_escape': self._escape})
env.update(args)
eval(self.co, env)
if '_rebase' in env:
subtpl, rargs = env['_rebase']
subtpl = self.__class__(name=subtpl, lookup=self.lookup)
rargs['_base'] = _stdout[:] #copy stdout
del _stdout[:] # clear stdout
return subtpl.execute(_stdout, **rargs)
return env
def render(self, **args):
""" Render the template using keyword arguments as local variables. """
stdout = []
self.execute(stdout, **args)
return ''.join(stdout)
def template(tpl, template_adapter=SimpleTemplate, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
'''
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.get('template_settings',{})
lookup = kwargs.get('template_lookup', TEMPLATE_PATH)
if isinstance(tpl, template_adapter):
TEMPLATES[tpl] = tpl
if settings: TEMPLATES[tpl].prepare(**settings)
elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
if not TEMPLATES[tpl]:
abort(500, 'Template (%s) not found' % tpl)
return TEMPLATES[tpl].render(**kwargs)
mako_template = functools.partial(template, template_adapter=MakoTemplate)
cheetah_template = functools.partial(template, template_adapter=CheetahTemplate)
jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
def view(tpl_name, **defaults):
''' Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the template, but return the handler result as is.
This includes returning a HTTPResponse(dict) to get,
for instance, JSON with autojson or other castfilters
'''
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if isinstance(result, (dict, DictMixin)):
tplvars = defaults.copy()
tplvars.update(result)
return template(tpl_name, **tplvars)
return result
return wrapper
return decorator
mako_view = functools.partial(view, template_adapter=MakoTemplate)
cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
# Modul initialization and configuration
TEMPLATE_PATH = ['./', './views/']
TEMPLATES = {}
DEBUG = False
MEMFILE_MAX = 1024*100
HTTP_CODES = {
100: 'CONTINUE',
101: 'SWITCHING PROTOCOLS',
200: 'OK',
201: 'CREATED',
202: 'ACCEPTED',
203: 'NON-AUTHORITATIVE INFORMATION',
204: 'NO CONTENT',
205: 'RESET CONTENT',
206: 'PARTIAL CONTENT',
300: 'MULTIPLE CHOICES',
301: 'MOVED PERMANENTLY',
302: 'FOUND',
303: 'SEE OTHER',
304: 'NOT MODIFIED',
305: 'USE PROXY',
306: 'RESERVED',
307: 'TEMPORARY REDIRECT',
400: 'BAD REQUEST',
401: 'UNAUTHORIZED',
402: 'PAYMENT REQUIRED',
403: 'FORBIDDEN',
404: 'NOT FOUND',
405: 'METHOD NOT ALLOWED',
406: 'NOT ACCEPTABLE',
407: 'PROXY AUTHENTICATION REQUIRED',
408: 'REQUEST TIMEOUT',
409: 'CONFLICT',
410: 'GONE',
411: 'LENGTH REQUIRED',
412: 'PRECONDITION FAILED',
413: 'REQUEST ENTITY TOO LARGE',
414: 'REQUEST-URI TOO LONG',
415: 'UNSUPPORTED MEDIA TYPE',
416: 'REQUESTED RANGE NOT SATISFIABLE',
417: 'EXPECTATION FAILED',
500: 'INTERNAL SERVER ERROR',
501: 'NOT IMPLEMENTED',
502: 'BAD GATEWAY',
503: 'SERVICE UNAVAILABLE',
504: 'GATEWAY TIMEOUT',
505: 'HTTP VERSION NOT SUPPORTED',
}
""" A dict of known HTTP error and status codes """
ERROR_PAGE_TEMPLATE = SimpleTemplate("""
%try:
%from bottle import DEBUG, HTTP_CODES, request
%status_name = HTTP_CODES.get(e.status, 'Unknown').title()
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Error {{e.status}}: {{status_name}}</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd; padding: 15px; margin: 15px;}
pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error {{e.status}}: {{status_name}}</h1>
<p>Sorry, the requested URL <tt>{{request.url}}</tt> caused an error:</p>
<pre>{{str(e.output)}}</pre>
%if DEBUG and e.exception:
<h2>Exception:</h2>
<pre>{{repr(e.exception)}}</pre>
%end
%if DEBUG and e.traceback:
<h2>Traceback:</h2>
<pre>{{e.traceback}}</pre>
%end
</body>
</html>
%except ImportError:
<b>ImportError:</b> Could not generate the error page. Please add bottle to sys.path
%end
""")
""" The HTML template used for error messages """
request = Request()
""" Whenever a page is requested, the :class:`Bottle` WSGI handler stores
metadata about the current request into this instance of :class:`Request`.
It is thread-safe and can be accessed from within handler functions. """
response = Response()
""" The :class:`Bottle` WSGI handler uses metadata assigned to this instance
of :class:`Response` to generate the WSGI response. """
local = threading.local()
""" Thread-local namespace. Not used by Bottle, but could get handy """
# Initialize app stack (create first empty Bottle app)
# BC: 0.6.4 and needed for run()
app = default_app = AppStack()
app.push()
| Python |
#!/usr/bin/env python
#coding=utf-8
from weibopy.auth import OAuthHandler
from weibopy.api import API
import sqlite3
from threading import Thread
from Queue import Queue
from time import sleep
from datetime import datetime, timedelta, date, time
import sys
from tag_detect import detect
import os
from signal import SIGTERM
from crawler_id import idlist as A
reload(sys)
sys.setdefaultencoding('utf-8')
PAGE = 2
START = 1
B = []
try:
tmp = sys.argv[1].split("-")
if len(tmp) < 2:
PAGE = int(tmp[0])
else:
START, PAGE = tmp
START = int(START)
PAGE = int(PAGE) - START + 1
except IndexError:
pass
LOCK = '/var/lock/sinacrawler.lock'
if os.path.isfile(LOCK):
f = open(LOCK, "r").read()
try:
os.kill(int(f), SIGTERM)
except:
pass
pid = os.getpid()
f = open(LOCK, "w")
f.write("%d"%(pid))
f.close()
def now():
return str(datetime.now()) + " "
print now() + "Initializing..."
def iszhaopin(s):
keywords = [(u"招聘", ),
(u"诚聘", ),
(u"诚招", ),
(u"新职位", ),
(u"急聘", ),
# (u"需要", u"人员"),
(u"招人", ),
(u"招", u"人员"),
# (u"挖角", ),
(u"急招", ),
(u"伯乐奖", ),
(u"招兵买马", ),
(u"发送简历", ),
(u"发简历", ),
(u"email简历", ),
(u"岗位", u"空缺"),
(u"职位", u"名"),
(u"推荐", u"人才"),
(u"荐才", u"注明应聘"),
(u"内推", u"实习生"),
(u"内部推荐", u"精英"),
(u"换工作", u"高手"),
(u"换跑道", u"千里马"),
(u"欢迎加入我们", ),
(u"兼职招聘", ),
(u"创业招聘", ),
]
declinekeywords = [(u"智联招聘", ),
(u"寻人启事", ),
(r"//@", ),
]
match = False
for keywordset in keywords:
match2 = True
for key in keywordset:
if key not in s:
match2 = False
break
if match2:
match = True
break
if not match:
return False
for keywordset in declinekeywords:
match = True
for key in keywordset:
if key not in s:
match = False
break
if match:
return False
return True
class SinaFetch():
consumer_key= "961495784"
consumer_secret ="47d9d806a1dc04cc758be6f7213465bc"
def __init__(self):
""" constructor """
def getAtt(self, key):
try:
return self.obj.__getattribute__(key)
except Exception, e:
#print e
return ''
def getAttValue(self, obj, key):
try:
return obj.__getattribute__(key)
except Exception, e:
print e
return ''
def setToken(self, token, tokenSecret):
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
self.auth.setToken(token, tokenSecret)
self.api = API(self.auth)
def auth(self):
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
auth_url = self.auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
self.auth.get_access_token(verifier)
self.api = API(self.auth)
def friends_timeline(self, page):
timeline = self.api.friends_timeline(count=200, page=page)
results = []
for line in timeline:
self.obj = line
mid = self.getAtt("id")
text = unicode(self.getAtt("text"))
posttime = self.getAtt("created_at")
source = self.getAtt("source")
user = self.getAtt("user")
try:
thumbnail = self.getAtt("thumbnail_pic")
if thumbnail[:7] != "http://":
thumbnail = ""
except:
thumbnail = ""
self.obj = user
userid = self.getAtt("id")
name = unicode(self.getAtt("screen_name"))
avatar = self.getAtt("profile_image_url")
if iszhaopin(text):
results += [(userid, name, avatar, mid, text, posttime, source, thumbnail)]
return results
q = Queue()
def working():
global B
cateid, crawlerinfo = q.get()
test = SinaFetch()
test.setToken(crawlerinfo[1], crawlerinfo[2])
for page in range(START, PAGE + START):
while True:
try:
result = test.friends_timeline(page)
break
except:
print now() + "Crawler %s Cate:%d page %d/%d Failed, Retrying..." % (crawlerinfo[0], cateid, page, START + PAGE - 1)
B += [(cateid, result)]
print now() + "Crawler %s Cate:%d page %d/%d Done." % (crawlerinfo[0], cateid, page, START + PAGE - 1)
sleep(0.2)
q.task_done()
for crawler in A:
q.put(crawler)
t = Thread(target=working)
t.setDaemon(True)
t.start()
sleep(0.2)
print now() + "Preparing cursors to operate database..."
path = '/var/www/0f523140-f3b3-4653-89b0-eb08c39940ad/src/crawler'
#path = os.path.dirname(sys.argv[0])
os.chdir(path)
import MySQLdb, uuid
db = MySQLdb.connect("205.185.126.152","apis","G2WvPRsxGEr77wEd","apis",charset="utf8")
c = db.cursor()
#_tagid = open("tag_list_withid.dict", "r").read().decode("utf-8").split('\n')
c.execute("SELECT * FROM tags")
tagid = {}
tagnoid = []
for i in c:
tag_id, tag = i[0], i[1]
tagnoid += [tag]
tagid[tag] = tag_id
f = open("tag_list_nogroup.dict", "w")
f.write('\n'.join(tagnoid))
f.close()
#Disabled temperarly
#d = detect()
#for line in _tagid:
# tag_id, tag = line.split()
# tagid[tag] = tag_id
print now() + "Dealing with pending tweets..."
c.execute("SELECT * FROM pending_tweets LIMIT 0 , 1")
while True:
try:
tweet_site_id, post_screenname, profile_image_url, source, post_datetime, content, type_, user_site_id, tweet_id, site_id, thumbnail = c.fetchone()
c.execute("DELETE FROM pending_tweets WHERE tweet_id = %s", (tweet_id,))
c.execute("SELECT * FROM tweets WHERE site_id = %s AND tweet_site_id = %s", (site_id, tweet_site_id))
if c.fetchone() != None:
print now() + "Dulplicate pending item:", tweet_site_id
c.execute("SELECT * FROM pending_tweets LIMIT 0 , 1")
continue
c.execute("""INSERT INTO tweets (
site_id, tweet_id, user_site_id, content, post_datetime,
type, tweet_site_id, favorite_count, application_count,
post_screenname, profile_image_url, source, thumbnail)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(site_id, tweet_id, user_site_id, content, post_datetime,
type_, tweet_site_id, 0, 0,
post_screenname, profile_image_url, source, thumbnail))
c.execute("""INSERT INTO cat_relationship (
tweet_id, cat_id)
VALUES (%s, %s)""",
(tweet_id, 0,))
#for tag in d.Split(content)[:]:
for tag in tagnoid:
if tag.lower() not in content.lower():
continue
try:
c.execute("""INSERT INTO tag_relationship (
tag_id, tweet_id)
VALUES (%s, %s)""",
(tagid[tag], tweet_id))
c.execute("SELECT count, tag_group FROM tags WHERE tag_id = %s", (tagid[tag],))
t = c.fetchone()
if t == None:
print now() + "Error updating count: No tag %s found!" % (tag, )
else:
count = t[0] + 1
tag_group = t[1]
if tag_group != 0:
#print tag_group, "Tag group detected!"
c.execute("UPDATE tags SET count = %s WHERE tag_group = %s", (count, tag_group))
else:
c.execute("UPDATE tags SET count = %s WHERE tag_id = %s", (count, tagid[tag]))
except KeyError:
print now() + "Error updating tag: No tag %s found!" % (tag, )
print now() + "Inserted pending item:", tweet_site_id
c.execute("SELECT * FROM pending_tweets LIMIT 0 , 1")
except:
break
q.join()
print now() + "Craw Complete."
for cat, items in B:
for userid, name, avatar, mid, text, posttime, source, thumbnail in items:
tweet_id = uuid.uuid4().hex
c.execute("SELECT * FROM tweets WHERE tweet_site_id = %s", (mid,))
if c.fetchone() != None:
print now() + "Dulplicate item: %d, %d" % (cat, mid)
continue
c.execute("""INSERT INTO tweets (
site_id, tweet_id, user_site_id, content, post_datetime,
type, tweet_site_id, favorite_count, application_count,
post_screenname, profile_image_url, source, thumbnail)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(1, tweet_id, userid, text, posttime,
2, mid, 0, 0,
name, avatar, source, thumbnail))
c.execute("""INSERT INTO cat_relationship (
cat_id, tweet_id)
VALUES (%s, %s)""",
(cat, tweet_id))
#for tag in d.Split(text)[:]:
for tag in tagnoid:
if tag.lower() not in text.lower():
continue
try:
c.execute("""INSERT INTO tag_relationship (
tag_id, tweet_id)
VALUES (%s, %s)""",
(tagid[tag], tweet_id))
c.execute("SELECT count, tag_group FROM tags WHERE tag_id = %s", (tagid[tag],))
t = c.fetchone()
if t == None:
print now() + "Error updating count: No tag %s found!" % (tag, )
else:
count = t[0] + 1
tag_group = t[1]
if tag_group != 0:
#print tag_group, "Tag group detected!"
c.execute("UPDATE tags SET count = %s WHERE tag_group = %s", (count, tag_group))
else:
c.execute("UPDATE tags SET count = %s WHERE tag_id = %s", (count, tagid[tag]))
except KeyError:
print now() + "Error updating tag: No tag %s found!" % (tag, )
c.execute("SELECT count FROM categories WHERE cat_id = %s", (cat,))
t = c.fetchone()
if t == None:
print now() + "Error updating count: No category %d found!" % (cat, )
else:
count = t[0] + 1
c.execute("UPDATE categories SET count = %s WHERE cat_id = %s", (count, cat))
print now() + "Inserted item: %d, %d" % (cat, mid)
#counting
c.execute("SELECT COUNT(*) FROM tweets WHERE post_datetime > %s", (datetime.combine(date.today(), time()),))
t = c.fetchone()
if t == None:
count = 0
else:
count = t[0]
c.execute("UPDATE counts SET count = %s WHERE type = %s", (count, "tweets_today"))
c.execute("SELECT COUNT(*) FROM tweets WHERE post_datetime > %s", (datetime.combine(date.today(), time()) - timedelta(days = datetime.now().isoweekday() - 1),))
t = c.fetchone()
if t == None:
count = 0
else:
count = t[0]
c.execute("UPDATE counts SET count = %s WHERE type = %s", (count, "tweets_thisweek"))
db.commit()
c.close()
print now() + "Wrote Database."
os.unlink(LOCK)
| Python |
from weibopy.auth import OAuthHandler
from weibopy.api import API
from threading import Thread
from Queue import Queue
from time import sleep
from datetime import datetime, timedelta, date, time
import sys
from tag_detect import detect
import os
from crawler_id import idlist as A
from weibopy.error import WeibopError
B = []
def now():
return str(datetime.now()) + " "
print now() + "Initializing..."
class SinaFollow():
consumer_key= "961495784"
consumer_secret ="47d9d806a1dc04cc758be6f7213465bc"
def __init__(self):
""" constructor """
def getAtt(self, key):
try:
return self.obj.__getattribute__(key)
except Exception, e:
print e
return ''
def getAttValue(self, obj, key):
try:
return obj.__getattribute__(key)
except Exception, e:
print e
return ''
def setToken(self, token, tokenSecret):
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
self.auth.setToken(token, tokenSecret)
self.api = API(self.auth)
def auth(self):
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
auth_url = self.auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
self.auth.get_access_token(verifier)
self.api = API(self.auth)
def friendship_create(self, screen_name):
timeline = self.api.create_friendship(screen_name = screen_name)
f = unicode(open("follow_id.list", "r").read(), "utf-8").replace("\r","").split("\n")
for line in f:
b = line.split('\t')
user = b[0]
cats = [int(x) for x in b[1:]]
B += [(user, cats)]
q = Queue()
def working():
global B
count = 0
crawler = q.get()
test = SinaFollow()
test.setToken(crawler[1][2], crawler[1][3])
for user, cats in B:
if crawler[0] in cats:
count += 1
sleep(0.5)
try:
test.friendship_create(user)
print now(), "Crawler", crawler[0], "Followed", count, ":", user
except WeibopError as (error_msg):
print now(), "Crawler", crawler[0], "Error following", count, ":", user, "Reason:",error_msg
q.task_done()
for crawler in enumerate(A):
q.put(crawler)
t = Thread(target=working)
t.setDaemon(True)
t.start()
sleep(2)
q.join()
print now() + "Follow Complete."
| Python |
import sys, uuid
from datetime import datetime
def now():
return str(datetime.now()) + " "
dic = open("tag_list.dict", "r")
result = []
dic2 = []
dic3 = []
for item in dic:
m = unicode(item, "utf-8").split()
if len(m) > 1:
tag, group = m
else:
tag, group = m[0], "0"
tag_id = uuid.uuid4().hex
result += [(tag_id, tag, group, 0)]
dic2 += [tag]
dic3 += [(tag_id, tag)]
dic.close()
#dic = open("tag_list_nogroup.dict", "w")
#dic.write("\n".join(dic2).encode("utf-8").lower())
#dic.close()
#dic = open("tag_list_withid.dict", "w")
#dic.write("\n".join([" ".join(x) for x in dic3]).encode("utf-8").lower())
#dic.close()
print now() + "Wrote Dict."
import MySQLdb
db = MySQLdb.connect("127.0.0.1","apis","G2WvPRsxGEr77wEd","apis",charset="utf8")
c = db.cursor()
c.executemany("""INSERT INTO tags (tag_id, name, tag_group, count) VALUES (%s, %s, %s, %s)""",
result)
db.commit()
c.close()
print now() + "Wrote Database."
| Python |
#coding:utf-8
from threading import Thread
from Queue import Queue
from time import sleep
import sqlite3
import sys, re, StringIO
import urllib2 as urllib
q = Queue()
NUM = 17
JOBS = 3000
results = []
def craw(arguments):
global results
try:
a = unicode(urllib.urlopen("http://tbole.com/result.php?searchid=%d" % (arguments,)).read(), "gbk")
a = a.replace("\n", " ").replace("\r", "")
b = re.findall(u"<span class=\"about_text\">[^<]+?</span>(.+?)</div>", a)
for c in b:
d = re.findall(u"<span><a[^>]*>(.+?)</a></span>", c)
for e in d:
results += [e]
print arguments, "Done."
except:
print arguments, "Error."
pass
sleep(0.2)
def working():
while True:
arguments = q.get()
craw(arguments)
q.task_done()
for i in range(NUM):
t = Thread(target=working)
t.setDaemon(True)
t.start()
for i in range(JOBS):
q.put(i)
q.join()
print "Craw completed."
b = {}
for a in results:
b[a] = 1;
f = open("tbole_key.txt", "w")
f.write("\n".join(b.keys()).encode('utf-8'))
f.close()
print "Wrote results."
| Python |
#coding:utf-8
#!/usr/bin/env python
from threading import Thread
from Queue import Queue
from time import sleep
import sqlite3
import sys, re, StringIO, os
import urllib2 as urllib
from datetime import datetime
q = Queue()
NUM = 20
TIMEOUT = 0.1
C = (u"名人堂", u"媒体汇", u"品牌馆")
def now():
return str(datetime.now()) + " "
print now() + "Initializing..."
def craw(url, tag1, tag2, tag3):
print now() + "Crawler",tag1,tag2,tag3,"Initializing..."
while True:
try:
a = unicode(urllib.urlopen(url).read(), "utf-8")
break
except:
print now() + "Crawler",tag1,tag2,tag3,"initialize failed, Retrying..."
sleep(TIMEOUT)
f = open(tag1 + os.sep + tag2 + os.sep + tag3 + ".txt", "w")
i = 0
while True:
i += 1
print now() + "Crawler",tag1,tag2,tag3,"Page",i,"Crawing..."
b = re.findall("<a href=\"(home.php\?uid=(\d+)&[^\"]+)\">([^<]+)</a>", a)
for urltmp, userid, nickname in b:
url = 'http://t.sina.cn/dpool/ttt/' + urltmp.replace("home.php", "user.php")
while True:
try:
c = unicode(urllib.urlopen(url).read(), "utf-8")
break
except:
try:
print now() + "Crawler",tag1,tag2,tag3,"Page",i,"User",nickname,"fetch failed, Retrying..."
except:
print now() + "Crawler",tag1,tag2,tag3,"Page",i,"User XXX","fetch failed, Retrying..."
sleep(TIMEOUT)
try:
d = re.findall(u"认证说明:([^<]+)", c)[0]
except:
d = ""
try:
print now() + "Crawler",tag1,tag2,tag3,"Page",i,"User",nickname,"("+d+")","Fetched."
except:
print now() + "Crawler",tag1,tag2,tag3,"Page",i,"User XXX","(XXX)","Fetched."
f.write((userid + '\t' + nickname + '\t' + d + '\n').encode('utf-8'))
sleep(TIMEOUT)
try:
nextpage = re.findall(u"<a href=\"([^\"]+)\">下页</a>", a)[0].replace("&", "&")
except:
f.close()
return
sleep(TIMEOUT)
url = "http://t.sina.cn" + nextpage
while True:
try:
a = unicode(urllib.urlopen(url).read(), "utf-8")
break
except:
print now() + "Crawler",tag1,tag2,tag3,"Page",i+1,"fetch failed, Retrying..."
sleep(TIMEOUT)
def working():
global q
while True:
arguments = q.get()
craw(*arguments)
q.task_done()
for i in range(NUM):
t = Thread(target=working)
t.setDaemon(True)
t.start()
for ntagt, tag1 in enumerate(C[2:]):
ntag1 = ntagt + 2
print now() + "Seeking",tag1,"..."
try:
os.mkdir(tag1)
except:
pass
url = "http://t.sina.cn/dpool/ttt/v2star.php?cat=%d&sorttype=industry&gsid=3_5bc659f93ba7c3eac863570828ad7bccb5" % (ntag1 + 1,)
while True:
try:
a = unicode(urllib.urlopen(url).read(), "utf-8")
break
except:
print now() + "Seeking",tag1,"failed, Retrying..."
sleep(TIMEOUT)
b = re.findall("<a href=\"(/dpool/ttt/v2star.php\?cat=%d&ta[^\"]+)\">([^<]+)</a>" % (ntag1 + 1,), a)
if(len(b)) == 0:
b = [[url, tag1]]
for (url, tag2) in b:
print now() + "Seeking",tag1,tag2,"..."
try:
os.mkdir(tag1 + os.sep + tag2)
except:
pass
if url[0] == '/':
url = 'http://t.sina.cn' + url.replace('&', '&')
while True:
try:
a = unicode(urllib.urlopen(url).read(), "utf-8")
break
except:
print now() + "Seeking",tag1,tag2,"failed, Retrying..."
sleep(TIMEOUT)
b2 = re.findall("<a href=\"(/dpool/ttt/v2star.php\?cat=%d&su[^\"]+)\">([^<]+)</a>" % (ntag1 + 1,), a)
for (url, tag3) in b2:
q.put(('http://t.sina.cn' + url.replace('&', '&'), tag1, tag2, tag3))
q.join()
| Python |
#coding:utf-8
from threading import Thread
from Queue import Queue
import sqlite3
import sys, re, StringIO
from time import sleep
import urllib2, urllib
TARGET = 1000
NUM = 10
ids = []
results = []
count = 0
q = Queue()
KEYS = ['招聘']
class UserAgentProcessor(urllib2.BaseHandler):
"""A handler to add a custom UA string to urllib2 requests
"""
def __init__(self):
self.handler_order = 100
self.ua = "User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.25 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.707.0 Chrome/12.0.707.0 Safari/534.25"
def http_request(self, request):
request.add_header("User-Agent", self.ua)
return request
https_request = http_request
opener = urllib2.build_opener(UserAgentProcessor())
urllib2.install_opener(opener)
def craw(key):
global count, results, q, ids
key = key.replace(" ", "%20")
print key
params = urllib.urlencode({'keyword': key, 'smblog': '搜微博'})
a = urllib2.urlopen("http://t.sina.cn/dpool/ttt/search.php?PHPSESSID=f54ade2b393f1a28b59db06939c8f420", data=params)
while True:
b = a.read().split('<div class="c"')
for item in b[1:-2]:
try:
if "转发了" in item:
continue
id = re.findall('id="([^"]+)"', item)[0]
text = re.findall('<span class="ctt">(.+?)</span>[\[\&]', item)[0]
text = re.sub("<.+?>","",text)
if text[0] == ':':
text = text[1:]
if id in ids:
continue
print id, text
results.append((id, unicode(text,'utf-8')))
ids.append(id)
count += 1
#print count
if count > TARGET:
return
except:
pass
try:
nextpage = re.findall("<a href=\"([^\"]+)\">下页</a>", b[-3])[0].replace("&", "&")
except:
return
sleep(0.1)
a = urllib.urlopen("http://t.sina.cn/dpool/ttt/" + nextpage)
def working():
global q
while True:
arguments = q.get()
craw(arguments)
q.task_done()
for i in range(NUM):
t = Thread(target=working)
t.setDaemon(True)
t.start()
for key in KEYS:
q.put(key)
q.join()
print "Craw completed."
sys.exit(1)
conn = sqlite3.connect("train.dat")
cur = conn.cursor()
try:
cur.execute("create table tweets (id text, content text)")
except sqlite3.OperationalError:
pass
cur.executemany("insert into tweets values (?,?)", results)
conn.commit()
cur.close()
conn.close()
print "Wrote Database."
| Python |
#!/usr/bin/env python
#coding=utf-8
from weibopy.auth import OAuthHandler
from weibopy.api import API
import sqlite3
from threading import Thread
from Queue import Queue
from time import sleep
from datetime import datetime, timedelta, date, time
import sys
from tag_detect import detect
import os
from signal import SIGTERM
from crawler_id import idlist as A
reload(sys)
sys.setdefaultencoding('utf-8')
PAGE = 2
START = 1
B = []
try:
tmp = sys.argv[1].split("-")
if len(tmp) < 2:
PAGE = int(tmp[0])
else:
START, PAGE = tmp
START = int(START)
PAGE = int(PAGE) - START + 1
except IndexError:
pass
LOCK = '/var/lock/sinacrawler.lock'
if os.path.isfile(LOCK):
f = open(LOCK, "r").read()
try:
os.kill(int(f), SIGTERM)
except:
pass
pid = os.getpid()
f = open(LOCK, "w")
f.write("%d"%(pid))
f.close()
def now():
return str(datetime.now()) + " "
print now() + "Initializing..."
def iszhaopin(s):
keywords = [(u"招聘", ),
(u"诚聘", ),
(u"诚招", ),
(u"新职位", ),
(u"急聘", ),
# (u"需要", u"人员"),
(u"招人", ),
(u"招", u"人员"),
# (u"挖角", ),
(u"急招", ),
(u"伯乐奖", ),
(u"招兵买马", ),
(u"发送简历", ),
(u"发简历", ),
(u"email简历", ),
(u"岗位", u"空缺"),
(u"职位", u"名"),
(u"推荐", u"人才"),
(u"荐才", u"注明应聘"),
(u"内推", u"实习生"),
(u"内部推荐", u"精英"),
(u"换工作", u"高手"),
(u"换跑道", u"千里马"),
(u"欢迎加入我们", ),
(u"兼职招聘", ),
(u"创业招聘", ),
]
declinekeywords = [(u"智联招聘", ),
(u"寻人启事", ),
(r"//@", ),
]
match = False
for keywordset in keywords:
match2 = True
for key in keywordset:
if key not in s:
match2 = False
break
if match2:
match = True
break
if not match:
return False
for keywordset in declinekeywords:
match = True
for key in keywordset:
if key not in s:
match = False
break
if match:
return False
return True
class SinaFetch():
consumer_key= "961495784"
consumer_secret ="47d9d806a1dc04cc758be6f7213465bc"
def __init__(self):
""" constructor """
def getAtt(self, key):
try:
return self.obj.__getattribute__(key)
except Exception, e:
#print e
return ''
def getAttValue(self, obj, key):
try:
return obj.__getattribute__(key)
except Exception, e:
print e
return ''
def setToken(self, token, tokenSecret):
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
self.auth.setToken(token, tokenSecret)
self.api = API(self.auth)
def auth(self):
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
auth_url = self.auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
self.auth.get_access_token(verifier)
self.api = API(self.auth)
def friends_timeline(self, page):
timeline = self.api.friends_timeline(count=200, page=page)
results = []
for line in timeline:
self.obj = line
mid = self.getAtt("id")
text = unicode(self.getAtt("text"))
posttime = self.getAtt("created_at")
source = self.getAtt("source")
user = self.getAtt("user")
try:
thumbnail = self.getAtt("thumbnail_pic")
if thumbnail[:7] != "http://":
thumbnail = ""
except:
thumbnail = ""
self.obj = user
userid = self.getAtt("id")
name = unicode(self.getAtt("screen_name"))
avatar = self.getAtt("profile_image_url")
if iszhaopin(text):
results += [(userid, name, avatar, mid, text, posttime, source, thumbnail)]
return results
q = Queue()
def working():
global B
cateid, crawlerinfo = q.get()
test = SinaFetch()
test.setToken(crawlerinfo[1], crawlerinfo[2])
for page in range(START, PAGE + START):
while True:
try:
result = test.friends_timeline(page)
break
except:
print now() + "Crawler %s Cate:%d page %d/%d Failed, Retrying..." % (crawlerinfo[0], cateid, page, START + PAGE - 1)
B += [(cateid, result)]
print now() + "Crawler %s Cate:%d page %d/%d Done." % (crawlerinfo[0], cateid, page, START + PAGE - 1)
sleep(0.2)
q.task_done()
for crawler in A:
q.put(crawler)
t = Thread(target=working)
t.setDaemon(True)
t.start()
sleep(0.2)
print now() + "Preparing cursors to operate database..."
path = '/var/www/0f523140-f3b3-4653-89b0-eb08c39940ad/src/crawler'
#path = os.path.dirname(sys.argv[0])
os.chdir(path)
import MySQLdb, uuid
db = MySQLdb.connect("205.185.126.152","apis","G2WvPRsxGEr77wEd","apis",charset="utf8")
c = db.cursor()
#_tagid = open("tag_list_withid.dict", "r").read().decode("utf-8").split('\n')
c.execute("SELECT * FROM tags")
tagid = {}
tagnoid = []
for i in c:
tag_id, tag = i[0], i[1]
tagnoid += [tag]
tagid[tag] = tag_id
f = open("tag_list_nogroup.dict", "w")
f.write('\n'.join(tagnoid))
f.close()
#Disabled temperarly
#d = detect()
#for line in _tagid:
# tag_id, tag = line.split()
# tagid[tag] = tag_id
print now() + "Dealing with pending tweets..."
c.execute("SELECT * FROM pending_tweets LIMIT 0 , 1")
while True:
try:
tweet_site_id, post_screenname, profile_image_url, source, post_datetime, content, type_, user_site_id, tweet_id, site_id, thumbnail = c.fetchone()
c.execute("DELETE FROM pending_tweets WHERE tweet_id = %s", (tweet_id,))
c.execute("SELECT * FROM tweets WHERE site_id = %s AND tweet_site_id = %s", (site_id, tweet_site_id))
if c.fetchone() != None:
print now() + "Dulplicate pending item:", tweet_site_id
c.execute("SELECT * FROM pending_tweets LIMIT 0 , 1")
continue
c.execute("""INSERT INTO tweets (
site_id, tweet_id, user_site_id, content, post_datetime,
type, tweet_site_id, favorite_count, application_count,
post_screenname, profile_image_url, source, thumbnail)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(site_id, tweet_id, user_site_id, content, post_datetime,
type_, tweet_site_id, 0, 0,
post_screenname, profile_image_url, source, thumbnail))
c.execute("""INSERT INTO cat_relationship (
tweet_id, cat_id)
VALUES (%s, %s)""",
(tweet_id, 0,))
#for tag in d.Split(content)[:]:
for tag in tagnoid:
if tag.lower() not in content.lower():
continue
try:
c.execute("""INSERT INTO tag_relationship (
tag_id, tweet_id)
VALUES (%s, %s)""",
(tagid[tag], tweet_id))
c.execute("SELECT count, tag_group FROM tags WHERE tag_id = %s", (tagid[tag],))
t = c.fetchone()
if t == None:
print now() + "Error updating count: No tag %s found!" % (tag, )
else:
count = t[0] + 1
tag_group = t[1]
if tag_group != 0:
#print tag_group, "Tag group detected!"
c.execute("UPDATE tags SET count = %s WHERE tag_group = %s", (count, tag_group))
else:
c.execute("UPDATE tags SET count = %s WHERE tag_id = %s", (count, tagid[tag]))
except KeyError:
print now() + "Error updating tag: No tag %s found!" % (tag, )
print now() + "Inserted pending item:", tweet_site_id
c.execute("SELECT * FROM pending_tweets LIMIT 0 , 1")
except:
break
q.join()
print now() + "Craw Complete."
for cat, items in B:
for userid, name, avatar, mid, text, posttime, source, thumbnail in items:
tweet_id = uuid.uuid4().hex
c.execute("SELECT * FROM tweets WHERE tweet_site_id = %s", (mid,))
if c.fetchone() != None:
print now() + "Dulplicate item: %d, %d" % (cat, mid)
continue
c.execute("""INSERT INTO tweets (
site_id, tweet_id, user_site_id, content, post_datetime,
type, tweet_site_id, favorite_count, application_count,
post_screenname, profile_image_url, source, thumbnail)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(1, tweet_id, userid, text, posttime,
2, mid, 0, 0,
name, avatar, source, thumbnail))
c.execute("""INSERT INTO cat_relationship (
cat_id, tweet_id)
VALUES (%s, %s)""",
(cat, tweet_id))
#for tag in d.Split(text)[:]:
for tag in tagnoid:
if tag.lower() not in text.lower():
continue
try:
c.execute("""INSERT INTO tag_relationship (
tag_id, tweet_id)
VALUES (%s, %s)""",
(tagid[tag], tweet_id))
c.execute("SELECT count, tag_group FROM tags WHERE tag_id = %s", (tagid[tag],))
t = c.fetchone()
if t == None:
print now() + "Error updating count: No tag %s found!" % (tag, )
else:
count = t[0] + 1
tag_group = t[1]
if tag_group != 0:
#print tag_group, "Tag group detected!"
c.execute("UPDATE tags SET count = %s WHERE tag_group = %s", (count, tag_group))
else:
c.execute("UPDATE tags SET count = %s WHERE tag_id = %s", (count, tagid[tag]))
except KeyError:
print now() + "Error updating tag: No tag %s found!" % (tag, )
c.execute("SELECT count FROM categories WHERE cat_id = %s", (cat,))
t = c.fetchone()
if t == None:
print now() + "Error updating count: No category %d found!" % (cat, )
else:
count = t[0] + 1
c.execute("UPDATE categories SET count = %s WHERE cat_id = %s", (count, cat))
print now() + "Inserted item: %d, %d" % (cat, mid)
#counting
c.execute("SELECT COUNT(*) FROM tweets WHERE post_datetime > %s", (datetime.combine(date.today(), time()),))
t = c.fetchone()
if t == None:
count = 0
else:
count = t[0]
c.execute("UPDATE counts SET count = %s WHERE type = %s", (count, "tweets_today"))
c.execute("SELECT COUNT(*) FROM tweets WHERE post_datetime > %s", (datetime.combine(date.today(), time()) - timedelta(days = datetime.now().isoweekday() - 1),))
t = c.fetchone()
if t == None:
count = 0
else:
count = t[0]
c.execute("UPDATE counts SET count = %s WHERE type = %s", (count, "tweets_thisweek"))
db.commit()
c.close()
print now() + "Wrote Database."
os.unlink(LOCK)
| Python |
#!/usr/bin/env python
#coding=utf-8
catelist = [
(1, u"传统网络Internet"),
(2, u"移动互联"),
(3, u"网游"),
(4, u"电子商务_B2C/团购"),
(5, u"软件、电信"),
(6, u"新媒体"),
(7, u"风投/投行"),
(8, u"其他外企"),
]
idlist = [
[1, (u"超超Sandy", "d11c25990634d0e486235f1b42a55f9f", "89859ba49065135017b894df5e5a9089")],
[1, (u"传统网络2", "9257d982dcbc26d21fa4f0afb16a54be", "e99c1ae713e14edc3ec3abb7e2344be3")],
[2, (u"冬冬Billy", "f6449dd703d66cf2be5274f321416958", "31c47db4cd79e43a9196871a554d0847")],
[2, (u"新潮-独", "e17cec5e79cd81704aa4b73d15caf639", "983582e2b4b880cc35caa7ac38ce3449")],
[2, (u"移动互联2", "6193a010668f5dcc106e671babf4fbe1", "605e4449590b2c3d96d34b049f96fdbd")],
[3, (u"田田July", "032ec596fa363aa9bd3e5e5917f6aea4", "9e0c243fa3ff3515765510ba4010c411")],
[3, (u"网游2", "743700d7ec385d0b740ecc9a4ef519d4", "b89c6d406e235ab3c49ccea1d82b5622")],
[4, (u"田田Lily", "3ef7fc951a66918dd1cd722485fe1686", "74f524fe376ce995703e73e63407684f")],
[4, (u"电子商务临2", "669001d16b1641a2138d529b435eaefb", "13f58a73995fd2b80bc0aa875ad363f0")],
[5, (u"小朱Linda", "0c10534f393fe08451edb140e3b1150d", "423fd333a2542dbf6e2a38119a6e7e04")],
[5, (u"软件电信2", "f577ad7699dc1a74330bc41329c2ce71", "20cc173dbb46a6784588767e71de03ef")],
[6, (u"小王trueman", "1f8f7db82cdbc346a91840cef2bc1cb9", "a16ead9ee3b6b3f43e601de127275ddc")],
[6, (u"新媒体2", "fc565ccfa32bdb962becc8d49a5a37d3", "8504469c6cad83cde0998299aca8b2fa")],
[7, (u"小毕Simon", "4151efe34301f5fddb9d34fc72e5f4a4", "dc4a07e8b7936d688726604a7442e4bc")],
[7, (u"风投2", "b14cbaaae5e46079770ea77feeaa0c91", "2dd7a1e5bb6036d69b2c983aa3f2a682")],
[8, (u"小黄Lily", "8ee871ac7d18e0141b54077fefd58af6", "dc5cda5a9a4ab5c5a5cd53f85f1f7915")],
[8, (u"外企名企2", "6712203ce54da88930f72014a0ef90bd", "d97779c02d60cacbabd0c398cb8acd93")],
]
| Python |
from pymining.segmenter import Segmenter
from pymining.configuration import Configuration
class detect:
def __init__(self):
self.cfg = Configuration.FromFile("pymining/conf/test.xml")
self.segmenter = Segmenter(self.cfg, "segmenter")
def Split(self, line):
wordList = self.segmenter.Split(line)
return wordList
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from urllib2 import Request, urlopen
import base64
from weibopy import oauth
from weibopy.error import WeibopError
from weibopy.api import API
class AuthHandler(object):
def apply_auth(self, url, method, headers, parameters):
"""Apply authentication headers to request"""
raise NotImplementedError
def get_username(self):
"""Return the username of the authenticated user"""
raise NotImplementedError
class BasicAuthHandler(AuthHandler):
def __init__(self, username, password):
self.username = username
self._b64up = base64.b64encode('%s:%s' % (username, password))
def apply_auth(self, url, method, headers, parameters):
headers['Authorization'] = 'Basic %s' % self._b64up
def get_username(self):
return self.username
class OAuthHandler(AuthHandler):
"""OAuth authentication handler"""
OAUTH_HOST = 'api.t.sina.com.cn'
OAUTH_ROOT = '/oauth/'
def __init__(self, consumer_key, consumer_secret, callback=None, secure=False):
self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.request_token = None
self.access_token = None
self.callback = callback
self.username = None
self.secure = secure
def _get_oauth_url(self, endpoint):
if self.secure:
prefix = 'https://'
else:
prefix = 'http://'
return prefix + self.OAUTH_HOST + self.OAUTH_ROOT + endpoint
def apply_auth(self, url, method, headers, parameters):
request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer, http_url=url, http_method=method,
token=self.access_token, parameters=parameters
)
request.sign_request(self._sigmethod, self._consumer, self.access_token)
headers.update(request.to_header())
def _get_request_token(self):
try:
url = self._get_oauth_url('request_token')
request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer, http_url=url, callback=self.callback
)
request.sign_request(self._sigmethod, self._consumer, None)
resp = urlopen(Request(url, headers=request.to_header()))
return oauth.OAuthToken.from_string(resp.read())
except Exception, e:
raise WeibopError(e)
def set_request_token(self, key, secret):
self.request_token = oauth.OAuthToken(key, secret)
def set_access_token(self, key, secret):
self.access_token = oauth.OAuthToken(key, secret)
def get_authorization_url(self, signin_with_twitter=False):
"""Get the authorization URL to redirect the user"""
try:
# get the request token
self.request_token = self._get_request_token()
# build auth request and return as url
if signin_with_twitter:
url = self._get_oauth_url('authenticate')
else:
url = self._get_oauth_url('authorize')
request = oauth.OAuthRequest.from_token_and_callback(
token=self.request_token, http_url=url
)
return request.to_url()
except Exception, e:
raise WeibopError(e)
def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
# build request
request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer,
token=self.request_token, http_url=url,
verifier=str(verifier)
)
request.sign_request(self._sigmethod, self._consumer, self.request_token)
# send request
resp = urlopen(Request(url, headers=request.to_header()))
self.access_token = oauth.OAuthToken.from_string(resp.read())
print 'Access token key: '+ str(self.access_token.key)
print 'Access token secret: '+ str(self.access_token.secret)
return self.access_token
except Exception, e:
raise WeibopError(e)
def setToken(self, token, tokenSecret):
self.access_token = oauth.OAuthToken(token, tokenSecret)
def get_username(self):
if self.username is None:
api = API(self)
user = api.verify_credentials()
if user:
self.username = user.screen_name
else:
raise WeibopError("Unable to get username, invalid oauth token!")
return self.username | Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
class WeibopError(Exception):
"""Weibopy exception"""
def __init__(self, reason):
self.reason = reason.encode('utf-8')
def __str__(self):
return self.reason
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from weibopy.utils import parse_datetime, parse_html_value, parse_a_href, \
parse_search_datetime, unescape_html
class ResultSet(list):
"""A list like object that holds results from a Twitter API query."""
class Model(object):
def __init__(self, api=None):
self._api = api
def __getstate__(self):
# pickle
pickle = dict(self.__dict__)
del pickle['_api'] # do not pickle the API reference
return pickle
@classmethod
def parse(cls, api, json):
"""Parse a JSON object into a model instance."""
raise NotImplementedError
@classmethod
def parse_list(cls, api, json_list):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
for obj in json_list:
results.append(cls.parse(api, obj))
return results
class Status(Model):
@classmethod
def parse(cls, api, json):
status = cls(api)
for k, v in json.items():
if k == 'user':
user = User.parse(api, v)
setattr(status, 'author', user)
setattr(status, 'user', user) # DEPRECIATED
elif k == 'screen_name':
setattr(status, k, v)
elif k == 'created_at':
setattr(status, k, parse_datetime(v))
elif k == 'source':
if '<' in v:
setattr(status, k, parse_html_value(v))
setattr(status, 'source_url', parse_a_href(v))
else:
setattr(status, k, v)
elif k == 'retweeted_status':
setattr(status, k, User.parse(api, v))
elif k == 'geo':
setattr(status, k, Geo.parse(api, v))
else:
setattr(status, k, v)
return status
def destroy(self):
return self._api.destroy_status(self.id)
def retweet(self):
return self._api.retweet(self.id)
def retweets(self):
return self._api.retweets(self.id)
def favorite(self):
return self._api.create_favorite(self.id)
class Geo(Model):
@classmethod
def parse(cls, api, json):
geo = cls(api)
if json is not None:
for k, v in json.items():
setattr(geo, k, v)
return geo
class Comments(Model):
@classmethod
def parse(cls, api, json):
comments = cls(api)
for k, v in json.items():
if k == 'user':
user = User.parse(api, v)
setattr(comments, 'author', user)
setattr(comments, 'user', user)
elif k == 'status':
status = Status.parse(api, v)
setattr(comments, 'user', status)
elif k == 'created_at':
setattr(comments, k, parse_datetime(v))
elif k == 'reply_comment':
setattr(comments, k, User.parse(api, v))
else:
setattr(comments, k, v)
return comments
def destroy(self):
return self._api.destroy_status(self.id)
def retweet(self):
return self._api.retweet(self.id)
def retweets(self):
return self._api.retweets(self.id)
def favorite(self):
return self._api.create_favorite(self.id)
class User(Model):
@classmethod
def parse(cls, api, json):
user = cls(api)
for k, v in json.items():
if k == 'created_at':
setattr(user, k, parse_datetime(v))
elif k == 'status':
setattr(user, k, Status.parse(api, v))
elif k == 'screen_name':
setattr(user, k, v)
elif k == 'following':
# twitter sets this to null if it is false
if v is True:
setattr(user, k, True)
else:
setattr(user, k, False)
else:
setattr(user, k, v)
return user
@classmethod
def parse_list(cls, api, json_list):
if isinstance(json_list, list):
item_list = json_list
else:
item_list = json_list['users']
results = ResultSet()
for obj in item_list:
results.append(cls.parse(api, obj))
return results
def timeline(self, **kargs):
return self._api.user_timeline(user_id=self.id, **kargs)
def friends(self, **kargs):
return self._api.friends(user_id=self.id, **kargs)
def followers(self, **kargs):
return self._api.followers(user_id=self.id, **kargs)
def follow(self):
self._api.create_friendship(user_id=self.id)
self.following = True
def unfollow(self):
self._api.destroy_friendship(user_id=self.id)
self.following = False
def lists_memberships(self, *args, **kargs):
return self._api.lists_memberships(user=self.screen_name, *args, **kargs)
def lists_subscriptions(self, *args, **kargs):
return self._api.lists_subscriptions(user=self.screen_name, *args, **kargs)
def lists(self, *args, **kargs):
return self._api.lists(user=self.screen_name, *args, **kargs)
def followers_ids(self, *args, **kargs):
return self._api.followers_ids(user_id=self.id, *args, **kargs)
class DirectMessage(Model):
@classmethod
def parse(cls, api, json):
dm = cls(api)
for k, v in json.items():
if k == 'sender' or k == 'recipient':
setattr(dm, k, User.parse(api, v))
elif k == 'created_at':
setattr(dm, k, parse_datetime(v))
else:
setattr(dm, k, v)
return dm
class Friendship(Model):
@classmethod
def parse(cls, api, json):
source = cls(api)
for k, v in json['source'].items():
setattr(source, k, v)
# parse target
target = cls(api)
for k, v in json['target'].items():
setattr(target, k, v)
return source, target
class SavedSearch(Model):
@classmethod
def parse(cls, api, json):
ss = cls(api)
for k, v in json.items():
if k == 'created_at':
setattr(ss, k, parse_datetime(v))
else:
setattr(ss, k, v)
return ss
def destroy(self):
return self._api.destroy_saved_search(self.id)
class SearchResult(Model):
@classmethod
def parse(cls, api, json):
result = cls()
for k, v in json.items():
if k == 'created_at':
setattr(result, k, parse_search_datetime(v))
elif k == 'source':
setattr(result, k, parse_html_value(unescape_html(v)))
else:
setattr(result, k, v)
return result
@classmethod
def parse_list(cls, api, json_list, result_set=None):
results = ResultSet()
results.max_id = json_list.get('max_id')
results.since_id = json_list.get('since_id')
results.refresh_url = json_list.get('refresh_url')
results.next_page = json_list.get('next_page')
results.results_per_page = json_list.get('results_per_page')
results.page = json_list.get('page')
results.completed_in = json_list.get('completed_in')
results.query = json_list.get('query')
for obj in json_list['results']:
results.append(cls.parse(api, obj))
return results
class List(Model):
@classmethod
def parse(cls, api, json):
lst = List(api)
for k,v in json.items():
if k == 'user':
setattr(lst, k, User.parse(api, v))
else:
setattr(lst, k, v)
return lst
@classmethod
def parse_list(cls, api, json_list, result_set=None):
results = ResultSet()
for obj in json_list['lists']:
results.append(cls.parse(api, obj))
return results
def update(self, **kargs):
return self._api.update_list(self.slug, **kargs)
def destroy(self):
return self._api.destroy_list(self.slug)
def timeline(self, **kargs):
return self._api.list_timeline(self.user.screen_name, self.slug, **kargs)
def add_member(self, id):
return self._api.add_list_member(self.slug, id)
def remove_member(self, id):
return self._api.remove_list_member(self.slug, id)
def members(self, **kargs):
return self._api.list_members(self.user.screen_name, self.slug, **kargs)
def is_member(self, id):
return self._api.is_list_member(self.user.screen_name, self.slug, id)
def subscribe(self):
return self._api.subscribe_list(self.user.screen_name, self.slug)
def unsubscribe(self):
return self._api.unsubscribe_list(self.user.screen_name, self.slug)
def subscribers(self, **kargs):
return self._api.list_subscribers(self.user.screen_name, self.slug, **kargs)
def is_subscribed(self, id):
return self._api.is_subscribed_list(self.user.screen_name, self.slug, id)
class JSONModel(Model):
@classmethod
def parse(cls, api, json):
lst = JSONModel(api)
for k,v in json.items():
setattr(lst, k, v)
return lst
class IDSModel(Model):
@classmethod
def parse(cls, api, json):
ids = IDSModel(api)
for k, v in json.items():
setattr(ids, k, v)
return ids
class Counts(Model):
@classmethod
def parse(cls, api, json):
ids = Counts(api)
for k, v in json.items():
setattr(ids, k, v)
return ids
class ModelFactory(object):
"""
Used by parsers for creating instances
of models. You may subclass this factory
to add your own extended models.
"""
status = Status
comments = Comments
user = User
direct_message = DirectMessage
friendship = Friendship
saved_search = SavedSearch
search_result = SearchResult
list = List
json = JSONModel
ids_list = IDSModel
counts = Counts
| Python |
"""
The MIT License
Copyright (c) 2007 Leah Culver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import cgi
import urllib
import time
import random
import urlparse
import hmac
import binascii
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class OAuthError(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occured.'):
self.message = message
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s, safe='~')
def _utf8_str(s):
"""Convert unicode to utf-8."""
if isinstance(s, unicode):
return s.encode("utf-8")
else:
return str(s)
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class OAuthConsumer(object):
"""Consumer of OAuth authentication.
OAuthConsumer is a data type that represents the identity of the Consumer
via its shared secret with the Service Provider.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
class OAuthToken(object):
"""OAuthToken is a data type that represents an End User via either an access
or request token.
key -- the token
secret -- the token secret
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
def from_string(s):
""" Returns a token from something like:
oauth_token_secret=xxx&oauth_token=xxx
"""
params = cgi.parse_qs(s, keep_blank_values=False)
key = params['oauth_token'][0]
secret = params['oauth_token_secret'][0]
token = OAuthToken(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
from_string = staticmethod(from_string)
def __str__(self):
return self.to_string()
class OAuthRequest(object):
"""OAuthRequest represents the request and can be serialized.
OAuth parameters:
- oauth_consumer_key
- oauth_token
- oauth_signature_method
- oauth_signature
- oauth_timestamp
- oauth_nonce
- oauth_version
- oauth_verifier
... any additional parameters, as defined by the Service Provider.
"""
parameters = None # OAuth parameters.
http_method = HTTP_METHOD
http_url = None
version = VERSION
def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None):
self.http_method = http_method
self.http_url = http_url
self.parameters = parameters or {}
def set_parameter(self, parameter, value):
self.parameters[parameter] = value
def get_parameter(self, parameter):
try:
return self.parameters[parameter]
except:
raise OAuthError('Parameter not found: %s' % parameter)
def _get_timestamp_nonce(self):
return self.get_parameter('oauth_timestamp'), self.get_parameter(
'oauth_nonce')
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
parameters = {}
for k, v in self.parameters.iteritems():
# Ignore oauth parameters.
if k.find('oauth_') < 0:
parameters[k] = v
return parameters
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
auth_header = 'OAuth realm="%s"' % realm
# Add the oauth parameters.
if self.parameters:
for k, v in self.parameters.iteritems():
if k[:6] == 'oauth_':
auth_header += ', %s="%s"' % (k, escape(str(v)))
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \
for k, v in self.parameters.iteritems()])
def to_url(self):
"""Serialize as a URL for a GET request."""
return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata())
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
params = self.parameters
try:
# Exclude the signature if it exists.
del params['oauth_signature']
except:
pass
# Escape key values before sorting.
key_values = [(escape(_utf8_str(k)), escape(_utf8_str(v))) \
for k,v in params.items()]
# Sort lexicographically, first after key, then after value.
key_values.sort()
# Combine key value pairs into a string.
return '&'.join(['%s=%s' % (k, v) for k, v in key_values])
def get_normalized_http_method(self):
"""Uppercases the http method."""
return self.http_method.upper()
def get_normalized_http_url(self):
"""Parses the URL and rebuilds it to be scheme://host/path."""
parts = urlparse.urlparse(self.http_url)
scheme, netloc, path = parts[:3]
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
return '%s://%s%s' % (scheme, netloc, path)
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of build_signature."""
# Set the signature method.
self.set_parameter('oauth_signature_method',
signature_method.get_name())
# Set the signature.
self.set_parameter('oauth_signature',self.build_signature(signature_method, consumer, token))
def build_signature(self, signature_method, consumer, token):
"""Calls the build signature method within the signature method."""
return signature_method.build_signature(self, consumer, token)
def from_request(http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = OAuthRequest._split_header(auth_header)
parameters.update(header_params)
except:
raise OAuthError('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = OAuthRequest._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = OAuthRequest._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return OAuthRequest(http_method, http_url, parameters)
return None
from_request = staticmethod(from_request)
def from_consumer_and_token(oauth_consumer, token=None,
callback=None, verifier=None, http_method=HTTP_METHOD,
http_url=None, parameters=None):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': oauth_consumer.key,
'oauth_timestamp': generate_timestamp(),
'oauth_nonce': generate_nonce(),
'oauth_version': OAuthRequest.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.callback:
parameters['oauth_callback'] = token.callback
# 1.0a support for verifier.
if verifier:
parameters['oauth_verifier'] = verifier
elif callback:
# 1.0a support for callback in the request token request.
parameters['oauth_callback'] = callback
return OAuthRequest(http_method, http_url, parameters)
from_consumer_and_token = staticmethod(from_consumer_and_token)
def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD,
http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return OAuthRequest(http_method, http_url, parameters)
from_token_and_callback = staticmethod(from_token_and_callback)
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
_split_header = staticmethod(_split_header)
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = cgi.parse_qs(param_str, keep_blank_values=False)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
_split_url_string = staticmethod(_split_url_string)
class OAuthServer(object):
"""A worker to check the validity of a request against a data store."""
timestamp_threshold = 300 # In seconds, five minutes.
version = VERSION
signature_methods = None
data_store = None
def __init__(self, data_store=None, signature_methods=None):
self.data_store = data_store
self.signature_methods = signature_methods or {}
def set_data_store(self, data_store):
self.data_store = data_store
def get_data_store(self):
return self.data_store
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.get_name()] = signature_method
return self.signature_methods
def fetch_request_token(self, oauth_request):
"""Processes a request_token request and returns the
request token on success.
"""
try:
# Get the request token for authorization.
token = self._get_token(oauth_request, 'request')
except OAuthError:
# No token required for the initial token request.
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
callback = self.get_callback(oauth_request)
except OAuthError:
callback = None # 1.0, no callback specified.
self._check_signature(oauth_request, consumer, None)
# Fetch a new token.
token = self.data_store.fetch_request_token(consumer, callback)
return token
def fetch_access_token(self, oauth_request):
"""Processes an access_token request and returns the
access token on success.
"""
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
verifier = self._get_verifier(oauth_request)
except OAuthError:
verifier = None
# Get the request token.
token = self._get_token(oauth_request, 'request')
self._check_signature(oauth_request, consumer, token)
new_token = self.data_store.fetch_access_token(consumer, token, verifier)
return new_token
def verify_request(self, oauth_request):
"""Verifies an api call and checks all the parameters."""
# -> consumer and token
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
# Get the access token.
token = self._get_token(oauth_request, 'access')
self._check_signature(oauth_request, consumer, token)
parameters = oauth_request.get_nonoauth_parameters()
return consumer, token, parameters
def authorize_token(self, token, user):
"""Authorize a request token."""
return self.data_store.authorize_request_token(token, user)
def get_callback(self, oauth_request):
"""Get the callback URL."""
return oauth_request.get_parameter('oauth_callback')
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _get_version(self, oauth_request):
"""Verify the correct version request for this server."""
try:
version = oauth_request.get_parameter('oauth_version')
except:
version = VERSION
if version and version != self.version:
raise OAuthError('OAuth version %s not supported.' % str(version))
return version
def _get_signature_method(self, oauth_request):
"""Figure out the signature with some defaults."""
try:
signature_method = oauth_request.get_parameter(
'oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise OAuthError('Signature method %s not supported try one of the '
'following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_consumer(self, oauth_request):
consumer_key = oauth_request.get_parameter('oauth_consumer_key')
consumer = self.data_store.lookup_consumer(consumer_key)
if not consumer:
raise OAuthError('Invalid consumer.')
return consumer
def _get_token(self, oauth_request, token_type='access'):
"""Try to find the token for the provided request token key."""
token_field = oauth_request.get_parameter('oauth_token')
token = self.data_store.lookup_token(token_type, token_field)
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return token
def _get_verifier(self, oauth_request):
return oauth_request.get_parameter('oauth_verifier')
def _check_signature(self, oauth_request, consumer, token):
timestamp, nonce = oauth_request._get_timestamp_nonce()
self._check_timestamp(timestamp)
self._check_nonce(consumer, token, nonce)
signature_method = self._get_signature_method(oauth_request)
try:
signature = oauth_request.get_parameter('oauth_signature')
except:
raise OAuthError('Missing signature.')
# Validate the signature.
valid_sig = signature_method.check_signature(oauth_request, consumer,
token, signature)
if not valid_sig:
key, base = signature_method.build_signature_base_string(
oauth_request, consumer, token)
raise OAuthError('Invalid signature. Expected signature base '
'string: %s' % base)
built = signature_method.build_signature(oauth_request, consumer, token)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = abs(now - timestamp)
if lapsed > self.timestamp_threshold:
raise OAuthError('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' %
(timestamp, now, self.timestamp_threshold))
def _check_nonce(self, consumer, token, nonce):
"""Verify that the nonce is uniqueish."""
nonce = self.data_store.lookup_nonce(consumer, token, nonce)
if nonce:
raise OAuthError('Nonce already used: %s' % str(nonce))
class OAuthClient(object):
"""OAuthClient is a worker to attempt to execute a request."""
consumer = None
token = None
def __init__(self, oauth_consumer, oauth_token):
self.consumer = oauth_consumer
self.token = oauth_token
def get_consumer(self):
return self.consumer
def get_token(self):
return self.token
def fetch_request_token(self, oauth_request):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_access_token(self, oauth_request):
"""-> OAuthToken."""
raise NotImplementedError
def access_resource(self, oauth_request):
"""-> Some protected resource."""
raise NotImplementedError
class OAuthDataStore(object):
"""A database abstraction used to lookup consumers and tokens."""
def lookup_consumer(self, key):
"""-> OAuthConsumer."""
raise NotImplementedError
def lookup_token(self, oauth_consumer, token_type, token_token):
"""-> OAuthToken."""
raise NotImplementedError
def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_request_token(self, oauth_consumer, oauth_callback):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
"""-> OAuthToken."""
raise NotImplementedError
def authorize_request_token(self, oauth_token, user):
"""-> OAuthToken."""
raise NotImplementedError
class OAuthSignatureMethod(object):
"""A strategy class that implements a signature method."""
def get_name(self):
"""-> str."""
raise NotImplementedError
def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token):
"""-> str key, str raw."""
raise NotImplementedError
def build_signature(self, oauth_request, oauth_consumer, oauth_token):
"""-> str."""
raise NotImplementedError
def check_signature(self, oauth_request, consumer, token, signature):
built = self.build_signature(oauth_request, consumer, token)
return built == signature
class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod):
def get_name(self):
return 'HMAC-SHA1'
def build_signature_base_string(self, oauth_request, consumer, token):
sig = (
escape(oauth_request.get_normalized_http_method()),
escape(oauth_request.get_normalized_http_url()),
escape(oauth_request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
#print "OAuth base string:" + str(sig)
raw = '&'.join(sig)
return key, raw
def build_signature(self, oauth_request, consumer, token):
"""Builds the base signature string."""
key, raw = self.build_signature_base_string(oauth_request, consumer,
token)
# HMAC object.
try:
import hashlib # 2.5
hashed = hmac.new(key, raw, hashlib.sha1)
except:
import sha # Deprecated
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod):
def get_name(self):
return 'PLAINTEXT'
def build_signature_base_string(self, oauth_request, consumer, token):
"""Concatenates the consumer key and secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def build_signature(self, oauth_request, consumer, token):
key, raw = self.build_signature_base_string(oauth_request, consumer,
token)
return key | Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from weibopy.models import ModelFactory
from weibopy.utils import import_simplejson
from weibopy.error import WeibopError
class Parser(object):
def parse(self, method, payload):
"""
Parse the response payload and return the result.
Returns a tuple that contains the result data and the cursors
(or None if not present).
"""
raise NotImplementedError
def parse_error(self, method, payload):
"""
Parse the error message from payload.
If unable to parse the message, throw an exception
and default error message will be used.
"""
raise NotImplementedError
class JSONParser(Parser):
payload_format = 'json'
def __init__(self):
self.json_lib = import_simplejson()
def parse(self, method, payload):
try:
json = self.json_lib.loads(payload)
except Exception, e:
print "Failed to parse JSON payload:"+ str(payload)
raise WeibopError('Failed to parse JSON payload: %s' % e)
#if isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
# cursors = json['previous_cursor'], json['next_cursor']
# return json, cursors
#else:
return json
def parse_error(self, method, payload):
return self.json_lib.loads(payload)
class ModelParser(JSONParser):
def __init__(self, model_factory=None):
JSONParser.__init__(self)
self.model_factory = model_factory or ModelFactory
def parse(self, method, payload):
try:
if method.payload_type is None: return
model = getattr(self.model_factory, method.payload_type)
except AttributeError:
raise WeibopError('No model for this payload type: %s' % method.payload_type)
json = JSONParser.parse(self, method, payload)
if isinstance(json, tuple):
json, cursors = json
else:
cursors = None
if method.payload_list:
result = model.parse_list(method.api, json)
else:
result = model.parse(method.api, json)
if cursors:
return result, cursors
else:
return result
| Python |
# Copyright 2010 Joshua Roesslein
# See LICENSE for details.
from datetime import datetime
import time
import htmlentitydefs
import re
def parse_datetime(str):
# We must parse datetime this way to work in python 2.4
#return datetime(*(time.strptime(str, '%a %b %d %H:%M:%S +0800 %Y')[0:6]))
#Changed by Felix Yan
try:
a = time.strptime(str, '%a %b %d %H:%M:%S +0800 %Y')[0:6]
except:
print "Error: " + str
a = ""
if len(a)<6:
raise ValueError
else:
return datetime(*a)
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def parse_a_href(atag):
start = atag.find('"') + 1
end = atag.find('"', start)
return atag[start:end]
def parse_search_datetime(str):
# python 2.4
return datetime(*(time.strptime(str, '%a, %d %b %Y %H:%M:%S +0000')[0:6]))
def unescape_html(text):
"""Created by Fredrik Lundh (http://effbot.org/zone/re-sub.htm#unescape-html)"""
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, unicode):
arg = arg.encode('utf-8')
elif not isinstance(arg, str):
arg = str(arg)
return arg
def import_simplejson():
try:
import simplejson as json
except ImportError:
try:
import json # Python 2.6+
except ImportError:
try:
from django.utils import simplejson as json # Google App Engine
except ImportError:
raise ImportError, "Can't load a json library"
return json
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from weibopy.error import WeibopError
from weibopy.utils import convert_to_utf8_str
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', False)
search_api = config.get('search_api', False)
def __init__(self, api, args, kargs):
# If authentication is required and no credentials
# are provided, throw an error.
if self.require_auth and not api.auth:
raise WeibopError('Authentication required!')
self.api = api
self.post_data = kargs.pop('post_data', None)
self.retry_count = kargs.pop('retry_count', api.retry_count)
self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_api:
self.api_root = api.search_root
else:
self.api_root = api.api_root
# Perform any path variable substitution
self.build_path()
if api.secure:
self.scheme = 'https://'
else:
self.scheme = 'http://'
if self.search_api:
self.host = api.search_host
else:
self.host = api.host
# Manually set Host header to fix an issue in python 2.5
# or older where Host is set including the 443 port.
# This causes Twitter to issue 301 redirect.
# See Issue http://github.com/joshthecoder/tweepy/issues/#issue/12
self.headers['Host'] = self.host
def build_parameters(self, args, kargs):
self.parameters = {}
for idx, arg in enumerate(args):
try:
self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
except IndexError:
raise WeibopError('Too many parameters supplied!')
for k, arg in kargs.items():
if arg is None:
continue
if k in self.parameters:
raise WeibopError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
if name == 'user' and self.api.auth:
value = self.api.auth.get_username()
else:
try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise WeibopError('No parameter value found for path variable: %s' % name)
del self.parameters[name]
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if self.api.source is not None:
self.parameters.setdefault('source',self.api.source)
if len(self.parameters):
if self.method == 'GET':
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
else:
self.headers.setdefault("User-Agent","python")
if self.post_data is None:
self.headers.setdefault("Accept","text/html")
self.headers.setdefault("Content-Type","application/x-www-form-urlencoded")
self.post_data = urllib.urlencode(self.parameters)
# Query the cache if one is available
# and this request uses a GET method.
if self.api.cache and self.method == 'GET':
cache_result = self.api.cache.get(url)
# if cache result found and not expired, return it
if cache_result:
# must restore api reference
if isinstance(cache_result, list):
for result in cache_result:
result._api = self.api
else:
cache_result._api = self.api
return cache_result
#urllib.urlencode(self.parameters)
# Continue attempting request until successful
# or maximum number of retries is reached.
sTime = time.time()
retries_performed = 0
while retries_performed < self.retry_count + 1:
# Open connection
# FIXME: add timeout
if self.api.secure:
conn = httplib.HTTPSConnection(self.host)
else:
conn = httplib.HTTPConnection(self.host)
# Apply authentication
if self.api.auth:
self.api.auth.apply_auth(
self.scheme + self.host + url,
self.method, self.headers, self.parameters
)
# Execute request
try:
conn.request(self.method, url, headers=self.headers, body=self.post_data)
resp = conn.getresponse()
except Exception, e:
raise WeibopError('Failed to send request: %s' % e + "url=" + str(url) +",self.headers="+ str(self.headers))
# Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(self.retry_delay)
retries_performed += 1
# If an error was returned, throw an exception
body = resp.read()
self.api.last_response = resp
if self.api.log is not None:
requestUrl = "URL:http://"+ self.host + url
eTime = '%.0f' % ((time.time() - sTime) * 1000)
postData = ""
if self.post_data is not None:
postData = ",post:"+ self.post_data[0:500]
self.api.log.debug(requestUrl +",time:"+ str(eTime)+ postData+",result:"+ body )
if resp.status != 200:
try:
json = self.api.parser.parse_error(self, body)
error_code = json['error_code']
error = json['error']
error_msg = 'error_code:' + error_code +','+ error
except Exception:
error_msg = "Twitter error response: status code = %s" % resp.status
raise WeibopError(error_msg)
# Parse the response payload
result = self.api.parser.parse(self, body)
conn.close()
# Store result into cache if one is available.
if self.api.cache and self.method == 'GET' and result:
self.api.cache.store(url, result)
return result
def _call(api, *args, **kargs):
method = APIMethod(api, args, kargs)
return method.execute()
# Set pagination mode
if 'cursor' in APIMethod.allowed_param:
_call.pagination_mode = 'cursor'
elif 'page' in APIMethod.allowed_param:
_call.pagination_mode = 'page'
return _call
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
weibo API library
"""
__version__ = '1.5'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from weibopy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, ModelFactory, IDSModel
from weibopy.error import WeibopError
from weibopy.api import API
from weibopy.cache import Cache, MemoryCache, FileCache
from weibopy.auth import BasicAuthHandler, OAuthHandler
from weibopy.streaming import Stream, StreamListener
from weibopy.cursor import Cursor
# Global, unauthenticated instance of API
api = API()
def debug(enable=True, level=1):
import httplib
httplib.HTTPConnection.debuglevel = level
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
from socket import timeout
from threading import Thread
from time import sleep
import urllib
from weibopy.auth import BasicAuthHandler
from weibopy.models import Status
from weibopy.api import API
from weibopy.error import WeibopError
from weibopy.utils import import_simplejson
json = import_simplejson()
STREAM_VERSION = 1
class StreamListener(object):
def __init__(self, api=None):
self.api = api or API()
def on_data(self, data):
"""Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data. Return False to stop stream and close connection.
"""
if 'in_reply_to_status_id' in data:
status = Status.parse(self.api, json.loads(data))
if self.on_status(status) is False:
return False
elif 'delete' in data:
delete = json.loads(data)['delete']['status']
if self.on_delete(delete['id'], delete['user_id']) is False:
return False
elif 'limit' in data:
if self.on_limit(json.loads(data)['limit']['track']) is False:
return False
def on_status(self, status):
"""Called when a new status arrives"""
return
def on_delete(self, status_id, user_id):
"""Called when a delete notice arrives for a status"""
return
def on_limit(self, track):
"""Called when a limitation notice arrvies"""
return
def on_error(self, status_code):
"""Called when a non-200 status code is returned"""
return False
def on_timeout(self):
"""Called when stream connection times out"""
return
class Stream(object):
host = 'stream.twitter.com'
def __init__(self, username, password, listener, timeout=5.0, retry_count = None,
retry_time = 10.0, snooze_time = 5.0, buffer_size=1500, headers=None):
self.auth = BasicAuthHandler(username, password)
self.running = False
self.timeout = timeout
self.retry_count = retry_count
self.retry_time = retry_time
self.snooze_time = snooze_time
self.buffer_size = buffer_size
self.listener = listener
self.api = API()
self.headers = headers or {}
self.body = None
def _run(self):
# setup
self.auth.apply_auth(None, None, self.headers, None)
# enter loop
error_counter = 0
conn = None
while self.running:
if self.retry_count and error_counter > self.retry_count:
# quit if error count greater than retry count
break
try:
conn = httplib.HTTPConnection(self.host)
conn.connect()
conn.sock.settimeout(self.timeout)
conn.request('POST', self.url, self.body, headers=self.headers)
resp = conn.getresponse()
if resp.status != 200:
if self.listener.on_error(resp.status) is False:
break
error_counter += 1
sleep(self.retry_time)
else:
error_counter = 0
self._read_loop(resp)
except timeout:
if self.listener.on_timeout() == False:
break
if self.running is False:
break
conn.close()
sleep(self.snooze_time)
except Exception:
# any other exception is fatal, so kill loop
break
# cleanup
self.running = False
if conn:
conn.close()
def _read_loop(self, resp):
data = ''
while self.running:
if resp.isclosed():
break
# read length
length = ''
while True:
c = resp.read(1)
if c == '\n':
break
length += c
length = length.strip()
if length.isdigit():
length = int(length)
else:
continue
# read data and pass into listener
data = resp.read(length)
if self.listener.on_data(data) is False:
self.running = False
def _start(self, async):
self.running = True
if async:
Thread(target=self._run).start()
else:
self._run()
def firehose(self, count=None, async=False):
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/firehose.json?delimited=length' % STREAM_VERSION
if count:
self.url += '&count=%s' % count
self._start(async)
def retweet(self, async=False):
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/retweet.json?delimited=length' % STREAM_VERSION
self._start(async)
def sample(self, count=None, async=False):
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/sample.json?delimited=length' % STREAM_VERSION
if count:
self.url += '&count=%s' % count
self._start(async)
def filter(self, follow=None, track=None, async=False):
params = {}
self.headers['Content-type'] = "application/x-www-form-urlencoded"
if self.running:
raise WeibopError('Stream object already connected!')
self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
if follow:
params['follow'] = ','.join(map(str, follow))
if track:
params['track'] = ','.join(map(str, track))
self.body = urllib.urlencode(params)
self._start(async)
def disconnect(self):
if self.running is False:
return
self.running = False
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import os
import mimetypes
from weibopy.binder import bind_api
from weibopy.error import WeibopError
from weibopy.parsers import ModelParser
class API(object):
"""Twitter API"""
def __init__(self, auth_handler=None,
host='api.t.sina.com.cn', search_host='api.t.sina.com.cn',
cache=None, secure=False, api_root='', search_root='',
retry_count=0, retry_delay=0, retry_errors=None,source=None,
parser=None, log = None):
self.auth = auth_handler
self.host = host
if source == None:
if auth_handler != None:
self.source = self.auth._consumer.key
else:
self.source = source
self.search_host = search_host
self.api_root = api_root
self.search_root = search_root
self.cache = cache
self.secure = secure
self.retry_count = retry_count
self.retry_delay = retry_delay
self.retry_errors = retry_errors
self.parser = parser or ModelParser()
self.log = log
""" statuses/public_timeline """
public_timeline = bind_api(
path = '/statuses/public_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = []
)
""" statuses/home_timeline """
home_timeline = bind_api(
path = '/statuses/home_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/friends_timeline """
friends_timeline = bind_api(
path = '/statuses/friends_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/comment """
comment = bind_api(
path = '/statuses/comment.json',
method = 'POST',
payload_type = 'comments',
allowed_param = ['id', 'cid', 'comment'],
require_auth = True
)
""" statuses/comment_destroy """
comment_destroy = bind_api(
path = '/statuses/comment_destroy/{id}.json',
method = 'POST',
payload_type = 'comments',
allowed_param = ['id'],
require_auth = True
)
""" statuses/comments_timeline """
comments = bind_api(
path = '/statuses/comments.json',
payload_type = 'comments', payload_list = True,
allowed_param = ['id', 'count', 'page'],
require_auth = True
)
""" statuses/comments_timeline """
comments_timeline = bind_api(
path = '/statuses/comments_timeline.json',
payload_type = 'comments', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/comments_by_me """
comments_by_me = bind_api(
path = '/statuses/comments_by_me.json',
payload_type = 'comments', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/user_timeline """
user_timeline = bind_api(
path = '/statuses/user_timeline.json',
payload_type = 'status', payload_list = True,
allowed_param = ['id', 'user_id', 'screen_name', 'since_id',
'max_id', 'count', 'page']
)
""" statuses/mentions """
mentions = bind_api(
path = '/statuses/mentions.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/counts """
counts = bind_api(
path = '/statuses/counts.json',
payload_type = 'counts', payload_list = True,
allowed_param = ['ids'],
require_auth = True
)
""" statuses/unread """
unread = bind_api(
path = '/statuses/unread.json',
payload_type = 'counts'
)
""" statuses/retweeted_by_me """
retweeted_by_me = bind_api(
path = '/statuses/retweeted_by_me.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/retweeted_to_me """
retweeted_to_me = bind_api(
path = '/statuses/retweeted_to_me.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/retweets_of_me """
retweets_of_me = bind_api(
path = '/statuses/retweets_of_me.json',
payload_type = 'status', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" statuses/show """
get_status = bind_api(
path = '/statuses/show.json',
payload_type = 'status',
allowed_param = ['id']
)
""" statuses/update """
update_status = bind_api(
path = '/statuses/update.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['status', 'lat', 'long', 'source'],
require_auth = True
)
""" statuses/upload """
def upload(self, filename, status, lat=None, long=None, source=None):
if source is None:
source=self.source
headers, post_data = API._pack_image(filename, 1024, source=source, status=status, lat=lat, long=long, contentname="pic")
args = [status]
allowed_param = ['status']
if lat is not None:
args.append(lat)
allowed_param.append('lat')
if long is not None:
args.append(long)
allowed_param.append('long')
if source is not None:
args.append(source)
allowed_param.append('source')
return bind_api(
path = '/statuses/upload.json',
method = 'POST',
payload_type = 'status',
require_auth = True,
allowed_param = allowed_param
)(self, *args, post_data=post_data, headers=headers)
""" statuses/reply """
reply = bind_api(
path = '/statuses/reply.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id', 'cid','comment'],
require_auth = True
)
""" statuses/repost """
repost = bind_api(
path = '/statuses/repost.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id', 'status'],
require_auth = True
)
""" statuses/destroy """
destroy_status = bind_api(
path = '/statuses/destroy/{id}.json',
method = 'DELETE',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" statuses/retweet """
retweet = bind_api(
path = '/statuses/retweet/{id}.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" statuses/retweets """
retweets = bind_api(
path = '/statuses/retweets/{id}.json',
payload_type = 'status', payload_list = True,
allowed_param = ['id', 'count'],
require_auth = True
)
""" users/show """
get_user = bind_api(
path = '/users/show.json',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name']
)
""" Get the authenticated user """
def me(self):
return self.get_user(screen_name=self.auth.get_username())
""" users/search """
search_users = bind_api(
path = '/users/search.json',
payload_type = 'user', payload_list = True,
require_auth = True,
allowed_param = ['q', 'per_page', 'page']
)
""" statuses/friends """
friends = bind_api(
path = '/statuses/friends.json',
payload_type = 'user', payload_list = True,
allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor']
)
""" statuses/followers """
followers = bind_api(
path = '/statuses/followers.json',
payload_type = 'user', payload_list = True,
allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor']
)
""" direct_messages """
direct_messages = bind_api(
path = '/direct_messages.json',
payload_type = 'direct_message', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" direct_messages/sent """
sent_direct_messages = bind_api(
path = '/direct_messages/sent.json',
payload_type = 'direct_message', payload_list = True,
allowed_param = ['since_id', 'max_id', 'count', 'page'],
require_auth = True
)
""" direct_messages/new """
new_direct_message = bind_api(
path = '/direct_messages/new.json',
method = 'POST',
payload_type = 'direct_message',
allowed_param = ['id', 'screen_name', 'user_id', 'text'],
require_auth = True
)
""" direct_messages/destroy """
destroy_direct_message = bind_api(
path = '/direct_messages/destroy/{id}.json',
method = 'DELETE',
payload_type = 'direct_message',
allowed_param = ['id'],
require_auth = True
)
""" friendships/create """
create_friendship = bind_api(
path = '/friendships/create.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name', 'follow'],
require_auth = True
)
""" friendships/destroy """
destroy_friendship = bind_api(
path = '/friendships/destroy.json',
method = 'DELETE',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" friendships/exists """
exists_friendship = bind_api(
path = '/friendships/exists.json',
payload_type = 'json',
allowed_param = ['user_a', 'user_b']
)
""" friendships/show """
show_friendship = bind_api(
path = '/friendships/show.json',
payload_type = 'friendship',
allowed_param = ['source_id', 'source_screen_name',
'target_id', 'target_screen_name']
)
""" friends/ids """
friends_ids = bind_api(
path = '/friends/ids.json',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name', 'cursor', 'count'],
require_auth = True
)
""" followers/ids """
followers_ids = bind_api(
path = '/followers/ids.json',
payload_type = 'json',
allowed_param = ['id', 'page'],
)
""" account/verify_credentials """
def verify_credentials(self):
try:
return bind_api(
path = '/account/verify_credentials.json',
payload_type = 'user',
require_auth = True
)(self)
except WeibopError:
return False
""" account/rate_limit_status """
rate_limit_status = bind_api(
path = '/account/rate_limit_status.json',
payload_type = 'json'
)
""" account/update_delivery_device """
set_delivery_device = bind_api(
path = '/account/update_delivery_device.json',
method = 'POST',
allowed_param = ['device'],
payload_type = 'user',
require_auth = True
)
""" account/update_profile_colors """
update_profile_colors = bind_api(
path = '/account/update_profile_colors.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['profile_background_color', 'profile_text_color',
'profile_link_color', 'profile_sidebar_fill_color',
'profile_sidebar_border_color'],
require_auth = True
)
""" account/update_profile_image """
def update_profile_image(self, filename):
headers, post_data = API._pack_image(filename=filename, max_size=700, source=self.source)
return bind_api(
path = '/account/update_profile_image.json',
method = 'POST',
payload_type = 'user',
require_auth = True
)(self, post_data=post_data, headers=headers)
""" account/update_profile_background_image """
def update_profile_background_image(self, filename, *args, **kargs):
headers, post_data = API._pack_image(filename, 800)
bind_api(
path = '/account/update_profile_background_image.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['tile'],
require_auth = True
)(self, post_data=post_data, headers=headers)
""" account/update_profile """
update_profile = bind_api(
path = '/account/update_profile.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['name', 'url', 'location', 'description'],
require_auth = True
)
""" favorites """
favorites = bind_api(
path = '/favorites/{id}.json',
payload_type = 'status', payload_list = True,
allowed_param = ['id', 'page']
)
""" favorites/create """
create_favorite = bind_api(
path = '/favorites/create/{id}.json',
method = 'POST',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" favorites/destroy """
destroy_favorite = bind_api(
path = '/favorites/destroy/{id}.json',
method = 'DELETE',
payload_type = 'status',
allowed_param = ['id'],
require_auth = True
)
""" notifications/follow """
enable_notifications = bind_api(
path = '/notifications/follow.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" notifications/leave """
disable_notifications = bind_api(
path = '/notifications/leave.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" blocks/create """
create_block = bind_api(
path = '/blocks/create.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" blocks/destroy """
destroy_block = bind_api(
path = '/blocks/destroy.json',
method = 'DELETE',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" blocks/exists """
def exists_block(self, *args, **kargs):
try:
bind_api(
path = '/blocks/exists.json',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)(self, *args, **kargs)
except WeibopError:
return False
return True
""" blocks/blocking """
blocks = bind_api(
path = '/blocks/blocking.json',
payload_type = 'user', payload_list = True,
allowed_param = ['page'],
require_auth = True
)
""" blocks/blocking/ids """
blocks_ids = bind_api(
path = '/blocks/blocking/ids.json',
payload_type = 'json',
require_auth = True
)
""" statuses/repost """
report_spam = bind_api(
path = '/report_spam.json',
method = 'POST',
payload_type = 'user',
allowed_param = ['id', 'user_id', 'screen_name'],
require_auth = True
)
""" saved_searches """
saved_searches = bind_api(
path = '/saved_searches.json',
payload_type = 'saved_search', payload_list = True,
require_auth = True
)
""" saved_searches/show """
get_saved_search = bind_api(
path = '/saved_searches/show/{id}.json',
payload_type = 'saved_search',
allowed_param = ['id'],
require_auth = True
)
""" saved_searches/create """
create_saved_search = bind_api(
path = '/saved_searches/create.json',
method = 'POST',
payload_type = 'saved_search',
allowed_param = ['query'],
require_auth = True
)
""" saved_searches/destroy """
destroy_saved_search = bind_api(
path = '/saved_searches/destroy/{id}.json',
method = 'DELETE',
payload_type = 'saved_search',
allowed_param = ['id'],
require_auth = True
)
""" help/test """
def test(self):
try:
bind_api(
path = '/help/test.json',
)(self)
except WeibopError:
return False
return True
def create_list(self, *args, **kargs):
return bind_api(
path = '/%s/lists.json' % self.auth.get_username(),
method = 'POST',
payload_type = 'list',
allowed_param = ['name', 'mode', 'description'],
require_auth = True
)(self, *args, **kargs)
def destroy_list(self, slug):
return bind_api(
path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
method = 'DELETE',
payload_type = 'list',
require_auth = True
)(self)
def update_list(self, slug, *args, **kargs):
return bind_api(
path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
method = 'POST',
payload_type = 'list',
allowed_param = ['name', 'mode', 'description'],
require_auth = True
)(self, *args, **kargs)
lists = bind_api(
path = '/{user}/lists.json',
payload_type = 'list', payload_list = True,
allowed_param = ['user', 'cursor'],
require_auth = True
)
lists_memberships = bind_api(
path = '/{user}/lists/memberships.json',
payload_type = 'list', payload_list = True,
allowed_param = ['user', 'cursor'],
require_auth = True
)
lists_subscriptions = bind_api(
path = '/{user}/lists/subscriptions.json',
payload_type = 'list', payload_list = True,
allowed_param = ['user', 'cursor'],
require_auth = True
)
list_timeline = bind_api(
path = '/{owner}/lists/{slug}/statuses.json',
payload_type = 'status', payload_list = True,
allowed_param = ['owner', 'slug', 'since_id', 'max_id', 'count', 'page']
)
get_list = bind_api(
path = '/{owner}/lists/{slug}.json',
payload_type = 'list',
allowed_param = ['owner', 'slug']
)
def add_list_member(self, slug, *args, **kargs):
return bind_api(
path = '/%s/%s/members.json' % (self.auth.get_username(), slug),
method = 'POST',
payload_type = 'list',
allowed_param = ['id'],
require_auth = True
)(self, *args, **kargs)
def remove_list_member(self, slug, *args, **kargs):
return bind_api(
path = '/%s/%s/members.json' % (self.auth.get_username(), slug),
method = 'DELETE',
payload_type = 'list',
allowed_param = ['id'],
require_auth = True
)(self, *args, **kargs)
list_members = bind_api(
path = '/{owner}/{slug}/members.json',
payload_type = 'user', payload_list = True,
allowed_param = ['owner', 'slug', 'cursor']
)
def is_list_member(self, owner, slug, user_id):
try:
return bind_api(
path = '/%s/%s/members/%s.json' % (owner, slug, user_id),
payload_type = 'user'
)(self)
except WeibopError:
return False
subscribe_list = bind_api(
path = '/{owner}/{slug}/subscribers.json',
method = 'POST',
payload_type = 'list',
allowed_param = ['owner', 'slug'],
require_auth = True
)
unsubscribe_list = bind_api(
path = '/{owner}/{slug}/subscribers.json',
method = 'DELETE',
payload_type = 'list',
allowed_param = ['owner', 'slug'],
require_auth = True
)
list_subscribers = bind_api(
path = '/{owner}/{slug}/subscribers.json',
payload_type = 'user', payload_list = True,
allowed_param = ['owner', 'slug', 'cursor']
)
def is_subscribed_list(self, owner, slug, user_id):
try:
return bind_api(
path = '/%s/%s/subscribers/%s.json' % (owner, slug, user_id),
payload_type = 'user'
)(self)
except WeibopError:
return False
""" trends/available """
trends_available = bind_api(
path = '/trends/available.json',
payload_type = 'json',
allowed_param = ['lat', 'long']
)
""" trends/location """
trends_location = bind_api(
path = '/trends/{woeid}.json',
payload_type = 'json',
allowed_param = ['woeid']
)
""" search """
search = bind_api(
search_api = True,
path = '/search.json',
payload_type = 'search_result', payload_list = True,
allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user']
)
search.pagination_mode = 'page'
""" trends """
trends = bind_api(
search_api = True,
path = '/trends.json',
payload_type = 'json'
)
""" trends/current """
trends_current = bind_api(
search_api = True,
path = '/trends/current.json',
payload_type = 'json',
allowed_param = ['exclude']
)
""" trends/daily """
trends_daily = bind_api(
search_api = True,
path = '/trends/daily.json',
payload_type = 'json',
allowed_param = ['date', 'exclude']
)
""" trends/weekly """
trends_weekly = bind_api(
search_api = True,
path = '/trends/weekly.json',
payload_type = 'json',
allowed_param = ['date', 'exclude']
)
""" Internal use only """
@staticmethod
def _pack_image(filename, max_size, source=None, status=None, lat=None, long=None, contentname="image"):
"""Pack image from file into multipart-formdata post body"""
# image must be less than 700kb in size
try:
if os.path.getsize(filename) > (max_size * 1024):
raise WeibopError('File is too big, must be less than 700kb.')
#except os.error, e:
except os.error:
raise WeibopError('Unable to access file')
# image must be gif, jpeg, or png
file_type = mimetypes.guess_type(filename)
if file_type is None:
raise WeibopError('Could not determine file type')
file_type = file_type[0]
if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
raise WeibopError('Invalid file type for image: %s' % file_type)
# build the mulitpart-formdata body
fp = open(filename, 'rb')
BOUNDARY = 'Tw3ePy'
body = []
if status is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="status"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(status)
if source is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="source"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(source)
if lat is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="lat"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(lat)
if long is not None:
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="long"')
body.append('Content-Type: text/plain; charset=US-ASCII')
body.append('Content-Transfer-Encoding: 8bit')
body.append('')
body.append(long)
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="'+ contentname +'"; filename="%s"' % filename)
body.append('Content-Type: %s' % file_type)
body.append('Content-Transfer-Encoding: binary')
body.append('')
body.append(fp.read())
body.append('--' + BOUNDARY + '--')
body.append('')
fp.close()
body.append('--' + BOUNDARY + '--')
body.append('')
body = '\r\n'.join(body)
# build headers
headers = {
'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
'Content-Length': len(body)
}
return headers, body
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from weibopy.error import WeibopError
class Cursor(object):
"""Pagination helper class"""
def __init__(self, method, *args, **kargs):
if hasattr(method, 'pagination_mode'):
if method.pagination_mode == 'cursor':
self.iterator = CursorIterator(method, args, kargs)
else:
self.iterator = PageIterator(method, args, kargs)
else:
raise WeibopError('This method does not perform pagination')
def pages(self, limit=0):
"""Return iterator for pages"""
if limit > 0:
self.iterator.limit = limit
return self.iterator
def items(self, limit=0):
"""Return iterator for items in each page"""
i = ItemIterator(self.iterator)
i.limit = limit
return i
class BaseIterator(object):
def __init__(self, method, args, kargs):
self.method = method
self.args = args
self.kargs = kargs
self.limit = 0
def next(self):
raise NotImplementedError
def prev(self):
raise NotImplementedError
def __iter__(self):
return self
class CursorIterator(BaseIterator):
def __init__(self, method, args, kargs):
BaseIterator.__init__(self, method, args, kargs)
self.next_cursor = -1
self.prev_cursor = 0
self.count = 0
def next(self):
if self.next_cursor == 0 or (self.limit and self.count == self.limit):
raise StopIteration
data, cursors = self.method(
cursor=self.next_cursor, *self.args, **self.kargs
)
self.prev_cursor, self.next_cursor = cursors
if len(data) == 0:
raise StopIteration
self.count += 1
return data
def prev(self):
if self.prev_cursor == 0:
raise WeibopError('Can not page back more, at first page')
data, self.next_cursor, self.prev_cursor = self.method(
cursor=self.prev_cursor, *self.args, **self.kargs
)
self.count -= 1
return data
class PageIterator(BaseIterator):
def __init__(self, method, args, kargs):
BaseIterator.__init__(self, method, args, kargs)
self.current_page = 0
def next(self):
self.current_page += 1
items = self.method(page=self.current_page, *self.args, **self.kargs)
if len(items) == 0 or (self.limit > 0 and self.current_page > self.limit):
raise StopIteration
return items
def prev(self):
if (self.current_page == 1):
raise WeibopError('Can not page back more, at first page')
self.current_page -= 1
return self.method(page=self.current_page, *self.args, **self.kargs)
class ItemIterator(BaseIterator):
def __init__(self, page_iterator):
self.page_iterator = page_iterator
self.limit = 0
self.current_page = None
self.page_index = -1
self.count = 0
def next(self):
if self.limit > 0 and self.count == self.limit:
raise StopIteration
if self.current_page is None or self.page_index == len(self.current_page) - 1:
# Reached end of current page, get the next page...
self.current_page = self.page_iterator.next()
self.page_index = -1
self.page_index += 1
self.count += 1
return self.current_page[self.page_index]
def prev(self):
if self.current_page is None:
raise WeibopError('Can not go back more, at first page')
if self.page_index == 0:
# At the beginning of the current page, move to next...
self.current_page = self.page_iterator.prev()
self.page_index = len(self.current_page)
if self.page_index == 0:
raise WeibopError('No more items')
self.page_index -= 1
self.count -= 1
return self.current_page[self.page_index]
| Python |
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import time
import threading
import os
import cPickle as pickle
try:
import hashlib
except ImportError:
# python 2.4
import md5 as hashlib
try:
import fcntl
except ImportError:
# Probably on a windows system
# TODO: use win32file
pass
class Cache(object):
"""Cache interface"""
def __init__(self, timeout=60):
"""Initialize the cache
timeout: number of seconds to keep a cached entry
"""
self.timeout = timeout
def store(self, key, value):
"""Add new record to cache
key: entry key
value: data of entry
"""
raise NotImplementedError
def get(self, key, timeout=None):
"""Get cached entry if exists and not expired
key: which entry to get
timeout: override timeout with this value [optional]
"""
raise NotImplementedError
def count(self):
"""Get count of entries currently stored in cache"""
raise NotImplementedError
def cleanup(self):
"""Delete any expired entries in cache."""
raise NotImplementedError
def flush(self):
"""Delete all cached entries"""
raise NotImplementedError
class MemoryCache(Cache):
"""In-memory cache"""
def __init__(self, timeout=60):
Cache.__init__(self, timeout)
self._entries = {}
self.lock = threading.Lock()
def __getstate__(self):
# pickle
return {'entries': self._entries, 'timeout': self.timeout}
def __setstate__(self, state):
# unpickle
self.lock = threading.Lock()
self._entries = state['entries']
self.timeout = state['timeout']
def _is_expired(self, entry, timeout):
return timeout > 0 and (time.time() - entry[0]) >= timeout
def store(self, key, value):
self.lock.acquire()
self._entries[key] = (time.time(), value)
self.lock.release()
def get(self, key, timeout=None):
self.lock.acquire()
try:
# check to see if we have this key
entry = self._entries.get(key)
if not entry:
# no hit, return nothing
return None
# use provided timeout in arguments if provided
# otherwise use the one provided during init.
if timeout is None:
timeout = self.timeout
# make sure entry is not expired
if self._is_expired(entry, timeout):
# entry expired, delete and return nothing
del self._entries[key]
return None
# entry found and not expired, return it
return entry[1]
finally:
self.lock.release()
def count(self):
return len(self._entries)
def cleanup(self):
self.lock.acquire()
try:
for k, v in self._entries.items():
if self._is_expired(v, self.timeout):
del self._entries[k]
finally:
self.lock.release()
def flush(self):
self.lock.acquire()
self._entries.clear()
self.lock.release()
class FileCache(Cache):
"""File-based cache"""
# locks used to make cache thread-safe
cache_locks = {}
def __init__(self, cache_dir, timeout=60):
Cache.__init__(self, timeout)
if os.path.exists(cache_dir) is False:
os.mkdir(cache_dir)
self.cache_dir = cache_dir
if cache_dir in FileCache.cache_locks:
self.lock = FileCache.cache_locks[cache_dir]
else:
self.lock = threading.Lock()
FileCache.cache_locks[cache_dir] = self.lock
if os.name == 'posix':
self._lock_file = self._lock_file_posix
self._unlock_file = self._unlock_file_posix
elif os.name == 'nt':
self._lock_file = self._lock_file_win32
self._unlock_file = self._unlock_file_win32
else:
print 'Warning! FileCache locking not supported on this system!'
self._lock_file = self._lock_file_dummy
self._unlock_file = self._unlock_file_dummy
def _get_path(self, key):
md5 = hashlib.md5()
md5.update(key)
return os.path.join(self.cache_dir, md5.hexdigest())
def _lock_file_dummy(self, path, exclusive=True):
return None
def _unlock_file_dummy(self, lock):
return
def _lock_file_posix(self, path, exclusive=True):
lock_path = path + '.lock'
if exclusive is True:
f_lock = open(lock_path, 'w')
fcntl.lockf(f_lock, fcntl.LOCK_EX)
else:
f_lock = open(lock_path, 'r')
fcntl.lockf(f_lock, fcntl.LOCK_SH)
if os.path.exists(lock_path) is False:
f_lock.close()
return None
return f_lock
def _unlock_file_posix(self, lock):
lock.close()
def _lock_file_win32(self, path, exclusive=True):
# TODO: implement
return None
def _unlock_file_win32(self, lock):
# TODO: implement
return
def _delete_file(self, path):
os.remove(path)
if os.path.exists(path + '.lock'):
os.remove(path + '.lock')
def store(self, key, value):
path = self._get_path(key)
self.lock.acquire()
try:
# acquire lock and open file
f_lock = self._lock_file(path)
datafile = open(path, 'wb')
# write data
pickle.dump((time.time(), value), datafile)
# close and unlock file
datafile.close()
self._unlock_file(f_lock)
finally:
self.lock.release()
def get(self, key, timeout=None):
return self._get(self._get_path(key), timeout)
def _get(self, path, timeout):
if os.path.exists(path) is False:
# no record
return None
self.lock.acquire()
try:
# acquire lock and open
f_lock = self._lock_file(path, False)
datafile = open(path, 'rb')
# read pickled object
created_time, value = pickle.load(datafile)
datafile.close()
# check if value is expired
if timeout is None:
timeout = self.timeout
if timeout > 0 and (time.time() - created_time) >= timeout:
# expired! delete from cache
value = None
self._delete_file(path)
# unlock and return result
self._unlock_file(f_lock)
return value
finally:
self.lock.release()
def count(self):
c = 0
for entry in os.listdir(self.cache_dir):
if entry.endswith('.lock'):
continue
c += 1
return c
def cleanup(self):
for entry in os.listdir(self.cache_dir):
if entry.endswith('.lock'):
continue
self._get(os.path.join(self.cache_dir, entry), None)
def flush(self):
for entry in os.listdir(self.cache_dir):
if entry.endswith('.lock'):
continue
self._delete_file(os.path.join(self.cache_dir, entry))
| Python |
import math
import pickle
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
class NaiveBayes:
def __init__(self, config, nodeName, loadFromFile = False):
#store variable(term)'s likelihood to each class
self.vTable = []
#store prior of each class
self.cPrior = []
#store isTrained by data
self.trained = loadFromFile
self.curNode = config.GetChild(nodeName)
self.modelPath = self.curNode.GetChild("model_path").GetValue()
self.logPath = self.curNode.GetChild("log_path").GetValue()
if (loadFromFile):
f = open(self.modelPath, "r")
modelStr = pickle.load(f)
[self.vTable, self.cPrior] = pickle.loads(modelStr)
f.close()
def Train(self, x, y):
#check parameters
if (x.nRow <> len(y)):
print "ERROR!, x.nRow should == len(y)"
return False
#calculate prior of each class
#1. init cPrior:
yy = set(y)
yy = list(yy)
yy.sort()
self.cPrior = [0 for i in range(yy[len(yy) - 1] + 1)]
#2. fill cPrior
for i in y:
self.cPrior[i] += 1
#calculate likehood of each term
#1. init vTable:
self.vTable = [[0 for i in range(len(self.cPrior))] \
for j in range(x.nCol)]
#2. fill vTable
for r in range(x.nRow):
for i in range(x.rows[r], x.rows[r + 1]):
self.vTable[x.cols[i]][y[r]] += 1
#normalize vTable
for i in range(x.nCol):
for j in range(len(self.cPrior)):
if (self.cPrior[j] > 1e-10):
self.vTable[i][j] /= float(self.cPrior[j])
#normalize cPrior
for i in range(len(self.cPrior)):
self.cPrior[i] /= float(len(y))
self.trained = True
#dump model path
f = open(self.modelPath, "w")
modelStr = pickle.dumps([self.vTable, self.cPrior], 1)
pickle.dump(modelStr, f)
f.close()
return True
def TestSample(self, cols, vals):
#check parameter
if (not self.trained):
print "Error!, not trained!"
return False
if (len(cols) <> len(vals)):
print "Error! len of cols should == len of vals"
return False
#calculate best p
targetP = []
maxP = -1000000000
for target in range(len(self.cPrior)):
curP = 0
curP += math.log(self.cPrior[target])
for c in range(0, len(cols)):
if (self.vTable[cols[c]][target] == 0):
curP += math.log(1e-7)
else:
curP += math.log(self.vTable[cols[c]][target])
#debug
#if (self.logPath <> ""):
# term = PyMining.idToTerm[cols[c]]
# prob = math.log(self.vTable[cols[c]][target] + 1e-7)
# f.write(term.encode("utf-8") + ":" + str(cols[c]) + ":" + str(prob) + "\n")
targetP.append(curP)
if (curP > maxP):
bestY = target
maxP = curP
#normalize probable
ret = []
total = 0
for i in range(len(targetP)):
total += math.exp(targetP[i])
for i in range(len(targetP)):
ret.append((i, math.exp(targetP[i]) / total))
return tuple(ret)
def Test(self, x, y):
#check parameter
if (not self.trained):
print "Error!, not trained!"
return False
if (x.nRow != len(y)):
print "Error! x.nRow should == len(y)"
return False
retY = []
correct = 0
if (self.logPath <> ""):
f = open(self.logPath, "w")
#predict all doc one by one
for r in range(x.nRow):
bestY = -1
maxP = -1000000000
#debug
if (self.logPath <> ""):
f.write("\n ===============new doc=================")
#calculate best p
for target in range(len(self.cPrior)):
curP = 0
if (self.cPrior[target] > 1e-8):
curP += math.log(self.cPrior[target])
else:
curP += math.log(1e-8)
#debug
if (self.logPath <> ""):
f.write("<target> : " + str(target) + "\n")
for c in range(x.rows[r], x.rows[r + 1]):
if (self.vTable[x.cols[c]][target] == 0):
curP += math.log(1e-7)
else:
curP += math.log(self.vTable[x.cols[c]][target])
#debug
if (self.logPath <> ""):
term = PyMining.idToTerm[x.cols[c]]
prob = math.log(self.vTable[x.cols[c]][target] + 1e-7)
f.write(term.encode("utf-8") + ":" + str(x.cols[c]) + ":" + str(prob) + "\n")
if (curP > maxP):
bestY = target
maxP = curP
#debug
if (self.logPath <> ""):
f.write("curP:" + str(curP) + "\n")
if (bestY < 0):
print "best y < 0, error!"
return False
if (bestY == y[r]):
correct += 1
#debug
else:
if (self.logPath <> ""):
f.write("predict error!")
retY.append(bestY)
if (self.logPath <> ""):
f.close()
return [retY, float(correct) / len(retY)]
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/train.txt")
nbModel = NaiveBayes(config, "naive_bayes")
nbModel.Train(trainx, trainy)
[testx, testy] = matCreater.CreatePredictMatrix("data/test.txt")
[resultY, precision] = nbModel.Test(testx, testy)
"""
print "testX, rows, cols ,vals"
print testX.rows
print testY
print testX.cols
"""
print precision
| Python |
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
from chisquare_filter import ChiSquareFilter
from naive_bayes import NaiveBayes
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__", True)
matCreater = ClassifierMatrix(config, "__matrix__", True)
chiFilter = ChiSquareFilter(config, "__filter__", True)
nbModel = NaiveBayes(config, "naive_bayes", True)
[testx, testy] = matCreater.CreatePredictMatrix("data/test.txt")
[testx, testy] = chiFilter.MatrixFilter(testx, testy)
[resultY, precision] = nbModel.Test(testx, testy)
print precision
| Python |
import math
from segmenter import Segmenter
from matrix import Matrix
from py_mining import PyMining
from configuration import Configuration
class ClassifierMatrix:
def __init__(self, config, nodeName, loadFromFile = False):
self.node = config.GetChild(nodeName)
self.segmenter = Segmenter(config, "__segmenter__")
self.trained = loadFromFile
PyMining.Init(config, "__global__", loadFromFile)
"""
create train matrix:
fill dict in PyMining, record:
1)termToId
2)idToTerm
3)termToDocCount
4)classToDocCount
and save mat-x using csr, save mat-y using list
"""
def CreateTrainMatrix(self, path = ""):
#get input-path
inputPath = path
if (inputPath == ""):
inputPath = self.node.GetChild("train_input").GetValue()
f = open(inputPath, "r")
uid = 0
rows = [0]
cols = []
vals = []
y = []
#fill the matrix's cols and rows
for line in f:
vec = line.split("\t")
line = vec[0]
target = int(vec[1])
y.append(target)
wordList = self.segmenter.Split(line.decode("utf-8"))
#store current row's cols
partCols = []
#create dicts and fill partCol
#calculate term-frequent in this loop
curWordCount = 0
termFres = {}
for word in wordList:
curWordCount += 1
if (not PyMining.termToId.has_key(word)):
PyMining.termToId[word] = uid
PyMining.idToTerm[uid] = word
uid += 1
termId = PyMining.termToId[word]
partCols.append(termId)
if (not termFres.has_key(termId)):
termFres[termId] = 1
else:
termFres[termId] += 1
#fill partCol
partCols = set(partCols)
partCols = list(partCols)
partCols.sort()
#fill cols and vals, fill termToDocCount
for col in partCols:
cols.append(col)
#fill vals with termFrequent
vals.append(termFres[col])
#fill idToDocCount
if (not PyMining.idToDocCount.has_key(col)):
PyMining.idToDocCount[col] = 1
else:
PyMining.idToDocCount[col] += 1
#fill rows
rows.append(rows[len(rows) - 1] + \
len(partCols))
#fill classToDocCount
if (not PyMining.classToDocCount.has_key(target)):
PyMining.classToDocCount[target] = 1
else:
PyMining.classToDocCount[target] += 1
#fill PyMining's idToIdf
for termId in PyMining.idToTerm.keys():
PyMining.idToIdf[termId] = math.log(float(len(rows) - 1) / (PyMining.idToDocCount[termId] + 1))
#NOTE: now, not mul idf to vals, because not all algorithms need tf * idf
#change matrix's vals using tf-idf represent
#for r in range(len(rows) - 1):
# for c in range(rows[r], rows[r + 1]):
# termId = cols[c]
# #idf(i) = log(|D| / |{d (ti included)}| + 1
# vals[c] = vals[c] * PyMining.idToIdf[termId]
#close file
f.close()
#write dicts out
PyMining.Write()
self.trained = True
return [Matrix(rows, cols, vals), y]
def CreatePredictSample(self, src):
print src
if (not self.trained):
print "train Classifier Matrix before predict"
#split sentence
#if src is read from utf-8 file directly,
# should using CreatePredictSample(src.decode("utf-8"))
wordList = self.segmenter.Split(src)
cols = []
vals = []
#fill partCols, and create csr
partCols = []
termFreqs = {}
for word in wordList:
if (PyMining.termToId.has_key(word)):
termId = PyMining.termToId[word]
partCols.append(termId)
if (not termFreqs.has_key(termId)):
termFreqs[termId] = 1
else:
termFreqs[termId] += 1
partCols = set(partCols)
partCols = list(partCols)
partCols.sort()
for col in partCols:
cols.append(col)
vals.append(termFreqs[col])
return [cols, vals]
"""
create predict matrix using previous dict
"""
def CreatePredictMatrix(self, path = ""):
if (not self.trained):
print "train ClassifierMatrix before predict"
return False
#get input path
inputPath = path
if (inputPath == ""):
inputPath = self.curNode.GetChild("test_input")
f = open(inputPath, "r")
rows = [0]
cols = []
vals = []
y = []
for line in f:
vec = line.split("\t")
line = vec[0]
y.append(int(vec[1]))
#split sentence
wordList = self.segmenter.Split(line.decode("utf-8"))
#fill partCols, and create csr
partCols = []
termFreqs = {}
curWordCount = 0
for word in wordList:
curWordCount += 1
if (PyMining.termToId.has_key(word)):
termId = PyMining.termToId[word]
partCols.append(termId)
if (not termFreqs.has_key(termId)):
termFreqs[termId] = 1
else:
termFreqs[termId] += 1
partCols = set(partCols)
partCols = list(partCols)
partCols.sort()
for col in partCols:
cols.append(col)
vals.append(termFreqs[col])
rows.append(rows[len(rows) - 1] + \
len(partCols))
#close file
f.close()
return [Matrix(rows, cols, vals), y]
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainMat, ty] = matCreater.CreateTrainMatrix("data/tuangou_titles3.txt")
[predictMat, py] = matCreater.CreatePredictMatrix("data/tuangou_titles3.txt")
print py
print predictMat.rows
print predictMat.cols
print predictMat.vals
| Python |
if __name__ == "__main__":
"""
train
"""
#init dm platfrom, include segmenter..
config = Configuration.FromFile("test.conf")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("train.txt")
#or using matCreater.CreateTrainMatrix(), train corpus will read from config
chiFilter = ChiSquareFilter(config, "__filter__")
chiFilter.TrainFilter(trainx, trainy)
#or using chiFilter.Create(trainx, trainy) get default setting in config
nbModel = NaiveBayes(config, "naive_bayes")
nbModel.Train(trainx, trainy)
"""
test
"""
# config = Configuration.FromFile("test.conf")
# PyMining.Init(config, "__global__", True), True means load from previos file
# matCreater = ClassifierMatrix(config, "__matrix__", True)
[testx, testy] = matCreater.CreateTestMatrix("test.txt")
#chiFilter = ChiSquareFilter(config, "__filter__", True)
[testx, testy] = chiFilter.MatrixFilter(testx, testy)
#nbModel = NaiveBayes(config, "naive_bayes", True)
[predicty, precision] = nbModel.Predict(testx, testy)
print precision
| Python |
#encoding=utf-8
import math
import pickle
import sys
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
from chisquare_filter import ChiSquareFilter
from twc_naive_bayes import TwcNaiveBayes
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/train.txt")
nbModel = TwcNaiveBayes(config, "twc_naive_bayes")
nbModel.Train(trainx, trainy)
inputStr = "仅售59元!原价108元的花园巴西烤肉自助餐一人次任吃(蛇口店、购物公园店全时段通用),另赠送两张10元现金抵用券!邀请好友返利10元!"
[cols, vals] = matCreater.CreatePredictSample(inputStr.decode("utf-8"))
retY = nbModel.TestSample(cols, vals)
print retY
| Python |
from xml.dom import minidom
class Configuration:
mCurNode = None
def __init__(self, node):
self.mCurNode = node
"""
get first child
"""
def GetChild(self, name):
for node in self.mCurNode.childNodes:
if node.nodeName == name:
return Configuration(node)
return None
def GetChilds(self, name):
nodes = []
for node in self.mCurNode.childNodes:
if node.nodeName == name:
nodes.append(Configuration(node))
return nodes
def GetName(self):
return self.mCurNode.nodeName
def GetValue(self):
return self.mCurNode.firstChild.data
@staticmethod
def FromFile(path):
return Configuration(minidom.parse(path).childNodes[0])
if __name__ == "__main__":
cfg = Configuration.FromFile("sandbox/test.xml")
print cfg.GetName()
print cfg.GetValue()
cfg1 = cfg.GetChild("hello")
print cfg1.GetName()
print cfg1.GetValue()
cfgs = cfg.GetChilds("world")
for c in cfgs:
print c.GetName()
print c.GetValue()
| Python |
#save materials produced during data-mining
class PyMining:
#dict store term -> id
termToId = {}
#dict store id -> term
idToTerm = {}
#dict store term -> how-many-docs-have-term
idToDocCount = {}
#dict store class -> how-many-docs-contained
classToDocCount = {}
#inverse document frequent of termId
idToIdf = {}
#filename of above
nameTermToId = ""
nameIdToTerm = ""
nameIdToDocCount = ""
nameClassToDocCount = ""
nameIdToIdf = ""
#isInit
isInit = False
#curNode
curNode = None
@staticmethod
def Init(config, nodeName, loadFromFile = False):
PyMining.termToId = {}
PyMining.idToTerm = {}
PyMining.idToDocCount = {}
PyMining.classToDocCount = {}
PyMining.idToIdf = {}
PyMining.curNode = config.GetChild(nodeName)
PyMining.nameTermToId = PyMining.curNode.GetChild("term_to_id").GetValue()
PyMining.nameIdToTerm = PyMining.curNode.GetChild("id_to_term").GetValue()
PyMining.nameIdToDocCount = PyMining.curNode.GetChild("id_to_doc_count").GetValue()
PyMining.nameClassToDocCount = PyMining.curNode.GetChild("class_to_doc_count").GetValue()
PyMining.nameIdToIdf = PyMining.curNode.GetChild("id_to_idf").GetValue()
if (loadFromFile):
PyMining.__ReadDict(PyMining.termToId, PyMining.nameTermToId, "str", "int")
PyMining.__ReadDict(PyMining.idToTerm, PyMining.nameIdToTerm, "int", "str")
PyMining.__ReadDict(PyMining.idToDocCount, PyMining.nameIdToDocCount, "int", "int")
PyMining.__ReadDict(PyMining.classToDocCount, PyMining.nameClassToDocCount, "int", "int")
PyMining.__ReadDict(PyMining.idToIdf, PyMining.nameIdToIdf, "int", "float")
PyMining.isInit = True
@staticmethod
def Write():
if (not PyMining.isInit):
print "call init before write()"
return False
PyMining.__WriteDict(PyMining.termToId, PyMining.nameTermToId)
PyMining.__WriteDict(PyMining.idToTerm, PyMining.nameIdToTerm)
PyMining.__WriteDict(PyMining.idToDocCount, PyMining.nameIdToDocCount)
PyMining.__WriteDict(PyMining.classToDocCount, PyMining.nameClassToDocCount)
PyMining.__WriteDict(PyMining.idToIdf, PyMining.nameIdToIdf)
return True
@staticmethod
def __ReadDict(dic, filename, typeK, typeV):
f = open(filename, "r")
for line in f:
line = line.decode("utf-8")
vec = line.split("\t")
k = vec[0]
v = vec[1]
if (typeK == "int"):
k = int(k)
if (typeV == "int"):
v = int(v)
elif (typeV == "float"):
v= float(v)
dic[k] = v
f.close()
@staticmethod
def __WriteDict(dic, filename):
f = open(filename, "w")
for k,v in dic.iteritems():
if isinstance(k, (str, unicode)):
f.write(k.encode("utf-8"))
else:
f.write(str(k))
f.write("\t")
if isinstance(v, (str, unicode)):
f.write(v.encode("utf-8"))
else:
f.write(str(v))
f.write("\n")
f.close()
@staticmethod
def ReadDict(dic, nodeName):
if (not PyMining.isInit):
print "init PyMining before using"
path = PyMining.curNode.GetChild(nodeName).GetValue()
PyMining.__ReadDict(dic, path)
@staticmethod
def WriteDict(dic, nodeName):
if (not PyMining.isInit):
print "init PyMining before using"
path = PyMining.curNode.GetChild(nodeName).GetValue()
PyMining.__WriteDict(dic, path)
| Python |
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
from chisquare_filter import ChiSquareFilter
from naive_bayes import NaiveBayes
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/sogou.train.txt")
chiFilter = ChiSquareFilter(config, "__filter__")
chiFilter.TrainFilter(trainx, trainy)
nbModel = NaiveBayes(config, "naive_bayes")
nbModel.Train(trainx, trainy)
[testx, testy] = matCreater.CreatePredictMatrix("data/sogou.test.txt")
[testx, testy] = chiFilter.MatrixFilter(testx, testy)
[resultY, precision] = nbModel.Test(testx, testy)
print precision
| Python |
import random
import bisect
class Tripple:
def __init__(self, row, col, val):
self.row = row
self.col = col
self.val = val
def Transpose(self):
tmp = self.row
self.row = self.col
self.col = tmp
return self
def TrippleCmp(t1, t2):
if (t1.row < t2.row):
return -1
elif (t1.row > t2.row):
return 1
else:
return t1.col < t2.col
class Matrix:
#init a matrix, using csr, and dimensions
def __init__(self, rows, cols, vals):
self.rows = rows
self.cols = cols
self.vals = vals
self.nRow = len(rows) - 1
maxCol = -1
for col in cols:
if (col > maxCol):
maxCol = col
self.nCol = maxCol + 1
#get element @(x,y), if no element, return 0, if range error, return -1
def Get(self, x, y):
if (x < 0) or (x >= self.nRow):
return 0
index = bisect.bisect_left(self.cols, y, self.rows[x], self.rows[x + 1])
if index < len(self.cols) and index >= 0 and self.cols[index] == y:
return 1
else:
return 0
def Transpose(self, nNewRow):
#make transposed-tripple from csr
triList = []
for r in range(0, len(self.rows) - 1):
for c in range(self.rows[r], self.rows[r + 1]):
t = Tripple(r, self.cols[c], self.vals[c])
t.Transpose()
triList.append(t)
#sort tripple
#for t in triList:
# print t.row, " ", t.col, " ", t.val
#print "====="
#sorted(triList, cmp = TrippleCmp)
triList.sort(cmp = TrippleCmp)
#for t in triList:
# print t.row, " ", t.col, " ", t.val
#make tripple back to csr
newRows = [0]
newCols = []
newVals = []
lastRow = 0
for i in range(0, len(triList)):
#add a new row
if triList[i].row != lastRow:
lastRowsLen = len(newRows)
for j in range(lastRow, triList[i].row - 1):
newRows.append(newRows[lastRowsLen - 1])
newRows.append(i)
lastRow = triList[i].row
#add a new col and val
newCols.append(triList[i].col)
newVals.append(triList[i].val)
for i in range(triList[len(triList) - 1].row, nNewRow - 1):
newRows.append(newRows[len(newRows) - 1])
newRows.append(len(triList))
return Matrix(newRows, newCols, newVals)
@staticmethod
def BaggingFromMatrix(mat, m):
#print "bagging", m
rows = [0]
cols = []
vals = []
maxCol = -1
baggingDict = {}
for i in range(0, m):
ratio = random.random()
index = int(ratio * mat.nRow)
baggingDict[i] = index
#print "add elements to new mat:", mat.rows[index + 1] - mat.rows[index]
rows.append(rows[len(rows) - 1] + (mat.rows[index + 1] - mat.rows[index]))
for j in range(mat.rows[index], mat.rows[index + 1]):
cols.append(mat.cols[j])
if (j > maxCol):
maxCol = j
vals.append(mat.vals[j])
newMat = Matrix(rows, cols, vals)
#print "after bagging:"
#print rows
#print cols
return [newMat.Transpose(mat.nCol), baggingDict]
#if __name__ == "__main__":
#rows = [0, 3, 4, 5, 6]
#cols = [0, 1, 2, 3, 4, 4]
#vals = [1, 1, 1, 1, 1, 1]
#mat = Matrix(rows, cols, vals, 4, 5)
#tMat = mat.Transpose()
#print tMat.rows
#print tMat.cols
#print tMat.vals
#sample = Matrix.BaggingFromMatrix(mat, 2)
#print sample.rows
#print sample.cols
#print sample.vals
#sample = Matrix.BaggingFromMatrix(mat, 2)
#print sample.rows
#print sample.cols
#print sample.vals
| Python |
#coding=utf8=
#mmseg
from configuration import Configuration
class Segmenter:
def __init__(self, config, nodeName):
curNode = config.GetChild(nodeName)
self.mainDict = self.LoadMainDict(curNode.GetChild("main_dict").GetValue())
def Split(self, line):
line = line.lower()
index = 0
wordList = []
while index < len(line):
finded = False
for i in range(1, 5, 1) [::-1]:
if (i + index <= len(line)):
curWord = line[index : i + index]
if (self.mainDict.has_key(curWord) and curWord not in wordList):
wordList.append(curWord)
index += i
finded = True
break
if (finded):
continue
index += 1
return wordList
def LoadMainDict(self, path):
f = open(path, "r")
dicts = {}
for line in f:
line = line.decode("utf-8")
if (line.find("\n") >= 0):
line = line[0:line.find("\n")]
dicts[line] = 1
f.close()
return dicts
if __name__ == "__main__":
cfg = Configuration.FromFile("conf/test.xml")
segmenter = Segmenter(cfg, "segmenter")
f = open("result.txt")
for line in f:
wordList = segmenter.Split(line.decode("utf-8"))
for word in wordList:
print word.encode("mbcs")
| Python |
#encoding=utf8
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
from chisquare_filter import ChiSquareFilter
from naive_bayes import NaiveBayes
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/train.txt")
chiFilter = ChiSquareFilter(config, "__filter__")
chiFilter.TrainFilter(trainx, trainy)
nbModel = NaiveBayes(config, "naive_bayes")
nbModel.Train(trainx, trainy)
inputStr = "仅售28元!原价698元的康迩福韩国美容美体中心的韩国特色美容套餐1份(紫莱花园店、时代奥城店2店通用):韩国特色面部SPA护理1次+韩国特色面部瘦脸加毛孔净化1次+韩国特色水"
[cols, vals] = matCreater.CreatePredictSample(inputStr)
[cols, vals] = chiFilter.SampleFilter(cols, vals)
probTuple = nbModel.TestSample(cols, vals)
print probTuple
| Python |
import math
import pickle
import sys
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
class TwcNaiveBayes:
def __init__(self, config, nodeName, loadFromFile = False):
#store weight from term->class
weights = []
self.trained = loadFromFile
self.curNode = config.GetChild(nodeName)
self.modelPath = self.curNode.GetChild("model_path").GetValue()
self.logPath = self.curNode.GetChild("log_path").GetValue()
if (loadFromFile):
f = open(self.modelPath, "r")
modelStr = pickle.load(f)
[self.weights, self.yy] = pickle.loads(modelStr)
f.close()
def Train(self, x, y):
#check parameters
if (x.nRow <> len(y)):
print "Error!, x.nRow should equals len(y)"
return False
"""
calculate d(i(term),j(doc))
1. d(i,j) = log(d(i,j) + 1)
2. d(i,j) = d(i,j) * idf(i)
3. d(i,j) = d(i,j) / sqrt(sigma(d(k,j)^2))
k belong current sample
"""
for r in range(len(x.rows) - 1):
sampleSum = 0.0
for c in range(x.rows[r], x.rows[r + 1]):
termId = x.cols[c]
x.vals[c] = math.log(x.vals[c] + 1)
x.vals[c] = x.vals[c] * PyMining.idToIdf[termId]
sampleSum += x.vals[c] * x.vals[c]
#normalize it
sampleSum = math.sqrt(sampleSum)
for c in range(x.rows[r], x.rows[r + 1]):
x.vals[c] = float(x.vals[c]) / sampleSum
"""
calculate weights
1. theta(c, i) = sigma d(i,j) + alpha(i)
j(y(j) not c
________________________________
sigma sigma d(k, j) + sum(alpha)
j(y(j) != c) k
(alpha(i) = 1)
(sum(alpha(i)) = len(y)
2. w(c, i) = log(theta(c,i))
3. w(c, i) = w(c, i) / sigma(w(c, i))
i
"""
self.yy = set(y)
self.yy = list(self.yy)
self.yy.sort()
#init weights:
self.weights = [[0 for j in range(x.nCol)] for i in range(len(self.yy))]
weightsSum = [0 for i in range(len(self.yy))]
#calculate theta(c,i) = sigma d(i,j) + 1
# y(j)<>c
for classId in range(len(self.yy)):
for r in range(len(x.rows) - 1):
for c in range(x.rows[r], x.rows[r + 1]):
if (y[r] <> self.yy[classId]):
termId = x.cols[c]
self.weights[classId][termId] += x.vals[c]
weightsSum[classId] += x.vals[c]
#normalize weights
classCount = len(self.yy)
for classId in range(len(self.yy)):
curClassSum = 0
for termId in range(x.nCol):
self.weights[classId][termId] += 1
self.weights[classId][termId] /= float(weightsSum[classId]) + classCount
self.weights[classId][termId] = math.log(self.weights[classId][termId])
curClassSum += math.fabs(self.weights[classId][termId])
for termId in range(x.nCol):
self.weights[classId][termId] /= curClassSum
self.trained = True
#dump model
f = open(self.modelPath, "w")
modelStr = pickle.dumps([self.weights, self.yy], 1)
pickle.dump(modelStr, f)
f.close()
return True
"""
l(t) = argmin sigma t(i) * w(c,i)
c i
(t(i) is frequency of termI in this sample)
"""
def __GetBestTarget(self, cols, vals):
if (len(cols) <> len(vals)):
print "Error!, len of cols should == len of vals"
return -1
#get min likelihood
#minL = sys.maxint
retList = []
maxL = -1
bestClass = 0
sumProb = 0
for classIndex in range(len(self.yy)):
curL = 0
for c in range(len(cols)):
termId = cols[c]
termFreq = vals[c]
curL += termFreq * self.weights[classIndex][termId]
retList.append([self.yy[classIndex], curL])
return tuple(retList)
"""
get result of a single-line-sample
"""
def TestSample(self, cols, vals):
#check parameter
if (not self.trained):
print "Error!, not trained!"
return ()
ret = self.__GetBestTarget(cols, vals)
return ret
"""
get result of a multi-line-sample
"""
def TestMatrix(self, x, y = None):
retY = []
correct = 0
for r in range(x.nRow):
ret = self.__GetBestTarget(x.cols[x.rows[r]:x.rows[r + 1]], x.vals[x.rows[r]:x.rows[r + 1]])
retY.append(ret)
if (y <> None):
bestL = sys.maxint
bestTarget = 0
for tup in ret:
if (tup[1] < bestL):
bestL = tup[1]
bestTarget = tup[0]
if (bestTarget == y[r]):
correct += 1
if (y <> None):
print "precision : ", float(correct) / x.nRow
return retY
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/train.txt")
nbModel = TwcNaiveBayes(config, "twc_naive_bayes")
nbModel.Train(trainx, trainy)
[testx, testy] = matCreater.CreatePredictMatrix("data/test.txt")
retY = nbModel.TestMatrix(testx, testy)
| Python |
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
class ChiSquareFilter:
def __init__(self, config, nodeName, loadFromFile = False):
self.curNode = config.GetChild(nodeName)
self.rate = float(self.curNode.GetChild("rate").GetValue())
self.method = self.curNode.GetChild("method").GetValue()
self.logPath = self.curNode.GetChild("log_path").GetValue()
self.modelPath = self.curNode.GetChild("model_path").GetValue()
self.blackList = {}
self.trained = loadFromFile
if (loadFromFile):
f = open(self.modelPath, "r")
for line in f:
self.blackList[int(line)] = 1
def SampleFilter(self, cols, vals):
if (not self.trained):
print "train filter before test"
return False
#check parameter
if (len(cols) <> len(vals)):
print "length of cols should equals length of vals"
return False
#filter sample
newCols = []
newVals = []
for c in range(0, len(cols)):
if not self.blackList.has_key(cols[c]):
newCols.append(cols[c])
newVals.append(vals[c])
return [cols, vals]
"""
filter given x,y by blackList
x's row should == y's row
@return newx, newy filtered
"""
def MatrixFilter(self, x, y):
if (not self.trained):
print "train filter before test"
return False
#check parameter
if (x.nRow <> len(y)):
print "ERROR!x.nRow should == len(y)"
return False
#stores new rows, cols, and vals
newRows = [0]
newCols = []
newVals = []
for r in range(x.nRow):
curRowLen = 0
#debug
#print "===new doc==="
for c in range(x.rows[r], x.rows[r + 1]):
if not self.blackList.has_key(x.cols[c]):
newCols.append(x.cols[c])
newVals.append(x.vals[c])
curRowLen += 1
#debug
#print PyMining.idToTerm[x.cols[c]].encode("utf-8")
newRows.append(newRows[len(newRows) - 1] + curRowLen)
return [Matrix(newRows, newCols, newVals), y]
"""
create a blackList by given x,y
@rate is a percentage of selected feature
using next formulation:
X^2(t, c) = N * (AD - CB)^2
____________________
(A+C)(B+D)(A+B)(C+D)
A,B,C,D is doc-count
A: belong to c, include t
B: Not belong to c, include t
C: belong to c, Not include t
D: Not belong to c, Not include t
B = t's doc-count - A
C = c's doc-count - A
D = N - A - B - C
and score of t can be calculated by next 2 formulations:
X^2(t) = sigma p(ci)X^2(t,ci) (avg)
i
X^2(t) = max { X^2(t,c) } (max)
@return true if succeed
"""
def TrainFilter(self, x, y):
#check parameter
if not ((self.method == "avg") or (self.method == "max")):
print "ERROR!method should be avg or max"
return False
if (x.nRow <> len(y)):
print "ERROR!x.nRow should == len(y)"
return False
#using y get set of target
yy = set(y)
yy = list(yy)
yy.sort()
#create a table stores X^2(t, c)
#create a table stores A(belong to c, and include t
chiTable = [[0 for i in range(x.nCol)] for j in range(yy[len(yy) - 1] + 1)]
aTable = [[0 for i in range(x.nCol)] for j in range(yy[len(yy) - 1] + 1)]
#calculate a-table
for row in range(x.nRow):
for col in range(x.rows[row], x.rows[row + 1]):
aTable[y[row]][x.cols[col]] += 1
#calculate chi-table
n = x.nRow
for t in range(x.nCol):
for cc in range(len(yy)):
#get a
a = aTable[yy[cc]][t]
#get b
b = PyMining.idToDocCount[t] - a
#get c
c = PyMining.classToDocCount[yy[cc]] - a
#get d
d = n - a - b -c
#get X^2(t, c)
numberator = float(n) * (a*d - c*b) * (a*d - c*b)
denominator = float(a+c) * (b+d) * (a+b) * (c+d)
chiTable[yy[cc]][t] = numberator / denominator
#calculate chi-score of each t
#chiScore is [score, t's id] ...(n)
chiScore = [[0 for i in range(2)] for j in range(x.nCol)]
if (self.method == "avg"):
#calculate prior prob of each c
priorC = [0 for i in range(yy[len(yy) - 1] + 1)]
for i in range(len(yy)):
priorC[yy[i]] = float(PyMining.classToDocCount[yy[i]]) / n
#calculate score of each t
for t in range(x.nCol):
chiScore[t][1] = t
for c in range(len(yy)):
chiScore[t][0] += priorC[yy[c]] * chiTable[yy[c]][t]
else:
#calculate score of each t
for t in range(x.nCol):
chiScore[t][1] = t
for c in range(len(yy)):
if (chiScore[t][0] < chiTable[yy[c]][t]):
chiScore[t][0] = chiTable[yy[c]][t]
#sort for chi-score, and make blackList
chiScore = sorted(chiScore, key = lambda chiType:chiType[0], reverse = True)
#add un-selected feature-id to blackList
for i in range(int(self.rate * len(chiScore)), len(chiScore)):
self.blackList[chiScore[i][1]] = 1
#output model information
if (self.modelPath <> ""):
f = open(self.modelPath, "w")
for k in self.blackList:
f.write(str(k) + "\n")
f.close()
#output chiSquare info
if (self.logPath <> ""):
f = open(self.logPath, "w")
f.write("chiSquare info:\n")
f.write("=======selected========\n")
for i in range(len(chiScore)):
if (i == int(self.rate * len(chiScore))):
f.write("========unselected=======\n")
term = PyMining.idToTerm[chiScore[i][1]]
score = chiScore[i][0]
f.write(term.encode("utf-8") + " " + str(score) + "\n")
f.close()
self.trained = True
return True
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/tuangou_titles3.txt")
chiFilter = ChiSquareFilter(config, "__filter__")
chiFilter.TrainFilter(trainx, trainy)
| Python |
import math
import pickle
import sys
from matrix import Matrix
from classifier_matrix import ClassifierMatrix
from segmenter import Segmenter
from py_mining import PyMining
from configuration import Configuration
from chisquare_filter import ChiSquareFilter
from twc_naive_bayes import TwcNaiveBayes
if __name__ == "__main__":
config = Configuration.FromFile("conf/test.xml")
PyMining.Init(config, "__global__")
matCreater = ClassifierMatrix(config, "__matrix__")
[trainx, trainy] = matCreater.CreateTrainMatrix("data/train.txt")
chiFilter = ChiSquareFilter(config, "__filter__")
chiFilter.TrainFilter(trainx, trainy)
nbModel = TwcNaiveBayes(config, "twc_naive_bayes")
nbModel.Train(trainx, trainy)
[testx, testy] = matCreater.CreatePredictMatrix("data/test.txt")
[testx, testy] = chiFilter.MatrixFilter(testx, testy)
retY = nbModel.TestMatrix(testx, testy)
| Python |
#coding:utf-8
import sys
a=u"""3 工程师 Done.
1 php Done.
5 php 工程师 Done.
2 设计师 Done.
6 视觉设计 Done.
7 产品经理 Done.
9 web Done.
10 编辑 Done.
11 实习生 Done.
12 产品 Done.
13 交互设计 Done.
8 产品设计 Done.
18 java Done.
19 UI Done.
22 销售 Done.
25 医药代表 Done.
24 java php Done.
29 gongzhuo Done.
17 c++ Done.
30 css Done.
39 程序架构师 Done.
41 SUNCR2008 Done.
38 百图 Done.
43 张彦路 Done.
40 百图互动传媒,重金诚聘PHP/.NET程序架构师多名。百图,意味着凭借所知所能所作所为,在新的领域,以新的方式,为您诠释固有的产品。 所知、所能、所作、所为,无所不在,无所不能――百图(PATO) Done.
42 策划 Done.
44 百度 Done.
45 北京 运营 Done.
47 脱发 Done.
49 ued Done.
50 广州 生物 Done.
48 我是一名软、硬件网络全能工程师。。涉及领域:asp.net Java php等语言技术 Done.
52 应届生 Done.
53 陈莹 Done.
54 elya Done.
36 助理 Done.
37 兼职 Done.
59 长春 Done.
56 视频编辑 Done.
58 校园招聘 Done.
46 招聘经理 Done.
57 视频 Done.
51 生物 Done.
60 移动 Done.
55 悲剧 Done.
65 呼叫中心运营经理 Done.
64 呼叫中心 Done.
66 运营经理 Done.
63 产品专员 Done.
71 管家婆 Done.
69 PHP工程师 Done.
72 数据库 Done.
73 瀹炰範鐢 Done.
70 用友 Done.
61 深圳 Done.
74 广告传播 Done.
80 策划 成都 Done.
78 出国劳务 Done.
81 成都 Done.
77 出国 Done.
76 linux 运维 Done.
75 linux Done.
79 运维 Done.
83 央视 Done.
82 JS Done.
87 百度无线 Done.
86 前端 Done.
62 产品助理 Done.
90 shenzhen Done.
91 groovy Done.
93 金山 PHP Done.
92 金山 Done.
84 cgi Done.
89 阿里巴巴 Done.
97 前端工程师 厦门 Done.
94 支付宝 Done.
98 UI设计 上海 Done.
85 动漫 Done.
88 长乐 Done.
95 开发经理 Done.
99 网页设计 Done.
100 网页设计 兼职 Done.
96 经理 Done.
101 pmcaff Done.
105 UI,视觉设计 Done.
103 gps Done.
106 UI设计 Done.
107 UI设计 北京 Done.
104 qt Done.
108 淘宝 Done.
109 excel Done.
110 工程师 C# Done.
112 ruby Done.
111 产品 招聘 Done.
113 UI设计师 Done.
114 UE Done.
115 产品经理助理 Done.
120 博彦科技 Done.
119 搜狐 Done.
121 c# Done.
123 寻ui+制作高手兼职 Done.
117 汽车 模型 Done.
116 汽车 Done.
118 搜狗 Done.
122 工业设计 Done.
126 缂栬緫 Done.
125 深圳+ui Done.
124 深圳 ui Done.
127 机器人 招聘 Done.
129 机器人 Done.
130 盛大创新院 Done.
134 17huryfnf hfgfhdgt Done.
128 招聘 机器人 Done.
133 糖衣炮弹 Done.
135 17huryfnf hfgfhdgt$ Done.
131 机械 Done.
139 what? Done.
140 jj Done.
141 瀹炰範鐢 Done.
142 交互设计UI Done.
143 city:深圳 cate:产品经理 Done.
145 fdsa Done.
146 包子 Done.
144 实习生 北京 Done.
136 前端开发 Done.
102 gis Done.
137 2 Done.
138 xxx Done.
147 首席架构师 Done.
151 解放碑 Done.
153 交互设计+上海 Done.
149 广州 销售 Done.
148 广州 产品经理 Done.
152 广州 Done.
150 内容编辑 Done.
155 视觉设计 杭州 Done.
154 python Done.
161 应聘JS Done.
162 瀹炰範鐢 Done.
160 数据仓库 java Done.
159 数据仓库 Done.
157 clothhr@163.com Done.
158 深圳 java Done.
164 佳木斯 Done.
169 erp Done.
168 seo Done.
156 产品+招聘 Done.
167 采购 Done.
165 策划 上海 Done.
166 物流 Done.
170 div+css Done.
171 你好 Done.
173 天津 seo Done.
172 浜や簰璁捐? Done.
175 天津 网络推广 Done.
174 天津 Done.
178 兼职 客服 Done.
177 东莞 招聘 Done.
176 市场 Done.
179 律师 Done.
181 设计 Done.
183 ruby on rails Done.
182 龙元建设 Done.
187 科技记者 Done.
186 科技编辑 Done.
163 职业欠钱 Done.
180 中国 Done.
184 翻译 Done.
185 产品经理 上海 Done.
190 网站策划 上海 Done.
193 BA Done.
195 business Done.
194 business ana Done.
196 analyst Done.
191 腾讯 Done.
198 建筑软件 Done.
192 技术总监 Done.
188 科技 Done.
189 产品策划 上海 Done.
197 分析 Done.
204 IT Done.
203 伟大公关 Done.
200 应届生 运维 Done.
201 中华英才网 Done.
208 英语 Done.
202 建筑 Done.
207 公关 Done.
209 系统分析 Done.
199 sap Done.
205 伟达公关 Done.
206 分析师 Done.
215 蓝驰 Done.
216 .net Done.
210 产品经理 深圳 Done.
217 技术经理 Done.
211 seo 福州 Done.
219 找工作就来这里吧。 Done.
214 手机 Done.
218 游戏策划 Done.
221 深圳外贸业务员 Done.
212 青岛 Done.
224 数字出版 Done.
225 出版 Done.
226 BD Done.
227 长沙 Done.
228 金融 Done.
230 微伯乐 Done.
222 .net 工程师 Done.
213 JavaScript Done.
220 外贸业务员 Done.
223 网络工程师 Done.
232 宁波 Done.
229 视觉设计 宁波 Done.
236 招聘 Done.
234 优客 Done.
237 魅族 Done.
235 生物信息 Done.
231 运维工程师 Done.
239 UI经理 Done.
240 UI总监 Done.
242 社区运营 Done.
241 室内 Done.
233 运维工程师 sina Done.
244 交互 Done.
245 卡乐购 Done.
238 iphone Done.
243 社区 Done.
250 上海团购网 Done.
246 盛大在线 Done.
249 本多 Done.
251 音乐 Done.
256 邮局 Done.
252 网站分析 Done.
247 Flash Done.
254 分析 上海 Done.
248 手办 Done.
253 医疗 Done.
257 企业邮箱 Done.
259 sa Done.
262 售前 Done.
258 会计 Done.
263 邮件 Done.
261 软件售前 Done.
267 产品经理 广州 Done.
260 系统管理员 Done.
265 环保 Done.
255 财务 Done.
269 flash lite Done.
264 广州 java Done.
272 校园 产品经理 Done.
266 环境工程 Done.
274 上海 Done.
270 北京 Done.
276 ccna Done.
278 威海 Done.
277 济南 Done.
279 HCI Done.
268 网站美工 Done.
280 django Done.
281 租房 Done.
282 出租 Done.
284 房源 Done.
283 as Done.
285 广州 市场 Done.
275 产品总监 Done.
287 php 深圳 Done.
289 ued 上海 Done.
288 php 上海 Done.
291 新浪微博招聘PHP高级开发工程师!!! Done.
273 產品 Done.
290 ued 北京 Done.
292 ror Done.
271 微博 Done.
297 婚礼策划 Done.
298 婚礼 Done.
294 新鲁尼 Done.
296 心理学 Done.
293 电子商务 Done.
299 婚策 Done.
295 心理 Done.
302 新浪薪水 Done.
303 软件测试 Done.
305 杭州 Done.
307 苏州 Done.
300 酒店销售 Done.
304 上海 java Done.
301 新浪产品薪水 Done.
308 国泰君安 Done.
306 网络工程 Done.
286 php 北京 Done.
313 外贸 Done.
312 人力资源 Done.
311 薪资主管 Done.
310 薪酬主管 Done.
315 沈阳 Done.
314 百度 php Done.
316 fsf Done.
320 city:北京;cate:网站编辑 Done.
318 兰州新东方 Done.
319 city:北京 cate:网站编辑 Done.
317 兰州新东方招聘 Done.
309 诚聘t.163.com的PM Done.
325 callcenter Done.
322 产品经理 招聘 Done.
323 北京 网站编辑 Done.
321 为获新知闯天下 Done.
324 df Done.
327 20k Done.
326 15k Done.
328 南京实习生 Done.
333 北京 php Done.
334 产品经理 助理 Done.
337 配置管理 Done.
335 东莞 Done.
336 搜索研发 Done.
331 产品经理 北京 Done.
339 版本管理 Done.
341 12580 Done.
340 应届 Done.
338 管理 Done.
342 平面设计 Done.
330 瀹炰範鐢 Done.
343 杭州 前端 Done.
345 诚聘:韩语技术支持工程师-上海/北京/天津/大连 Done.
347 sohu Done.
348 网易 Done.
349 掰断 Done.
346 新浪 Done.
344 总监 Done.
350 测试 Done.
332 记者 Done.
354 上海 产品 Done.
352 淘米 Done.
353 实习 Done.
357 新浪微博API2 Done.
358 招聘工程师 Done.
359 招聘 工程师 Done.
355 活动 策划 Done.
356 数据挖掘 Done.
360 建筑建模 Done.
351 郑州 Done.
363 mysql Done.
365 前台 Done.
361 缴费 Done.
367 abc Done.
366 小姐 Done.
368 外包 网站 Done.
364 项目 网站 Done.
369 招标 网站 Done.
362 非 Done.
373 event manager Done.
372 event Done.
370 招标 Done.
376 峰会 Done.
371 外包 Done.
379 软件开发 Done.
377 插画助理 Done.
374 会议 Done.
380 物流 上海 Done.
375 论坛 Done.
384 常州 Done.
383 大连 Done.
385 e-learning Done.
381 福州 php Done.
382 交互 北京 Done.
386 学习 Done.
329 南京 Done.
378 数据 挖掘 Done.
391 窝窝团 Done.
390 上海 前端 Done.
388 产品运营 Done.
392 产品规划 Done.
393 广东 Done.
387 木匠 Done.
395 青岛 产品经理 Done.
396 厦门 Done.
400 数码印花 Done.
401 hr Done.
394 ajax Done.
399 老罗 Done.
397 教育 Done.
398 新东方 Done.
402 网站市场推广 Done.
404 android Done.
405 一起手游 Done.
389 交互设计师 Done.
407 马云 Done.
408 c Done.
409 基金 Done.
412 服装设计 Done.
406 李刚 Done.
410 投资 Done.
403 市场推广 Done.
411 股票 Done.
419 city:深圳 cate:程序员 Done.
418 hiall Done.
420 city:北京 cate:程序员 Done.
422 city:北京 cate:产品经理 Done.
421 city:北京 cate:c 程序员 Done.
414 体育经纪 Done.
423 实习生 阿里 Done.
417 重庆 Done.
425 王菲 Done.
426 斯蒂芬 Done.
427 愚公移山 Done.
428 工业控制 plc Done.
429 plc Done.
431 外贸业务iyuan Done.
430 西门子 Done.
424 实习生 淘宝 Done.
413 体育 Done.
434 微博运营实习生 Done.
435 二手房 Done.
436 php,北京 Done.
432 广告产品经理 Done.
433 新浪微博运营实习生 Done.
415 记者 媒体 Done.
416 媒体 Done.
437 php+北京 Done.
440 傻逼 Done.
444 寒假 实习 Done.
445 寒假 Done.
442 惠州 Done.
443 游戏 Done.
439 CCNP Done.
438 王微 Done.
450 啊狸 Done.
447 北京 实习 Done.
448 武汉 新闻 Done.
452 phpppp Done.
451 marcom Done.
446 假期 Done.
441 惠诈 Done.
449 新闻 Done.
456 熙康 Done.
458 嵌入式 Done.
455 杭州 UI Done.
457 东软 Done.
454 杭州 GUI Done.
461 主编 Done.
463 南京 UI Done.
464 法律 Done.
465 f Done.
466 招聘 电视记者 Done.
462 内容 Done.
467 招聘 mac Done.
471 创新工场 Done.
470 法语 Done.
460 新媒体 Done.
459 后台开发 Done.
469 php 杭州 Done.
476 兼职 杭州 Done.
474 达彼思 Done.
472 美工 Done.
473 4A Done.
475 google Done.
479 格力 Done.
478 微简历 Done.
477 #求职# Done.
481 北京 媒体 Done.
483 北京 无线 Done.
484 北京 杂志 Done.
482 北京 新媒体 Done.
485 化工 Done.
486 培训生 Done.
487 管理培训生 Done.
488 销售经理 Done.
468 招聘 苹果 Done.
480 总监 北京 Done.
489 Mac Done.
492 海南 Done.
494 博鳌 Done.
493 海口 Done.
495 大师 Done.
496 老沉 Done.
491 卫生 Done.
453 网络安全 Done.
490 预防医学 Done.
499 web前端 杭州 Done.
497 宽连十方 Done.
502 数据产品经理 Done.
505 工作营 Done.
498 web前端 Done.
503 lucene Done.
507 求职 交互设计 Done.
506 应聘 交互设计 Done.
504 搜索 Done.
500 前端 杭州 Done.
512 环评 Done.
509 oracle Done.
508 上海 交互设计师 Done.
510 营销 Done.
501 网络营销 Done.
515 音樂 Done.
517 凡客诚品 Done.
518 秘书 Done.
514 射频 Done.
519 图书 Done.
511 杂志 Done.
516 音 Done.
524 上海 媒体 Done.
522 社会化媒体营销 Done.
523 媒体 ps 影视制作 Done.
525 无锡 Done.
526 财务总监 Done.
527 人力资源经理 Done.
521 法务 Done.
513 交通 Done.
520 猎头 Done.
532 无线产品经理 Done.
533 移动产品经理 Done.
534 客户端 产品经理 Done.
535 长沙 招聘 Done.
536 手机 产品经理 Done.
537 安全 Done.
539 PROE Done.
540 Pro/E Done.
538 机械设计 Done.
530 KA Done.
543 平面设计 无锡 Done.
541 乳 Done.
542 运营 Done.
531 美容编辑 Done.
544 绍兴 Done.
545 cate:java工程师 city:北京 Done.
549 南通 Done.
550 实习生 南京 Done.
547 delphi Done.
548 自动化 Done.
553 绵阳 Done.
551 证券 Done.
546 数值 Done.
552 推广 Done.
554 保险 Done.
557 asdfsf Done.
560 深圳 网站 Done.
558 搜索引擎 Done.
556 美丽 Done.
555 园林 Done.
564 广州 市场经理 Done.
563 广州市场经理 Done.
561 深圳 网站编辑 Done.
559 网站 Done.
565 电商运营 Done.
566 韩国语 Done.
567 韩语 Done.
569 酒店 Done.
571 IT业 Done.
570 本地化 Done.
568 校园 Done.
572 元器件 Done.
575 smm Done.
574 软件 Done.
573 芯片 Done.
562 市场经理 Done.
528 技术支持 Done.
529 模特 Done.
577 长沙求职 Done.
581 微博求职 Done.
580 求职 Done.
582 日本 Done.
576 sns Done.
583 测试工程师 Done.
578 交互设计师 北京 Done.
579 社会化 Done.
587 剪辑师 Done.
586 99 Done.
588 北京 java Done.
585 sem Done.
592 实习生 插画 Done.
590 上海 助理 Done.
591 电子 Done.
595 手机游戏 广州 Done.
584 AE Done.
594 画师 Done.
597 人设 Done.
596 图书馆 Done.
599 人物设计师 Done.
598 人 设 Done.
603 maya Done.
589 开放 Done.
593 插画 Done.
605 NLP Done.
606 sueveannal@theknot.com Done.
604 动画 Done.
607 商务智能 Done.
609 上海 大专 Done.
610 记者站 Done.
611 记者 广州 Done.
608 BI Done.
613 西安 机械 Done.
614 互动营销客户经理 Done.
616 互动媒介经理 Done.
600 实习生 原画 插画 人物设计 Done.
617 互动客户经理 Done.
612 西安 Done.
618 互动 客户经理 Done.
621 房地产 Done.
615 互动营销媒介经理 Done.
619 业务员 Done.
623 asp.net Done.
624 实习生 媒体 Done.
622 房地产 广州 Done.
625 实习生 新闻 Done.
601 3D Done.
627 实习生 报社 Done.
628 实习生 报纸 Done.
629 asp.net 深圳 Done.
630 旅游策划 Done.
631 旅游 Done.
633 腾讯nlp Done.
634 asd Done.
632 美女 Done.
626 实习生 网站 Done.
620 163 Done.
636 公务员 Done.
637 模特儿 Done.
639 徐中一 Done.
638 掌上百度 Done.
641 招聘 四川 Done.
640 壁虎 Done.
644 空姐 Done.
642 交互实习生 Done.
643 苍井空 Done.
645 快乐的阅读 Done.
647 大连 地产 Done.
635 教师 Done.
650 test Done.
646 快乐阅读 Done.
648 信息安全 Done.
649 自然语言处理 Done.
652 广州 电子商务 Done.
654 内容处理 Done.
656 招聘 北京大麦网 前端工程师 Done.
655 内容分析 Done.
653 世界地图 Done.
658 产品经理 财经 Done.
659 产品经理 证券 Done.
651 网页设计师 Done.
660 产品经理 股票 Done.
662 实习生 土木工程 Done.
663 实习生 土木 Done.
657 策划 无线 Done.
665 实习生建筑 Done.
668 哈尔滨 实习 Done.
664 实习生 建筑 Done.
666 土木工程 Done.
670 福州 Done.
667 PHP 广州 Done.
669 新闻 实习 Done.
673 VC 投资 Done.
675 德语 Done.
672 VC Done.
661 杭州招聘 Done.
671 数据 Done.
676 红枣 Done.
678 交互设计 北京 Done.
679 网易招聘 Done.
681 腾讯扎好哦品 Done.
683 新浪招聘 Done.
682 腾讯招聘 Done.
684 百度招聘 Done.
674 笔译 Done.
680 招产品 Done.
685 招聘主管 Done.
677 榆林 Done.
687 实施经理 Done.
690 cate:交互设计师,city:上海 Done.
686 eam Done.
689 cate:交互设计师 city:上海 Done.
693 泰语 Done.
692 客户经理 Done.
691 高级产品经理 Done.
694 实习生 汽车 Done.
688 项目经理 Done.
698 福建 酒 Done.
695 泰国 Done.
697 松江 Done.
701 dba Done.
699 福建 营销经理 Done.
700 福建 销售经理 Done.
703 移动通信 Done.
702 页面制作 Done.
704 投资 证券 Done.
708 风水师 Done.
707 武汉 Done.
709 太原 Done.
696 人事 Done.
706 投资 分析师 Done.
712 广告公司实习 Done.
713 实习 广州 Done.
714 肉丝 Done.
711 广告公司 Done.
716 安利 Done.
717 宝洁 Done.
715 医药 Done.
719 药品注册 Done.
718 交互设计 实习 Done.
721 数据库管理员 Done.
722 网络 Done.
705 投资 经理 Done.
720 注册 Done.
724 cisco Done.
723 思科 Done.
728 芜湖 Done.
729 自动化测试 Done.
727 andriod Done.
725 广告 Done.
726 模具 Done.
602 全部招聘 php 编辑 产品经理 交互设计 视觉设计 实习生 产品 产品设计 java Done.
732 山西 实习生 Done.
730 QTP Done.
731 自动测试 Done.
737 二书 Done.
738 豆豆猫 Done.
736 美容师 Done.
739 statusnet Done.
740 景观设计 Done.
741 园林设计 Done.
742 平面媒体 Done.
733 广州地区 Done.
710 公司名称:北京数字天堂信息科技有限责任公司 职位名称:UI设计师 人数:2人 薪资:面谈 职位要求:偏手机界面UI设计,要求会网页设计。 Done.
735 敢死队 Done.
744 内容总监 Done.
748 纳米 Done.
749 oracl Done.
750 广州 实习 linux Done.
747 上海 金融 Done.
746 前端 上海 Done.
734 会计 泉州 Done.
753 rtsp Done.
752 live555 Done.
751 广州 实习 Done.
754 视频流 Done.
755 流媒体 Done.
756 特殊工作 Done.
758 倒萨 Done.
760 ‘ Done.
757 工作 Done.
745 摄影 Done.
743 媒体 网站 Done.
776 大同 Done.
778 人人呢 Done.
779 人人 Done.
774 交互设计 北京 三元桥 Done.
781 应届生 深圳 Done.
775 交互设计 太阳宫 Done.
780 应届生 广州 Done.
782 南宁 Done.
783 媒介经理 Done.
786 a Done.
787 b Done.
785 游戏 媒介经理 Done.
784 游戏媒介经理 Done.
773 mtk Done.
788 HR伴侣 Done.
794 我们都是好孩子 Done.
795 设计师 深圳 Done.
790 %你好% Done.
797 云阳 Done.
777 jsp Done.
798 万州 Done.
800 上海 策划 Done.
799 沙坪坝 Done.
802 主编经验 Done.
801 宽途 Done.
803 大刊 Done.
805 时尚 Done.
806 著名互联网公司、nadaq上市,LAMP工程师招聘,工作地点:北京 Done.
796 产品总监 北京 Done.
804 时尚杂志 Done.
807 研发工程师 Done.
810 士大夫 Done.
812 nadaq Done.
809 豆腐干 Done.
816 机器视觉 Done.
811 发 Done.
815 计算机视觉 Done.
814 java工程师 Done.
808 热 Done.
813 服务员 Done.
817 模式识别 Done.
824 用户体验 北京 朝阳 Done.
823 IBM Done.
822 会展 Done.
825 用户体验 朝阳 Done.
827 英语 南京 Done.
820 创业 Done.
828 lbs Done.
829 峰会策划 Done.
831 会议策划 Done.
832 会议 上海 Done.
826 英语流利 Done.
819 年薪 Done.
821 银行 Done.
830 活动策划 Done.
836 编辑 成都 Done.
834 photoshop Done.
840 应届硕士 Done.
835 导游 Done.
839 成都编辑 Done.
838 成都 编辑 Done.
837 人事主管 Done.
841 应届硕士招聘 Done.
844 深圳文案 Done.
846 程序员 Done.
845 大姚 Done.
843 文案 Done.
847 java 上海 Done.
849 biostatistician Done.
851 sas Done.
850 药物经济 Done.
848 ue 80 Done.
842 旅游记者 Done.
854 android 百度 Done.
855 广州 记者 Done.
856 android 实习生 Done.
833 产品 实习生 Done.
859 翻译 长沙 Done.
858 审计 Done.
860 交互 设计师 Done.
862 销售 空调 Done.
863 产品 经理 Done.
853 微博推广专员5名,专职月薪2000元 提成,兼职月薪1000元 提成。要求:注册微博客1年以上,关注100人以上,粉丝数1000以上,经常上网,泡论坛、写博客;有过公关公司、媒体公司、营销公司工作经验优先。邮件:uvw002@163.com Done.
789 全部招聘 php 编辑 产品经理 交互设计 视觉设计 实习生 产品 产品设计 Done.
852 统计 Done.
867 rails Done.
868 编辑 西安 Done.
865 自然语言 处理 Done.
866 cate : 营销 经理 city 北京 Done.
871 西安 行政 Done.
870 西安行政 Done.
872 西安 网站 Done.
873 咨询顾问 Done.
874 交互 设计 Done.
869 网站 业务 Done.
875 新东方 招聘 产品 经理 Done.
876 新东方 产品 经理 Done.
880 生物 医学 工程师 Done.
877 臧知昶 Done.
882 leed Done.
879 招聘信息 Done.
881 搜索 研发 工程师 Done.
878 iOS 系统 招聘 导航 软件开发 人员 Done.
857 会计师 Done.
885 架构师 Done.
886 娱乐 Done.
861 请 各位 帮忙 转播 推荐 呀 Done.
891 广州 助理 Done.
890 广州助理 Done.
888 文员 广州 Done.
889 广州 行政 Done.
892 怀旧 Done.
887 文员 Done.
893 飞机 Done.
894 营销 经理 Done.
864 界面 设计师 一名 请 各位 帮忙 转播 推荐 呀 Done.
902 supporting Done.
903 法律 实习生 Done.
905 web 前端 Done.
904 招聘:b2b销售经理,有电子商务销售管理经验优先,联系qq:408378857 e-mai:tianxf@gasgoo.com Done.
906 经济学 Done.
907 硕士 Done.
901 英语助教 Done.
900 新浪网 php 工程师 系统 架构 师 Done.
909 郑州 迪士尼 儿童 15938737424 地点 富田 太阳城 一站 站 广场 Done.
899 php 程序员 Done.
911 工业 工程师 Done.
908 用户体验 Done.
912 商务 Done.
914 聯網 Done.
913 彩铃运营 Done.
919 英语 广州 Done.
916 客户端 产品 经理 Done.
920 英语 八级 Done.
918 网站推广 Done.
915 无线 手机 产品 Done.
917 手机 产品 经理 Done.
921 izenesoft Done.
926 实习生 会计 Done.
922 电气 Done.
924 核工程 Done.
923 地球化学 Done.
925 交互设计 上海 Done.
928 外贸 厦门 Done.
927 会计 上海 Done.
929 互联网 分析师 Done.
930 商业 分析师 Done.
932 系统维护 Done.
934 @ Done.
883 产品 经理 一名 市场推广 SEO 方向 文案 策划 前端 设计师 时尚 健康 类 的 电子 商场 项目 招聘 Done.
931 网页 设计师 Done.
933 937 bambook Done.
转发 Done.
935 市场营销 Done.
936 网站运营 Done.
942 汉语 Done.
910 迪士尼 儿童 15938737424 地点 郑州 富田 太阳城 一站 站 广场 Done.
945 平面 设计师 Done.
940 project manager Done.
939 acca Done.
941 对外汉语 Done.
943 计算语言 Done.
949 lsb Done.
950 网页前台 Done.
951 前台设计 Done.
948 运营助理 Done.
944 系统 工程师 Done.
952 诚聘 Done.
946 系统架构 Done.
955 民生银行 Done.
956 阜新 Done.
957 坪山 Done.
958 深圳龙岗 Done.
959 龙岗 Done.
954 文案策划 Done.
962 java 杭州 Done.
963 依娃璇子 Done.
953 俱乐部 Done.
938 品牌经理 Done.
961 产品 经理 客户端 Done.
960 JAVA 架构 师 Done.
964 找c 服务器端开发人员,windows平台,熟悉分布式设计,流处理设计,薪水从优 Done.
966 公司招聘 设计师 Done.
967 OpenGL 实习生 Done.
968 OpenGL Done.
965 江青 Done.
969 android 北京 Done.
974 网络兼职 Done.
975 储运经理 Done.
973 j2ee Done.
972 市场专员 Done.
970 微博招聘 Done.
971 风险 Done.
947 系统 架构 师 Done.
978 java 工程师 Done.
981 巨人 Done.
979 王国 Done.
982 文理兼通 Done.
983 文理 Done.
985 姜沈励 Done.
986 苏州采购 Done.
984 逻辑 Done.
976 售后 Done.
977 等等 Done.
980 五 Done.
989 精算师 Done.
992 twitter Done.
993 珠海 Done.
987 供应链 Done.
995 温州 Done.
991 网站编辑 Done.
990 英才网 Done.
994 ios Done.
997 金华 Done.
988 北京 会计 Done.
999 防盗门 Done.
1000 三国 Done.
1003 analytics Done.
1002 google analytics Done.
1001 青岛招聘 Done.
1004 市场尽力 Done.
1005 scala Done.
1008 公关总监 Done.
1007 安踏 Done.
996 义乌 Done.
1006 什么 Done.
1009 江 Done.
1014 #招聘# Done.
1013 seo 广州 Done.
998 scooter Done.
1010 WPF Done.
1012 的 Done.
1011 silverlight Done.
1021 广州 SEO Done.
1020 360 Done.
1016 #光谷# Done.
1018 net Done.
1019 php 郑州 Done.
1017 456 Done.
1015 高级 Done.
1024 sns 杭州 Done.
1026 关心网 Done.
1030 设计员 Done.
1029 网游 Done.
1025 自然语言 Done.
1027 杭州 实习生 Done.
1022 公司 Done.
1031 设计员 南京 Done.
1023 人力资源 经理 Done.
1032 实习生 郑州 Done.
1028 玉米 Done.
1036 开心网 Done.
1034 新浪微博 Done.
1035 人人网 Done.
1037 文员 北京 Done.
1038 厦门 php Done.
1033 惠城 Done.
1041 and 1 Done.
1042 order by 10 Done.
1043 1 and Done.
1044 <> Done.
1046 script alert a Done.
1040 sdgf Done.
1048 新浪 交互 设计师 了 Done.
1049 联发科技 Done.
1052 recruiting Done.
1051 产品 专员 上海 Done.
1050 报关 Done.
1055 广州 校园招聘 Done.
1057 插画师 Done.
1056 见 Done.
1053 应聘 设计师 Done.
1054 产品 经理助理 Done.
1045 script Done.
1047 新浪 交互 设计师 Done.
1058 广州 文员 Done.
1060 net 成都 Done.
1061 艺助 Done.
1062 艺人助理 Done.
1065 足浴技师 Done.
1059 广州文员 Done.
1064 产品 设计师 Done.
1069 会计 大连 Done.
1070 到底 Done.
1066 足浴 Done.
1073 深圳 Symbian Done.
1067 足疗 Done.
1071 君隆 Done.
1075 北京 公关 Done.
1077 时尚集团 Done.
1074 深圳 php Done.
1072 人力 Done.
1076 总编 Done.
1078 现代传播 Done.
1079 瑞丽 Done.
1082 PR Done.
1084 平媒 Done.
1080 桦榭 Done.
1083 平媒经历 Done.
1088 solr Done.
1087 cate Done.
1086 斯坦尼康 Done.
1085 PD Done.
1081 周刊 Done.
1090 广州 新浪 Done.
1092 2011、 Done.
1094 d Done.
1095 们公 Done.
1089 山东浪潮齐鲁软件产业股份有限公司诚聘优秀软件工程师应届毕业生,资深软件工程师、软件测试工程师、嵌入式软件工程师、GIS/GPS软件工程师、单片机软件工程师、数据库开发工程师、网络工程师、高级JAVA软件工程师、高级.NET软件工程师、高级C 软件工程师、项目经理、销售总监 Done.
1093 2011 Done.
1096 1-2 Done.
1099 信社区产 Done.
1100 信共 Done.
1101 动互联 Done.
1091 上海 交互 Done.
1103 银联 Done.
1104 内容运营 Done.
1105 互联网 产品 Done.
1102 急招 Done.
1106 残疾 Done.
1068 界面 设计师 一名 请 帮忙 Done.
1107 网页设计 广州 Done.
1108 人事 广州 Done.
1110 网页 设计师 广州 Done.
1109 行政 广州 Done.
1111 56 Done.
1112 家具设计 Done.
1113 arm Done.
1116 360安全 Done.
1115 新葵互动 Done.
1114 人民 Done.
1063 区域 经理 市场营销 人员 人 项目 河南 许继 仪表 有限公司 详情 请 http db dqjob 88 com vvip cm 1277951335735 2 更多 信息 www job 1001 查看 Done.
1117 分布式 Done.
1118 说 Done.
1121 网络 工程师 Done.
1122 阿里巴巴 产品 Done.
1120 c 方向 Done.
1119 实习生 java Done.
1123 淘宝 产品 Done.
1125 广州 外企 Done.
1126 广州 媒 Done.
1127 产品 广州 Done.
1128 情报学 Done.
1124 产品设计 上海 Done.
1133 产品 上海 Done.
1130 产品 经理 北京 Done.
1129 北京 交互 Done.
1134 移动支付 Done.
1136 sheying Done.
1138 nike Done.
1137 北京 产品 经理 Done.
1132 实习生 杭州 Done.
1135 互联网 Done.
1098 有没有 弟弟 妹妹 软件开发 要 找工作 Done.
1139 nike 6.0 Done.
1140 hjghj Done.
1142 河南 Done.
1143 监理 Done.
1146 chanpin Done.
1141 flex Done.
1145 隧道 Done.
1144 隧道监理 Done.
1097 有没有 弟弟 妹妹 软件开发 需要 找工作 Done.
1147 chanpinsh Done.
1152 南昌那个 Done.
1151 实习生 上海 Done.
1153 南昌 Done.
1148 chanping Done.
1149 风水 Done.
1150 产品 经理 上海 Done.
1156 模拟设计 Done.
1159 美国 Done.
1158 传播学 Done.
1160 上海 php Done.
1157 模拟 Done.
1163 塘沽 Done.
1155 日文 Done.
1161 奇虎360 Done.
1162 副总 Done.
1168 交互 天津 Done.
1165 电脑 Done.
1164 电脑技术 Done.
1166 雕蜡 Done.
1167 北京 net Done.
1169 焊接 Done.
1172 wordpress Done.
1171 北京 机械 Done.
1174 许利雄 Done.
1170 北京 类 Done.
1173 模具设计 Done.
1175 百纳 Done.
1178 北京 手机 gui Done.
1179 北京 gui Done.
1180 台湾 Done.
1176 gui Done.
1181 php 经理 北京 Done.
1177 手机 gui Done.
1154 汽车 上海 Done.
1183 微软中国 Done.
1186 重庆 网站 Done.
1187 品质管理 Done.
1185 adobe Done.
1190 实习生 山西 Done.
1188 老师 Done.
1182 微软 Done.
1191 山西 Done.
1189 运营总监 Done.
1195 电视 广州 Done.
1192 bs Done.
1194 广州 媒体 Done.
1193 阿里巴巴 国际 站 Done.
1196 电视广州 Done.
1197 广州 电视 Done.
1200 上海 设计师 Done.
1199 上海 前端 设计师 Done.
1198 广州电视 Done.
1201 北京 C Done.
1203 北京 ajax Done.
1205 UED 经理 Done.
1204 marketing Done.
1206 北京 android Done.
1184 飞信 Done.
1202 山东 Done.
1207 上海 android Done.
1209 广州 手机游戏 Done.
1131 全音 乐组 的人 人去 嗨歌 歌 耶耶 给 队长 过 生日 Done.
1214 webex Done.
1210 广州 儿童 Done.
1208 广州 手机 Done.
1217 编辑 北京 Done.
1218 Lotus Done.
1216 彳 Done.
1212 腾讯微博 Done.
1211 广州 产品 经理 Done.
1213 hadoop Done.
1215 新浪 编辑 Done.
1220 Domino Done.
1224 用户 上海 Done.
1223 交互 上海 Done.
1219 Notes Done.
1226 yoka Done.
1222 优视 Done.
1225 编辑 济南 Done.
1227 新浪编辑 Done.
1230 季 Done.
1221 UC Done.
1232 福建 Done.
1235 编辑 广州 Done.
1231 招贤纳士 Done.
1229 投资银行 Done.
1239 枫华创益 Done.
1233 微博 博 招聘网 Done.
1234 李开复 Done.
1236 投资经理 Done.
1228 信托 Done.
1242 xhso Done.
1243 kl Done.
1238 百事 Done.
1240 明星 Done.
1245 poMars Zheng Done.
1241 歌手 Done.
1244 po Done.
1249 缸/淋浴 Done.
1251 青岛 暖 Done.
1250 宝 Done.
1246 perl Done.
1237 联合利华 Done.
1252 胡锦涛 Done.
1256 上海会计 Done.
1255 上海财务 Done.
1258 上海 设备 工程师 Done.
1254 android 广州 Done.
1257 设备 工程师 Done.
1260 上海 设备工程师 Done.
1259 分析员 Done.
1247 语言 Done.
1253 采购经理 Done.
1265 建安大 Done.
1264 瑞典 Done.
1263 瑞士 Done.
1262 法国 Done.
1266 加拿大 Done.
1267 比利时 Done.
1269 芬兰 Done.
1268 卢森堡 Done.
1270 北欧 Done.
1272 西班牙 Done.
1261 osgi Done.
1271 意大利 Done.
1277 网站管理 Done.
1276 外贸 广州 Done.
1274 外貿 Done.
1279 网络管理员 Done.
1278 网管 Done.
1281 广东 php Done.
1280 春 分立 秋冬 至 Done.
1273 公益 Done.
1282 甘肃 php Done.
1275 外贸 州 Done.
1283 新疆 php Done.
1248 丁香 数据库 工程师 MySQL DBA Done.
1284 揭阳 php Done.
1289 Mars Zheng Done.
1291 桂林 Done.
1288 39健康网 Done.
1287 游戏 工程师 广州 Done.
1290 北京 产品 设计师 Done.
1295 用户研究 Done.
1292 中山 Done.
1296 iphone 深圳 Done.
1297 mba Done.
1299 dresses Done.
1300 groupon Done.
1298 lashou Done.
1301 51job Done.
1305 city 杭州 Done.
1302 lightinthebox Done.
1294 d 5 Done.
1285 广东 php 工程师 Done.
1307 mongodb Done.
1306 nosql Done.
1308 监测 Done.
1304 cate 软件测试 city 杭州 Done.
1310 客服 Done.
1303 b2c Done.
1286 游戏 工程师 Done.
1313 实习生 佛山 Done.
1314 实习生 广州 Done.
1311 生 北京 Done.
1318 深圳 实习生 Done.
1317 护士 Done.
1312 北京 生 Done.
1319 电子商务 深圳 Done.
1320 深圳 电子商务 Done.
1323 低碳 Done.
1325 haha Done.
1324 新能源 Done.
1321 网络营销 深圳 Done.
1309 环境 Done.
1316 京东 Done.
1315 派代 Done.
1330 上海 公关 Done.
1328 广州兼职 Done.
1329 浏览器 Done.
1326 互联网 产品 经理 Done.
1332 新浪 微博 博 Done.
1322 CDM Done.
1331 新浪 微博 Done.
1327 摄影师 Done.
1335 c# 苏州 Done.
1338 123 Done.
1339 研究所 Done.
1337 c# 苏 州 Done.
1333 学徒 Done.
1336 播音 Done.
1340 新加坡 Done.
1344 rhce Done.
1345 OCP Done.
1342 农民 Done.
1346 济南 操作工 Done.
1347 操作工 山东 Done.
1341 劳务 Done.
1348 山东 操作工 Done.
1343 操作工 Done.
1351 产品经历 Done.
1352 csico Done.
1353 江门 Done.
1349 商河 Done.
1350 生产副总 Done.
1356 奕惠嘉 Done.
1359 2131 Done.
1357 暑期工 Done.
1358 页面重构 Done.
1355 希捷 Done.
1361 冶金 Done.
1360 微薄 Done.
1364 游戏 媒介 经理 Done.
1363 CEO Done.
1362 程序 Done.
1365 英语翻译 Done.
1366 网页美工 Done.
1371 baidu Done.
1370 珍爱网 Done.
1367 重构 Done.
1372 商业地产 Done.
1354 Java Senior Software Engineer 软件 工程师 Done.
1374 java 北京 Done.
1334 服务器 Done.
1369 百合网 Done.
1368 世纪佳缘 Done.
1378 大熊 Done.
1373 社交 Done.
1379 eclipse Done.
1381 广州 实习生 Done.
1383 沈阳 韩语 翻译 Done.
1382 木兰设计 Done.
1380 客户服务 Done.
1384 沈阳翻译 Done.
1385 周熙 Done.
1377 深圳 互联网 Done.
1389 制片人 Done.
1387 数字图像 Done.
1388 图像 Done.
1390 识别 Done.
1391 建筑动画 Done.
1386 照片 Done.
1392 相机 Done.
1395 设计学徒 Done.
1393 执行主编 Done.
1396 CAD Done.
1399 电厂 Done.
1394 sarft net Done.
1398 医学 Done.
1401 垃圾 Done.
1402 神经病 Done.
1400 工资 Done.
1376 安全工程 Done.
1375 空调 Done.
1397 力推 上海 淮海 新日铁 招 JAVA 日语 要 学校 211 Done.
1406 蛋白质 Done.
1405 发酵 Done.
1410 律师 南宁 Done.
1412 临沂 Done.
1403 好玩 Done.
1408 广州实习 Done.
1404 纯化 Done.
1411 婚纱 Done.
1409 安全测试 Done.
1415 上海 美术 Done.
1417 交互 深圳 Done.
1413 soho Done.
1418 礼宾员 Done.
1407 游戏开发 Done.
1414 视觉 Done.
1419 talend Done.
1423 郑州 法语 Done.
1422 美团 Done.
1424 郑州 英语 Done.
1425 郑州 外语 Done.
1420 网站设计 Done.
1427 jobkoo Done.
1426 sales Done.
1429 媒介 北京 Done.
1416 产品策划 Done.
1432 sharepoint Done.
1434 fles Done.
1431 moss Done.
1433 开心 Done.
1435 汽修 Done.
1437 c/c Done.
1440 上海 oracle Done.
1438 新疆 Done.
1439 北京 产品 Done.
1430 媒介执行 Done.
1441 net 软件 工程师 Done.
1442 深圳 net 软件 工程师 Done.
1443 qqqqr Done.
1436 猎头职位 Done.
1446 北京保安 Done.
1428 媒介 Done.
1445 视觉设计 是飞 Done.
1447 php 围绕 Done.
1452 call center Done.
1453 呼叫中心 北京 Done.
1450 net 北京 Done.
1454 建筑 哈尔滨 Done.
1457 郑州 房产 人员 Done.
1451 宝马 Done.
1449 深圳 行政 Done.
1459 电气销售 Done.
1460 宁夏销售 Done.
1461 城市规划 Done.
1444 保安 Done.
1458 房产销售 Done.
1464 杭州 电子商务 产业园 Done.
1462 网络推广 Done.
1463 asp net 程序员 Done.
1448 兼 Done.
1467 虾米网 Done.
1468 CAD 机械 设计师 Done.
1469 CAD 机械 Done.
1466 唯你网 Done.
1470 zhonghuayantu Done.
1473 CAD 员 大学生 Done.
1472 CAD 大学生 Done.
1465 杭州 电子商务 Done.
1455 cate 视频 编辑 city 济南 Done.
1478 郑德明 Done.
1479 交互 杭州 Done.
1477 公关策划 Done.
1476 策划经理 Done.
1475 技术 Done.
1481 视觉设计 北京 Done.
1474 行政助理 Done.
1482 网页设计 北京 Done.
1485 珠海司机 Done.
1483 北京 游戏公司 Done.
1488 网络推广 长沙 Done.
1484 网站策划 Done.
1486 司机 Done.
1471 大学生 Done.
1490 samwang jobkoo com Done.
1492 职酷 Done.
1480 电话回访 Done.
1491 jobkoo com Done.
1489 职酷网 Done.
1493 深深深 Done.
1497 国际贸易 上海 Done.
1498 上海 英语翻译 Done.
1499 上海 日语 翻译 Done.
1495 华为 Done.
1501 160 深圳 Done.
1500 上海翻译 Done.
1502 160深圳 Done.
1504 影视 设计类 Done.
1503 数据分析 Done.
1506 北京影视 Done.
1507 快递 Done.
1496 国际贸易 Done.
1494 北京 大麦 网 前端 工程师 Done.
1487 网络编辑 Done.
1510 马鞍山 Done.
1511 保时捷 Done.
1512 杭州 园林 Done.
1508 charming lu sina cn Done.
1509 交互 新蛋 Done.
1505 影视 Done.
1518 897720084 Done.
1517 交互 实习生 Done.
1516 网页 设计师 北京 Done.
1515 北京 seo Done.
1520 嘉定 Done.
1522 wangjiayun11 Done.
1521 深圳 包装设计 Done.
1513 团购 Done.
1525 1122 Done.
1524 厦门、 Done.
1527 景德镇 Done.
1526 asp net Done.
1514 city 重庆 文案 助理 要求 英语 专业 Done.
1528 农药 Done.
1519 摄影助理 Done.
1530 上海 宝 Done.
1529 result Done.
1531 新蛋 Done.
1532 java 广州 Done.
1535 fdsafdsa Done.
1534 成都 java 架构 师 Done.
1536 地产中介 Done.
1533 中文 Done.
1523 前端 工程师 Done.
1538 杭州 虾米 Done.
1539 北京百度 Done.
1542 北京 豆瓣 Done.
1541 上海 pplive Done.
1543 广州 网页设计 Done.
1545 dsfasdf Done.
1540 北京 百度 Done.
1546 outlook Done.
1548 vba Done.
1544 东北 Done.
1547 网页设计 深圳 Done.
1550 海归 Done.
1549 河北 Done.
1552 江苏 Done.
1554 广州 新浪 微博 Done.
1555 南京 实习生 Done.
1537 地产 Done.
1556 动漫助理 Done.
1553 江明炜 Done.
1557 seo 推文 Done.
1558 帝网 络 Done.
1561 1 Done.
1559 ss Done.
1560 22 3 Done.
1562 12 Done.
1565 童装 设计师 Done.
1566 上海 产品 经理 Done.
1568 网络 编辑 Done.
1563 3 Done.
1564 服装 设计师 Done.
1572 合肥 Done.
1570 行政 Done.
1551 国外 Done.
1569 招聘专员 Done.
1567 美术编辑 Done.
1571 产品 经理 无线 Done.
1456 南京 天 天加 加 空调设备 有限公司 硬件 工程师 人 商用机 产品 等等 详情 请 http www ntjob 88 com vvip cm 1294213192877 更多 信息 暖通 英才 网 Done.
1576 设计 北京 Done.
1580 阿里 Done.
1577 银时代 Done.
1579 将爱 Done.
1578 传统文化 网络 编辑 Done.
1573 方正 Done.
1575 测试 工程师 Done.
1582 金鹰 Done.
1584 销售助理 Done.
1583 天翼 Done.
1586 上海策划 Done.
1585 上海企划 Done.
1581 beij Done.
1574 运维 维 工程师 Done.
1588 广州 外贸 跟 单员 Done.
1589 广州 跟 单员 Done.
1591 重庆 网站 编辑 Done.
1594 快消品 Done.
1592 搜狐微博 Done.
1587 广州 外贸 Done.
1598 实习 天津 Done.
1597 广州 PHP Done.
1593 n8 Done.
1600 长沙 net Done.
1599 求职 实习生 Done.
1602 实习生 天津 Done.
1604 安智网 Done.
1601 实习生 招聘 Done.
1595 net 工程师 Done.
1605 贾琪 Done.
1606 诺亚 Done.
1603 北京 金融 Done.
1607 研华 Done.
1608 制药 Done.
1590 电影剪辑 Done.
1610 实习 金融 专业 Done.
1596 39健康 Done.
1614 asp Done.
1613 nihao Done.
1615 聚能灶 Done.
1616 groupon hr sina com Done.
1609 昆明 Done.
1620 procurement Done.
1621 广州 服务员 Done.
1617 ljb 115 com Done.
1619 汽车之家 Done.
1624 杭州 赛博 创业 工场 Done.
1612 企划 Done.
1618 开发 Done.
1611 杭州 招聘 产品设计 人员 Done.
1626 杭州 创业 Done.
1628 豆瓣招聘 Done.
1630 xiaolinzou Done.
1622 网页 Done.
1631 网络 编辑 重庆 Done.
1623 研发 Done.
1632 重庆 网站 设计师 Done.
1633 重庆 网页 设计师 Done.
1625 赛博 创业 工场 Done.
1636 重庆 文案 策划 Done.
1635 重庆 产品 设计师 Done.
1627 香港 Done.
1638 通訊 Done.
1629 caoyang corp the 9 com Done.
1637 engineer Done.
1640 通信维护 Done.
1643 校园能人 Done.
1644 阜阳 师范学院 Done.
1639 光缆维护 Done.
1645 阜师院 Done.
1641 通信 Done.
1642 通信技术 Done.
1634 重庆 设计师 Done.
1647 交互 设计 实习生 Done.
1648 广州招聘 Done.
1649 用户 研究员 Done.
1653 北京 平面设计 Done.
1652 北京 求职 平面设计 Done.
1651 摄影招聘 Done.
1655 厦门司机 Done.
1657 律师助理 Done.
1658 奢侈品 Done.
1659 GUCCI Done.
1656 店长 Done.
1661 安全管理 Done.
1660 LV Done.
1663 新浪体育 Done.
1666 北京 减排 Done.
1664 zhangjing Done.
1665 深圳 运营 Done.
1662 张玉铭 Done.
1667 项目 经理 北京 Done.
1669 广州 编辑 Done.
1671 ui 设计 杭州 Done.
1672 大麦 Done.
1673 大麦 上海 Done.
1670 华为 孙亚芳 Done.
1668 诺基亚 Done.
1674 UED 经理 上海 Done.
1676 upipi pi Done.
1677 厦门兼职 Done.
1680 测试研发 Done.
1678 证券分析 Done.
1675 记者 编辑 Done.
1679 人力资源 总监 Done.
1682 郑州 实习生 Done.
1681 火花网 Done.
1683 郑州 java Done.
1685 质控 Done.
1654 系统 Done.
1687 内容 管理系统 Done.
1689 深圳 自动化 Done.
1688 广东招聘 Done.
1684 QC Done.
1686 液相 Done.
1646 维修电工 Done.
1693 兼职运营 Done.
1692 侯子爱 吃 桃子 Done.
1691 手机游戏 Done.
1694 软件开发 工程师 Done.
1699 架构 师 上海 Done.
1690 陈列 Done.
1696 手工 Done.
1697 生活馆 Done.
1700 软件 架构 师 北京 Done.
1701 云吞 Done.
1702 13916086091 Done.
1695 产品 实习 Done.
1698 软件 架构 师 Done.
1704 杭州 动漫 Done.
1706 理想 哥 产品 经理 Done.
1703 阳江 Done.
1708 中国 国际 动漫 节 Done.
1709 动漫节 Done.
1705 北京 动漫 Done.
1707 项目 经理 Done.
1712 货代 Done.
1714 郑州 外贸 跟 单员 Done.
1715 浙江 Done.
1716 策划 北京 Done.
1713 外贸 跟 单员 Done.
1710 佛山 Done.
1720 产品 经理 手机 Done.
1717 淘宝房产 Done.
1721 binarylee Done.
1719 树苗 Done.
1711 日语 Done.
1725 舞蹈招聘 Done.
1723 生 广州 Done.
1726 界面外包 Done.
1724 舞蹈 Done.
1727 界面 外包 Done.
1718 树 Done.
1722 无线 产品 经理 北京 Done.
1728 UI 外包 Done.
1731 深圳 产品 经历 Done.
1729 深圳 产品 设计师 Done.
1732 深圳 产品 经理 Done.
1730 深圳 产品 Done.
1733 交互 实习 北京 Done.
1734 实习 交互 北京 Done.
1737 faxtee Done.
1736 创业 北京 Done.
1740 联系售后 Done.
1738 成都 市场 Done.
1742 联想电脑 Done.
1741 联系 售后服务 Done.
1739 cic Done.
1746 深圳 设计 Done.
1743 毕业生 Done.
1745 测试经理 Done.
1748 测试 工程师 上海 Done.
1744 guoli1 Done.
1749 三五互联 Done.
1750 沈阳 机械 Done.
1747 兰亭集势 Done.
1751 求职 ios Done.
1753 深圳 管理咨询 Done.
1754 hr duohuwai com Done.
1756 农商 Done.
1755 宝宝教育 Done.
1752 市场总监 Done.
1760 化学 Done.
1758 材化 Done.
1759 材化 Done.
1763 全段 Done.
1761 mysql DBA Done.
1764 兼职客服 Done.
1757 材料 Done.
1765 珠海招聘 Done.
1766 成都 ui Done.
1767 建筑设计 Done.
1771 助理 天津 Done.
1770 遥感 Done.
1769 当当 Done.
1768 建筑 设计 Done.
1735 项目管理 Done.
1772 助理 北京 Done.
1773 招 实习 广州 Done.
1774 北京 移动 互联网 Done.
1777 招实习 广州 Done.
1776 idg Done.
1781 郑州 实习 Done.
1775 深圳 android Done.
1780 酷狗 Done.
1782 后期 Done.
1783 lingxue 1985 h Done.
1785 guangz Done.
1778 生 天津 Done.
1779 服务端 Done.
1786 asp net 成都 Done.
1788 aasdf Done.
1787 ffff Done.
1790 再发 发 围脖 征募 Done.
1792 瓦力 Done.
1793 DKM Done.
1794 武汉 java Done.
1789 MM Done.
1791 求职信息 Done.
1795 产品实习 Done.
1797 renderman Done.
1798 php 方面 职位 Done.
1796 天 Done.
1799 北京 交互 设计 Done.
1801 大专 学历 女孩子 做 Done.
1800 交互 设计 北京 Done.
1804 24券团购 Done.
1802 Goso Done.
1805 24券 Done.
1803 融众网 Done.
1807 前台 北京 Done.
1810 视觉设计 阿里 Done.
1808 市场 运营 助理 Done.
1809 深圳 网页 设计师 Done.
1811 销售 深圳 Done.
1812 深圳 销售 Done.
1813 太原 编辑 Done.
1762 实习生 北京 交互 设计 Done.
1784 lingxue 1985 hotmail com Done.
1806 网站技术 经理 Done.
1818 厦门 平面 Done.
1816 爱库 Done.
1820 厦门 实习 Done.
1814 杂志 编辑 Done.
1821 鄂尔多斯 Done.
1819 文字录入 Done.
1815 音乐 编辑 Done.
1817 厦门 ui Done.
1822 建筑工程 设计 Done.
1829 中演 票务 通 Done.
1827 广东汕头 Done.
1830 凯业必达 Done.
1831 GUI 设计师 Done.
1823 建筑工程 技术 Done.
1832 呼叫中心 运营 经理 Done.
1833 康琴伢 Done.
1834 13657439572 Done.
1825 数值策划 Done.
1828 化妆师 Done.
1835 产品 北京 Done.
1826 凡客 Done.
1840 新浪 商务 拓展 Done.
1839 上海兼职 Done.
1838 上海 兼职 Done.
1824 杭州 实习 Done.
1842 新浪 前端 Done.
1845 美会 Done.
1844 亿贝 Done.
1841 山东 前端 Done.
1843 ebay Done.
1836 产品 经理 无限 Done.
1837 20万 Done.
1850 风险投资 Done.
1852 麦包包 Done.
1851 风投 Done.
1849 associate Done.
1848 investment Done.
1853 用友 商务 Done.
1856 编辑 郑州 Done.
1858 网易 含 资格 Done.
1857 上海 支付 宝 Done.
1855 俄语翻译 Done.
1859 网易杭州 Done.
1860 西宁 Done.
1862 杭州 音乐 Done.
1861 用友北京 Done.
1854 北京招聘 Done.
1846 惠普 Done.
1863 音乐 杭州 Done.
1866 青岛 交互 设计 Done.
1867 大连 前端 Done.
1865 13326657232 Done.
1864 丁允 Done.
1871 运城 Done.
1869 长沙 java Done.
1872 北京 销售 Done.
1875 1985 Done.
1876 杭州 法律 Done.
1873 android 上海 Done.
1874 drupal Done.
1877 杭州 法学 Done.
1870 统计分析 Done.
1878 天津滨海 Done.
1868 市场 北京 Done.
1882 广州 客户端 Done.
1879 asdfasdfasd Done.
1886 微盘 Done.
1883 社区 运营 Done.
1884 游戏测试 Done.
1881 客户端 Done.
1885 数据库 工程师 Done.
1880 数据库 开发 工程师 Done.
1888 成都 经营 Done.
1889 成都 运营 Done.
1892 成都 经理 Done.
1891 成都 经理 Done.
1893 成都 产品 Done.
1896 厦门 界面 Done.
1895 汽车 南京 Done.
1894 汽车 检测员 Done.
1890 成都 经理 Done.
1898 超经 Done.
1897 建筑 工程师 Done.
1899 经纪人 Done.
1847 万 Done.
1900 北京 网页 设计师 Done.
1903 seo 工程师 Done.
1905 ls Done.
1904 产品 总监 北京 Done.
1902 市场北京 Done.
1906 环艺 Done.
1887 罗兰 科技发展 有限公司 Done.
1907 重庆销售 Done.
1910 广州 投资 经理 Done.
1901 用户 Done.
1912 中文分词 Done.
1911 产品 经理 广州 Done.
1908 led Done.
1909 杭州 php Done.
1916 @小马拓 Done.
1913 广州 互动 Done.
1915 交互 设计 上海 Done.
1919 北京 平面设计 实习生 Done.
1914 设计经理 Done.
1918 平面设计 实习生 Done.
1921 徐小平 Done.
1917 上 Done.
1922 盛大 Done.
1924 运维 维 工程师 sina Done.
1925 sina Done.
1927 产品设计 实习 Done.
1928 bet Done.
1929 BJBET CN Done.
1931 玉林 Done.
1930 android java Done.
1934 产品 经理 深圳 Done.
1935 lvyulin 20082163 com Done.
1933 java python Done.
1932 兼职 北京 Done.
1936 lvyulin 2008 163 com Done.
1938 加盟招商 Done.
1926 king Done.
1939 ux Done.
1940 系统开发 Done.
1941 有奖 Done.
1937 拓展 Done.
1920 city 北京 cate 程序员 Done.
1923 平面 Done.
1946 ggggggggggaaaaa Done.
1943 伯乐奖 Done.
1944 php 厦门 Done.
1951 goldengate Done.
1950 安徽 司机 Done.
1949 幕墙 销售 经理 职位 Done.
1952 容灾 Done.
1953 灾备 Done.
1945 工商 Done.
1948 总经理 Done.
1955 uspv Done.
1954 hds Done.
1957 易到用车 Done.
1956 网页 设计师 兼职 Done.
1958 BD 广州 Done.
1947 上海 生 Done.
1942 伯乐 Done.
"""
b=a.split('\n')
e=[]
for c in b:
d=" ".join(c.split()[:-1])
e+=[d]
g="\r\n".join(e).encode('utf-8')
f = open("tbole.txt", "w")
f.write(g)
f.close()
print "Wrote results."
| Python |
#!/usr/bin/env python
#coding=utf-8
catelist = [
(1, u"传统网络Internet"),
(2, u"移动互联"),
(3, u"网游"),
(4, u"电子商务_B2C/团购"),
(5, u"软件、电信"),
(6, u"新媒体"),
(7, u"风投/投行"),
(8, u"其他外企"),
]
idlist = [
[1, (u"超超Sandy", "d11c25990634d0e486235f1b42a55f9f", "89859ba49065135017b894df5e5a9089")],
[1, (u"传统网络2", "9257d982dcbc26d21fa4f0afb16a54be", "e99c1ae713e14edc3ec3abb7e2344be3")],
[2, (u"冬冬Billy", "f6449dd703d66cf2be5274f321416958", "31c47db4cd79e43a9196871a554d0847")],
[2, (u"新潮-独", "e17cec5e79cd81704aa4b73d15caf639", "983582e2b4b880cc35caa7ac38ce3449")],
[2, (u"移动互联2", "6193a010668f5dcc106e671babf4fbe1", "605e4449590b2c3d96d34b049f96fdbd")],
[3, (u"田田July", "032ec596fa363aa9bd3e5e5917f6aea4", "9e0c243fa3ff3515765510ba4010c411")],
[3, (u"网游2", "743700d7ec385d0b740ecc9a4ef519d4", "b89c6d406e235ab3c49ccea1d82b5622")],
[4, (u"田田Lily", "3ef7fc951a66918dd1cd722485fe1686", "74f524fe376ce995703e73e63407684f")],
[4, (u"电子商务临2", "669001d16b1641a2138d529b435eaefb", "13f58a73995fd2b80bc0aa875ad363f0")],
[5, (u"小朱Linda", "0c10534f393fe08451edb140e3b1150d", "423fd333a2542dbf6e2a38119a6e7e04")],
[5, (u"软件电信2", "f577ad7699dc1a74330bc41329c2ce71", "20cc173dbb46a6784588767e71de03ef")],
[6, (u"小王trueman", "1f8f7db82cdbc346a91840cef2bc1cb9", "a16ead9ee3b6b3f43e601de127275ddc")],
[6, (u"新媒体2", "fc565ccfa32bdb962becc8d49a5a37d3", "8504469c6cad83cde0998299aca8b2fa")],
[7, (u"小毕Simon", "4151efe34301f5fddb9d34fc72e5f4a4", "dc4a07e8b7936d688726604a7442e4bc")],
[7, (u"风投2", "b14cbaaae5e46079770ea77feeaa0c91", "2dd7a1e5bb6036d69b2c983aa3f2a682")],
[8, (u"小黄Lily", "8ee871ac7d18e0141b54077fefd58af6", "dc5cda5a9a4ab5c5a5cd53f85f1f7915")],
[8, (u"外企名企2", "6712203ce54da88930f72014a0ef90bd", "d97779c02d60cacbabd0c398cb8acd93")],
]
| Python |
# -*- coding: utf-8 -*-
from ragendja.settings_pre import *
# Increase this when you update your on the production site, so users
# don't have to refresh their cache. By setting this your MEDIA_URL
# automatically becomes /media/MEDIA_VERSION/
MEDIA_VERSION = 1
# By hosting media on a different domain we can get a speedup (more parallel
# browser connections).
#if on_production_server or not have_appserver:
# MEDIA_URL = 'http://media.mydomain.com/media/%d/'
# Add base media (jquery can be easily added via INSTALLED_APPS)
COMBINE_MEDIA = {
'combined-%(LANGUAGE_CODE)s.js': (
# See documentation why site_data can be useful:
# http://code.google.com/p/app-engine-patch/wiki/MediaGenerator
'.site_data.js',
),
'combined-%(LANGUAGE_DIR)s.css': (
'global/look.css',
),
}
# Change your email settings
if on_production_server:
DEFAULT_FROM_EMAIL = 'drkkojima@gmail.com'
SERVER_EMAIL = DEFAULT_FROM_EMAIL
# Make this unique, and don't share it with anybody.
SECRET_KEY = '19720403'
#ENABLE_PROFILER = True
#ONLY_FORCED_PROFILE = True
#PROFILE_PERCENTAGE = 25
#SORT_PROFILE_RESULTS_BY = 'cumulative' # default is 'time'
# Profile only datastore calls
#PROFILE_PATTERN = 'ext.db..+\((?:get|get_by_key_name|fetch|count|put)\)'
# Enable I18N and set default language to 'en'
USE_I18N = True
TIME_ZONE = 'Asia/Tokyo'
LANGUAGE_CODE = 'en'
# Restrict supported languages (and JS media generation)
LANGUAGES = (
# ('de', 'German'),
('en', 'English'),
# ('ja', 'Japanese'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.media',
'django.core.context_processors.request',
'django.core.context_processors.i18n',
)
MIDDLEWARE_CLASSES = (
'ragendja.middleware.ErrorMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'httpauth.Middleware',
# Django authentication
'django.contrib.auth.middleware.AuthenticationMiddleware',
# Google authentication
#'ragendja.auth.middleware.GoogleAuthenticationMiddleware',
# Hybrid Django/Google authentication
#'ragendja.auth.middleware.HybridAuthenticationMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.locale.LocaleMiddleware',
'ragendja.sites.dynamicsite.DynamicSiteIDMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
# Google authentication
#AUTH_USER_MODULE = 'ragendja.auth.google_models'
#AUTH_ADMIN_MODULE = 'ragendja.auth.google_admin'
# Hybrid Django/Google authentication
#AUTH_USER_MODULE = 'ragendja.auth.hybrid_models'
LOGIN_URL = '/account/login/'
LOGOUT_URL = '/account/logout/'
LOGIN_REDIRECT_URL = '/haco/report/'
INSTALLED_APPS = (
# Add jquery support (app is in "common" folder). This automatically
# adds jquery to your COMBINE_MEDIA['combined-%(LANGUAGE_CODE)s.js']
# Note: the order of your INSTALLED_APPS specifies the order in which
# your app-specific media files get combined, so jquery should normally
# come first.
'jquery',
# Add blueprint CSS (http://blueprintcss.org/)
'blueprintcss',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.webdesign',
'django.contrib.flatpages',
'django.contrib.redirects',
'django.contrib.sites',
'appenginepatcher',
'ragendja',
'myapp',
'registration',
'mediautils',
'haco',
)
# List apps which should be left out from app settings and urlsauto loading
IGNORE_APP_SETTINGS = IGNORE_APP_URLSAUTO = (
# Example:
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'yetanotherapp',
)
# Remote access to production server (e.g., via manage.py shell --remote)
DATABASE_OPTIONS = {
# Override remoteapi handler's path (default: '/remote_api').
# This is a good idea, so you make it not too easy for hackers. ;)
# Don't forget to also update your app.yaml!
#'remote_url': '/remote-secret-url',
# !!!Normally, the following settings should not be used!!!
# Always use remoteapi (no need to add manage.py --remote option)
#'use_remote': True,
# Change appid for remote connection (by default it's the same as in
# your app.yaml)
#'remote_id': 'otherappid',
# Change domain (default: <remoteid>.appspot.com)
#'remote_host': 'bla.com',
}
import sys, os
rootdir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(rootdir, "lib"))
from ragendja.settings_post import *
| Python |
from ragendja.settings_post import settings
settings.add_app_media('combined-%(LANGUAGE_CODE)s.js',
'myapp/code.js',
)
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
rootpatterns = patterns('',
(r'^person/', include('myapp.urls')),
)
| Python |
# -*- coding: utf-8 -*-
from django.db.models import permalink, signals
from google.appengine.ext import db
from ragendja.dbutils import cleanup_relations
class Person(db.Model):
"""Basic user profile with personal details."""
first_name = db.StringProperty(required=True)
last_name = db.StringProperty(required=True)
def __unicode__(self):
return '%s %s' % (self.first_name, self.last_name)
@permalink
def get_absolute_url(self):
return ('myapp.views.show_person', (), {'key': self.key()})
signals.pre_delete.connect(cleanup_relations, sender=Person)
class File(db.Model):
owner = db.ReferenceProperty(Person, required=True, collection_name='file_set')
name = db.StringProperty(required=True)
file = db.BlobProperty(required=True)
@permalink
def get_absolute_url(self):
return ('myapp.views.download_file', (), {'key': self.key(),
'name': self.name})
def __unicode__(self):
return u'File: %s' % self.name
class Contract(db.Model):
employer = db.ReferenceProperty(Person, required=True, collection_name='employee_contract_set')
employee = db.ReferenceProperty(Person, required=True, collection_name='employer_contract_set')
start_date = db.DateTimeProperty()
end_date = db.DateTimeProperty()
| Python |
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.core.files.uploadedfile import UploadedFile
from django.utils.translation import ugettext_lazy as _, ugettext as __
from myapp.models import Person, File, Contract
from ragendja.auth.models import UserTraits
from ragendja.forms import FormWithSets, FormSetField
from registration.forms import RegistrationForm, RegistrationFormUniqueEmail
from registration.models import RegistrationProfile
class UserRegistrationForm(forms.ModelForm):
username = forms.RegexField(regex=r'^\w+$', max_length=30,
label=_(u'Username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),
label=_(u'Email address'))
city =forms.RegexField(regex=r'^\w+$', max_length=30,
label=_(u'city'))
password1 = forms.CharField(widget=forms.PasswordInput(render_value=False),
label=_(u'Password'))
password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
label=_(u'Password (again)'))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
if user and user.is_active:
raise forms.ValidationError(__(u'This username is already taken. Please choose another.'))
return self.cleaned_data['username']
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(__(u'You must type the same password each time'))
return self.cleaned_data
def save(self, domain_override=""):
"""
Create the new ``User`` and ``RegistrationProfile``, and
returns the ``User``.
This is essentially a light wrapper around
``RegistrationProfile.objects.create_inactive_user()``,
feeding it the form data and a profile callback (see the
documentation on ``create_inactive_user()`` for details) if
supplied.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'],
domain_override=domain_override)
self.instance = new_user
return super(UserRegistrationForm, self).save()
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
email = self.cleaned_data['email'].lower()
if User.all().filter('email =', email).filter(
'is_active =', True).count(1):
raise forms.ValidationError(__(u'This email address is already in use. Please supply a different email address.'))
return email
class Meta:
model = User
exclude = UserTraits.properties().keys()
class FileForm(forms.ModelForm):
name = forms.CharField(required=False, label='Name (set automatically)')
def clean(self):
file = self.cleaned_data.get('file')
if not self.cleaned_data.get('name'):
if isinstance(file, UploadedFile):
self.cleaned_data['name'] = file.name
else:
del self.cleaned_data['name']
return self.cleaned_data
class Meta:
model = File
class PersonForm(forms.ModelForm):
files = FormSetField(File, form=FileForm, exclude='content_type')
employers = FormSetField(Contract, fk_name='employee')
employees = FormSetField(Contract, fk_name='employer')
class Meta:
model = Person
PersonForm = FormWithSets(PersonForm)
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
urlpatterns = patterns('myapp.views',
(r'^create_admin_user$', 'create_admin_user'),
(r'^$', 'list_people'),
(r'^create/$', 'add_person'),
(r'^show/(?P<key>.+)$', 'show_person'),
(r'^edit/(?P<key>.+)$', 'edit_person'),
(r'^delete/(?P<key>.+)$', 'delete_person'),
(r'^download/(?P<key>.+)/(?P<name>.+)$', 'download_file'),
)
| Python |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import create_object, delete_object, \
update_object
from google.appengine.ext import db
from mimetypes import guess_type
from myapp.forms import PersonForm
from myapp.models import Contract, File, Person
from ragendja.dbutils import get_object_or_404
from ragendja.template import render_to_response
def list_people(request):
return object_list(request, Person.all(), paginate_by=10)
def show_person(request, key):
return object_detail(request, Person.all(), key)
def add_person(request):
return create_object(request, form_class=PersonForm,
post_save_redirect=reverse('myapp.views.show_person',
kwargs=dict(key='%(key)s')))
def edit_person(request, key):
return update_object(request, object_id=key, form_class=PersonForm)
def delete_person(request, key):
return delete_object(request, Person, object_id=key,
post_delete_redirect=reverse('myapp.views.list_people'))
def download_file(request, key, name):
file = get_object_or_404(File, key)
if file.name != name:
raise Http404('Could not find file with this name!')
return HttpResponse(file.file,
content_type=guess_type(file.name)[0] or 'application/octet-stream')
def create_admin_user(request):
user = User.get_by_key_name('admin')
if not user or user.username != 'admin' or not (user.is_active and
user.is_staff and user.is_superuser and
user.check_password('admin')):
user = User(key_name='admin', username='admin',
email='admin@localhost', first_name='Boss', last_name='Admin',
is_active=True, is_staff=True, is_superuser=True)
user.set_password('admin')
user.put()
return render_to_response(request, 'myapp/admin_created.html')
| Python |
from django.contrib import admin
from myapp.models import Person, File
class FileInline(admin.TabularInline):
model = File
class PersonAdmin(admin.ModelAdmin):
inlines = (FileInline,)
list_display = ('first_name', 'last_name')
admin.site.register(Person, PersonAdmin)
| Python |
#!/usr/bin/env python
if __name__ == '__main__':
from common.appenginepatch.aecmd import setup_env
setup_env(manage_py_env=True)
# Recompile translation files
from mediautils.compilemessages import updatemessages
updatemessages()
# Generate compressed media files for manage.py update
import sys
from mediautils.generatemedia import updatemedia
if len(sys.argv) >= 2 and sys.argv[1] == 'update':
updatemedia(True)
import settings
from django.core.management import execute_manager
execute_manager(settings)
| Python |
'''
Django middleware for HTTP authentication.
Copyright (c) 2007, Accense Technology, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Accense Technology nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth import authenticate
from django.http import HttpResponse
import base64
import logging
# Written by sgk.
# This code depends on the implementation internals of the Django builtin
# 'django.contrib.auth.middleware.AuthenticationMiddleware' authentication
# middleware, specifically the 'request._cached_user' member.
class ByHttpServerMiddleware(object):
'''
Reflect the authentication result by HTTP server which hosts Django.
This middleware must be placed in the 'settings.py' MIDDLEWARE_CLASSES
definition before the above Django builtin 'AuthenticationMiddleware'.
You can use the ordinaly '@login_required' decorator to restrict views
to authenticated users. Set the 'settings.py' LOGIN_URL definition
appropriately if required.
'''
def process_request(self, request):
if hasattr(request, '_cached_user'):
return None
try:
username = request.META['REMOTE_USER']
user = User.objects.get(username=username)
except (KeyError, User.DoesNotExist):
# Fallback to other authentication middleware.
return None
request._cached_user = user
return None
class Middleware(object):
'''
Django implementation of the HTTP basic authentication.
This middleware must be placed in the 'settings.py' MIDDLEWARE_CLASSES
definition before the above Django builtin 'AuthenticationMiddleware'.
Set the 'settings.py' LOGIN_URL definition appropriately if required.
To show the browser generated login dialog to user, you have to use the
following '@http_login_required(realm=realm)' decorator instead of the
ordinaly '@login_required' decorator.
'''
def process_request(self, request):
if hasattr(request, '_cached_user'):
return None
try:
(method, encoded) = request.META['HTTP_AUTHORIZATION'].split()
if method.lower() != 'basic':
return None
(username, password) = base64.b64decode(encoded).split(':')
user =authenticate( username=username, password=password)
except (KeyError, TypeError):
# Fallback to other authentication middleware.
return None
request._cached_user = user
return None
def http_login_required(realm=None):
'''
Decorator factory to restrict views to authenticated user and show the
browser generated login dialog if the user is not authenticated.
This is the function that returns a decorator. To use the decorator,
use '@http_login_required()' or '@http_login_required(realm='...')'.
'''
def decorator(func):
def handler(request, *args, **kw):
if request.user.is_authenticated():
return func(request, *args, **kw)
response = HttpResponse(status=401)
response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm or 'Django')
return response
return handler
return decorator
| Python |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
from django.template import Context, RequestContext, loader
from django.views.generic.list_detail import object_list
from django.views.generic.simple import direct_to_template
from django.forms.formsets import formset_factory
from haco.models import *
from httpauth import *
from haco.jsTime import *
from haco.convert import *
import logging
import time
@login_required
def repo_all( request):
u = User.all()
u = u.filter( 'username', request.user.username)
u = u.filter( 'is_superuser', True)
if u.count() == 0:
return HttpResponse("you don't have the right to access this page")
else:
logging.info("repo_all")
if request.GET.has_key( 'delta'):
day = someday(int(request.GET['delta']))
else:
day = today()
q = HacoUser.all()
mes = "<html><head></head><body>"
for hacoUser in q:
user = hacoUser.user
mes += str(hacoUser.user.username)
mes +="<div>"
t_list = [-1.0] * 144
l_list = [-1.0] * 144
w_list = [-1.0] * 144
q =Haco.all()
q =q.order( 'pnum')
q =q.filter( 'user', user)
q =q.filter( 'date', day)
q =q.order( 'pnum')
for h in q:
t_list[h.pnum] = h.temp
l_list[h.pnum] = h.light
w_list[h.pnum] = h.watt
mes += t_chart(t_list)
mes += l_chart(l_list)
mes += w_chart(w_list)
mes +="</div>"
mes +="</body></html>"
return HttpResponse( mes)
def t_chart( a_list):
chart = "<img src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chco=00b379&chxt=y&chxr=0,0,40&chds=0,40&chd=t:"
for data in a_list:
chart += str(data) +","
chart = chart[0:len(chart)-1]
chart += "&chtt=temperature&chg=4.17,25,1,4&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'>"
return chart
def l_chart( a_list):
chart = "<img src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chxt =y&chxr=0,0,700&chds=0,700&chd=t:"
for data in a_list:
chart += str(data) +","
chart = chart[0:len(chart)-1]
chart += "&cht=lc&chtt=light&chg=4.17,14.3,1,2&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'>"
return chart
def w_chart( a_list):
chart = "<img src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chco=009CD1&chxt=y&chxr=0,0,1000&chds=0,1000&chd=t:"
for data in a_list:
chart += str(data) +","
chart = chart[0:len(chart)-1]
chart += "&cht=lc&chtt=watt&chg=4.17,20.00,1,2&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'>"
return chart
| Python |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext import db
from django.contrib.auth.models import User
#from datetime import *
import datetime
class HacoUser( db.Model):
user =db.ReferenceProperty( User)
zip =db.StringProperty()
twitterID =db.StringProperty()
address =db.StringProperty()
geoPt =db.GeoPtProperty()
class Haco( db.Model):
user =db.ReferenceProperty( User)
username =db.StringProperty( str(User))
pnum =db.IntegerProperty()
temp =db.FloatProperty()
light =db.FloatProperty()
watt =db.FloatProperty()
date =db.DateTimeProperty()
timestamp = db.DateTimeProperty()
class Mention( db.Model):
postUser =db.StringProperty()
postText =db.StringProperty()
postDate =db.DateTimeProperty()
| Python |
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.core.files.uploadedfile import UploadedFile
from django.utils.translation import ugettext_lazy as _, ugettext as __
from myapp.models import Person, File, Contract
from ragendja.auth.models import UserTraits
from ragendja.forms import FormWithSets, FormSetField
from registration.forms import RegistrationForm, RegistrationFormUniqueEmail
from registration.models import RegistrationProfile
from hashlib import sha1
from haco.models import HacoUser
class UserRegistrationForm(forms.ModelForm):
username =forms.RegexField(regex=r'^\w+$', max_length=30,
label=_(u'Username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),
label=_(u'Email address'))
twitterID =forms.RegexField(regex=r'^\w+$', max_length=30,
label=_(u'TwitterID'))
zip =forms.RegexField(regex=r'^[0-9]+$', max_length=30,
label=_(u'Zip'))
password1 = forms.CharField(widget=forms.PasswordInput(render_value=False),
label=_(u'Password'))
password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
label=_(u'Password (again)'))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
if user and user.is_active:
raise forms.ValidationError(__(u'This username is already taken. Please choose another.'))
return self.cleaned_data['username']
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(__(u'You must type the same password each time'))
return self.cleaned_data
def save(self, domain_override="", user=""):
"""
Create the new ``User`` and ``RegistrationProfile``, and
returns the ``User``.
This is essentially a light wrapper around
``RegistrationProfile.objects.create_inactive_user()``,
feeding it the form data and a profile callback (see the
documentation on ``create_inactive_user()`` for details) if
supplied.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'],
domain_override=domain_override,
send_email=False)
self.instance = new_user
if super(UserRegistrationForm, self).save():
haco_users =HacoUser.all().filter( 'user =', self.instance)
if haco_users.count() ==0:
haco_user =HacoUser()
haco_user.user =new_user
haco_user.zip =self.cleaned_data['twitterID']
haco_user.zip =self.cleaned_data['zip']
haco_user.put()
else:
for haco_user in haco_users:
haco_user.zip =self.cleaned_data['twitterID']
haco_user.zip =self.cleaned_data['zip']
haco_user.put()
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
email = self.cleaned_data['email'].lower()
if User.all().filter('email =', email).filter(
'is_active =', True).count(1):
raise forms.ValidationError(__(u'This email address is already in use. Please supply a different email address.'))
return email
class Meta:
model =User
exclude = UserTraits.properties().keys()
class UserConfigForm(forms.Form):
twitterID =forms.RegexField(regex=r'^\w+$', max_length=30,
label=_(u'TwitterID'))
zip = forms.RegexField(required=True, regex=r'^[0-9]+$',
max_length=7,label=_(u'Zip'))
def save(self, key=""):
q =HacoUser.all()
q =q.filter( 'user',key)
for hacoUser in q:
ID = hacoUser.key().id()
hacouser = HacoUser.get_by_id(ID)
hacouser.user = key
hacouser.zip = self.cleaned_data['zip']
hacouser.twitterID = self.cleaned_data['twitterID']
hacouser.put()
class QueryForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$', max_length=30)
delta = forms.RegexField(regex=r'^-[0-9]+$', max_length=3)
pnum = forms.RegexField(regex=r'^[0-9]+$', max_length=3)
##class UserConfigurationForm(forms.Form):
##
## email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),
## label=_(u'Email address'))
##
## first_name = forms.RegexField(regex=r'^\w+$', max_length=30,
## label=_(u'First name'))
##
## last_name = forms.RegexField(regex=r'^\w+$', max_length=30,
## label=_(u'Last name'))
##
## twitterID =forms.RegexField(regex=r'^\w+$', max_length=30,
## label=_(u'TwitterID'))
##
## zip =forms.RegexField(regex=r'^[0-9]+$', max_length=30,
## label=_(u'zip'))
##
## password1 = forms.CharField(widget=forms.PasswordInput(render_value=False),
## label=_(u'Password'))
##
## password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
## label=_(u'Password (again)'))
##
## def clean(self):
## return self.cleaned_data
##
## def save(self, key=""):
##
## auth_user = User.get( key)
##
##
## q =HacoUser.all()
## q =q.filter( 'user',key)
## for hacoUser in q:
## ID = hacoUser.key().id()
##
## user = User.get(key)
## user.email = self.cleaned_data['zip']
## user.first_name = self.cleaned_data['first_name']
## user.last_name = self.cleaned_data['last_name']
## user.password = sha1(self.cleaned_data['password1']).hexdigest()
## user.put()
##
##
##
## hacouser = HacoUser.get_by_id(ID)
## hacouser.user = key
## hacouser.zip = self.cleaned_data['zip']
## hacouser.twitterID = self.cleaned_data['twitterID']
## hacouser.put()
##
##
class FileForm(forms.ModelForm):
name = forms.CharField(required=False, label='Name (set automatically)')
def clean(self):
file = self.cleaned_data.get('file')
if not self.cleaned_data.get('name'):
if isinstance(file, UploadedFile):
self.cleaned_data['name'] = file.name
else:
del self.cleaned_data['name']
return self.cleaned_data
class Meta:
model = File
#class PersonForm(forms.ModelForm):
# files = FormSetField(File, form=FileForm, exclude='content_type')
# employers = FormSetField(Contract, fk_name='employee')
# employees = FormSetField(Contract, fk_name='employer')
#
# class Meta:
# model = Person
#PersonForm = FormWithSets(PersonForm)
| Python |
#!/usr/bin/python
"""
NOTE: Tango is being renamed to Twython; all basic strings have been changed below, but there's still work ongoing in this department.
Twython is an up-to-date library for Python that wraps the Twitter API.
Other Python Twitter libraries seem to have fallen a bit behind, and
Twitter's API has evolved a bit. Here's hoping this helps.
TODO: OAuth, Streaming API?
Questions, comments? ryan@venodesigns.net
"""
import httplib, urllib, urllib2, mimetypes, mimetools
from urllib2 import HTTPError
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
__version__ = "0.8.0.1"
"""Twython - Easy Twitter utilities in Python"""
try:
import simplejson
except ImportError:
try:
import json as simplejson
except:
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
try:
import oauth
except ImportError:
pass
class TangoError(Exception):
def __init__(self, msg, error_code=None):
self.msg = msg
if error_code == 400:
raise APILimit(msg)
def __str__(self):
return repr(self.msg)
class APILimit(TangoError):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class setup:
def __init__(self, authtype = "OAuth", username = None, password = None, oauth_keys = None, headers = None):
self.authtype = authtype
self.authenticated = False
self.username = username
self.password = password
self.oauth_keys = oauth_keys
if self.username is not None and self.password is not None:
if self.authtype == "OAuth":
self.request_token_url = 'https://twitter.com/oauth/request_token'
self.access_token_url = 'https://twitter.com/oauth/access_token'
self.authorization_url = 'http://twitter.com/oauth/authorize'
self.signin_url = 'http://twitter.com/oauth/authenticate'
# Do OAuth type stuff here - how should this be handled? Seems like a framework question...
elif self.authtype == "Basic":
self.auth_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
self.auth_manager.add_password(None, "http://twitter.com", self.username, self.password)
self.handler = urllib2.HTTPBasicAuthHandler(self.auth_manager)
self.opener = urllib2.build_opener(self.handler)
if headers is not None:
self.opener.addheaders = [('User-agent', headers)]
try:
simplejson.load(self.opener.open("http://twitter.com/account/verify_credentials.json"))
self.authenticated = True
except HTTPError, e:
raise TangoError("Authentication failed with your provided credentials. Try again? (%s failure)" % `e.code`, e.code)
# OAuth functions; shortcuts for verifying the credentials.
def fetch_response_oauth(self, oauth_request):
pass
def get_unauthorized_request_token(self):
pass
def get_authorization_url(self, token):
pass
def exchange_tokens(self, request_token):
pass
# URL Shortening function huzzah
def shortenURL(self, url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"):
try:
return urllib2.urlopen(shortener + "?" + urllib.urlencode({query: url_to_shorten})).read()
except HTTPError, e:
raise TangoError("shortenURL() failed with a %s error code." % `e.code`)
def constructApiURL(self, base_url, params):
return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.iteritems()])
def getRateLimitStatus(self, rate_for = "requestingIP"):
try:
if rate_for == "requestingIP":
return simplejson.load(urllib2.urlopen("http://twitter.com/account/rate_limit_status.json"))
else:
if self.authenticated is True:
return simplejson.load(self.opener.open("http://twitter.com/account/rate_limit_status.json"))
else:
raise TangoError("You need to be authenticated to check a rate limit status on an account.")
except HTTPError, e:
raise TangoError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % `e.code`, e.code)
def getPublicTimeline(self):
try:
return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/public_timeline.json"))
except HTTPError, e:
raise TangoError("getPublicTimeline() failed with a %s error code." % `e.code`)
def getFriendsTimeline(self, **kwargs):
if self.authenticated is True:
try:
friendsTimelineURL = self.constructApiURL("http://twitter.com/statuses/friends_timeline.json", kwargs)
return simplejson.load(self.opener.open(friendsTimelineURL))
except HTTPError, e:
raise TangoError("getFriendsTimeline() failed with a %s error code." % `e.code`)
else:
raise TangoError("getFriendsTimeline() requires you to be authenticated.")
def getUserTimeline(self, id = None, **kwargs):
if id is not None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False:
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + id + ".json", kwargs)
elif id is None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False and self.authenticated is True:
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + self.username + ".json", kwargs)
else:
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline.json", kwargs)
try:
# We do our custom opener if we're authenticated, as it helps avoid cases where it's a protected user
if self.authenticated is True:
return simplejson.load(self.opener.open(userTimelineURL))
else:
return simplejson.load(urllib2.urlopen(userTimelineURL))
except HTTPError, e:
raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline."
% `e.code`, e.code)
def getUserMentions(self, **kwargs):
if self.authenticated is True:
try:
mentionsFeedURL = self.constructApiURL("http://twitter.com/statuses/mentions.json", kwargs)
return simplejson.load(self.opener.open(mentionsFeedURL))
except HTTPError, e:
raise TangoError("getUserMentions() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getUserMentions() requires you to be authenticated.")
def showStatus(self, id):
try:
if self.authenticated is True:
return simplejson.load(self.opener.open("http://twitter.com/statuses/show/%s.json" % id))
else:
return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/show/%s.json" % id))
except HTTPError, e:
raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline."
% `e.code`, e.code)
def updateStatus(self, status, in_reply_to_status_id = None):
if self.authenticated is True:
if len(list(status)) > 140:
raise TangoError("This status message is over 140 characters. Trim it down!")
try:
return simplejson.load(self.opener.open("http://twitter.com/statuses/update.json?", urllib.urlencode({"status": status, "in_reply_to_status_id": in_reply_to_status_id})))
except HTTPError, e:
raise TangoError("updateStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateStatus() requires you to be authenticated.")
def destroyStatus(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/status/destroy/%s.json", "POST" % id))
except HTTPError, e:
raise TangoError("destroyStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyStatus() requires you to be authenticated.")
def endSession(self):
if self.authenticated is True:
try:
self.opener.open("http://twitter.com/account/end_session.json", "")
self.authenticated = False
except HTTPError, e:
raise TangoError("endSession failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You can't end a session when you're not authenticated to begin with.")
def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1"):
if self.authenticated is True:
apiURL = "http://twitter.com/direct_messages.json?page=" + page
if since_id is not None:
apiURL += "&since_id=" + since_id
if max_id is not None:
apiURL += "&max_id=" + max_id
if count is not None:
apiURL += "&count=" + count
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TangoError("getDirectMessages() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getDirectMessages() requires you to be authenticated.")
def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1"):
if self.authenticated is True:
apiURL = "http://twitter.com/direct_messages/sent.json?page=" + page
if since_id is not None:
apiURL += "&since_id=" + since_id
if max_id is not None:
apiURL += "&max_id=" + max_id
if count is not None:
apiURL += "&count=" + count
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TangoError("getSentMessages() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getSentMessages() requires you to be authenticated.")
def sendDirectMessage(self, user, text):
if self.authenticated is True:
if len(list(text)) < 140:
try:
return self.opener.open("http://twitter.com/direct_messages/new.json", urllib.urlencode({"user": user, "text": text}))
except HTTPError, e:
raise TangoError("sendDirectMessage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("Your message must not be longer than 140 characters")
else:
raise TangoError("You must be authenticated to send a new direct message.")
def destroyDirectMessage(self, id):
if self.authenticated is True:
try:
return self.opener.open("http://twitter.com/direct_messages/destroy/%s.json" % id, "")
except HTTPError, e:
raise TangoError("destroyDirectMessage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You must be authenticated to destroy a direct message.")
def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false"):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/friendships/create/" + id + ".json" + "?follow=" + follow
if user_id is not None:
apiURL = "http://twitter.com/friendships/create.json?user_id=" + user_id + "&follow=" + follow
if screen_name is not None:
apiURL = "http://twitter.com/friendships/create.json?screen_name=" + screen_name + "&follow=" + follow
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
# Rate limiting is done differently here for API reasons...
if e.code == 403:
raise TangoError("You've hit the update limit for this method. Try again in 24 hours.")
raise TangoError("createFriendship() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createFriendship() requires you to be authenticated.")
def destroyFriendship(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/friendships/destroy/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/friendships/destroy.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/friendships/destroy.json?screen_name=" + screen_name
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TangoError("destroyFriendship() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyFriendship() requires you to be authenticated.")
def checkIfFriendshipExists(self, user_a, user_b):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/friendships/exists.json", urllib.urlencode({"user_a": user_a, "user_b": user_b})))
except HTTPError, e:
raise TangoError("checkIfFriendshipExists() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("checkIfFriendshipExists(), oddly, requires that you be authenticated.")
def updateDeliveryDevice(self, device_name = "none"):
if self.authenticated is True:
try:
return self.opener.open("http://twitter.com/account/update_delivery_device.json?", urllib.urlencode({"device": device_name}))
except HTTPError, e:
raise TangoError("updateDeliveryDevice() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateDeliveryDevice() requires you to be authenticated.")
def updateProfileColors(self, **kwargs):
if self.authenticated is True:
try:
return self.opener.open(self.constructApiURL("http://twitter.com/account/update_profile_colors.json?", kwargs))
except HTTPError, e:
raise TangoError("updateProfileColors() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateProfileColors() requires you to be authenticated.")
def updateProfile(self, name = None, email = None, url = None, location = None, description = None):
if self.authenticated is True:
useAmpersands = False
updateProfileQueryString = ""
if name is not None:
if len(list(name)) < 20:
updateProfileQueryString += "name=" + name
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 20 for all usernames. Try again.")
if email is not None and "@" in email:
if len(list(email)) < 40:
if useAmpersands is True:
updateProfileQueryString += "&email=" + email
else:
updateProfileQueryString += "email=" + email
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.")
if url is not None:
if len(list(url)) < 100:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"url": url})
else:
updateProfileQueryString += urllib.urlencode({"url": url})
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 100 for all urls. Try again.")
if location is not None:
if len(list(location)) < 30:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"location": location})
else:
updateProfileQueryString += urllib.urlencode({"location": location})
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 30 for all locations. Try again.")
if description is not None:
if len(list(description)) < 160:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"description": description})
else:
updateProfileQueryString += urllib.urlencode({"description": description})
else:
raise TangoError("Twitter has a character limit of 160 for all descriptions. Try again.")
if updateProfileQueryString != "":
try:
return self.opener.open("http://twitter.com/account/update_profile.json?", updateProfileQueryString)
except HTTPError, e:
raise TangoError("updateProfile() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateProfile() requires you to be authenticated.")
def getFavorites(self, page = "1"):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/favorites.json?page=" + page))
except HTTPError, e:
raise TangoError("getFavorites() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getFavorites() requires you to be authenticated.")
def createFavorite(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/favorites/create/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("createFavorite() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createFavorite() requires you to be authenticated.")
def destroyFavorite(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/favorites/destroy/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("destroyFavorite() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyFavorite() requires you to be authenticated.")
def notificationFollow(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/notifications/follow/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/notifications/follow/follow.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/notifications/follow/follow.json?screen_name=" + screen_name
try:
return simplejson.load(self.opener.open(apiURL, ""))
except HTTPError, e:
raise TangoError("notificationFollow() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("notificationFollow() requires you to be authenticated.")
def notificationLeave(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/notifications/leave/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/notifications/leave/leave.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/notifications/leave/leave.json?screen_name=" + screen_name
try:
return simplejson.load(self.opener.open(apiURL, ""))
except HTTPError, e:
raise TangoError("notificationLeave() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("notificationLeave() requires you to be authenticated.")
def getFriendsIDs(self, id = None, user_id = None, screen_name = None, page = "1"):
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/friends/ids/" + id + ".json" + "?page=" + page
if user_id is not None:
apiURL = "http://twitter.com/friends/ids.json?user_id=" + user_id + "&page=" + page
if screen_name is not None:
apiURL = "http://twitter.com/friends/ids.json?screen_name=" + screen_name + "&page=" + page
try:
return simplejson.load(urllib2.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getFriendsIDs() failed with a %s error code." % `e.code`, e.code)
def getFollowersIDs(self, id = None, user_id = None, screen_name = None, page = "1"):
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/followers/ids/" + id + ".json" + "?page=" + page
if user_id is not None:
apiURL = "http://twitter.com/followers/ids.json?user_id=" + user_id + "&page=" + page
if screen_name is not None:
apiURL = "http://twitter.com/followers/ids.json?screen_name=" + screen_name + "&page=" + page
try:
return simplejson.load(urllib2.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getFollowersIDs() failed with a %s error code." % `e.code`, e.code)
def createBlock(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/create/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("createBlock() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createBlock() requires you to be authenticated.")
def destroyBlock(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/destroy/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("destroyBlock() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyBlock() requires you to be authenticated.")
def checkIfBlockExists(self, id = None, user_id = None, screen_name = None):
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/blocks/exists/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/blocks/exists.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/blocks/exists.json?screen_name=" + screen_name
try:
return simplejson.load(urllib2.urlopen(apiURL))
except HTTPError, e:
raise TangoError("checkIfBlockExists() failed with a %s error code." % `e.code`, e.code)
def getBlocking(self, page = "1"):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking.json?page=" + page))
except HTTPError, e:
raise TangoError("getBlocking() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getBlocking() requires you to be authenticated")
def getBlockedIDs(self):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking/ids.json"))
except HTTPError, e:
raise TangoError("getBlockedIDs() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getBlockedIDs() requires you to be authenticated.")
def searchTwitter(self, search_query, **kwargs):
searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.urlencode({"q": search_query})
try:
return simplejson.load(urllib2.urlopen(searchURL))
except HTTPError, e:
raise TangoError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code)
def getCurrentTrends(self, excludeHashTags = False):
apiURL = "http://search.twitter.com/trends/current.json"
if excludeHashTags is True:
apiURL += "?exclude=hashtags"
try:
return simplejson.load(urllib.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getCurrentTrends() failed with a %s error code." % `e.code`, e.code)
def getDailyTrends(self, date = None, exclude = False):
apiURL = "http://search.twitter.com/trends/daily.json"
questionMarkUsed = False
if date is not None:
apiURL += "?date=" + date
questionMarkUsed = True
if exclude is True:
if questionMarkUsed is True:
apiURL += "&exclude=hashtags"
else:
apiURL += "?exclude=hashtags"
try:
return simplejson.load(urllib.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getDailyTrends() failed with a %s error code." % `e.code`, e.code)
def getWeeklyTrends(self, date = None, exclude = False):
apiURL = "http://search.twitter.com/trends/daily.json"
questionMarkUsed = False
if date is not None:
apiURL += "?date=" + date
questionMarkUsed = True
if exclude is True:
if questionMarkUsed is True:
apiURL += "&exclude=hashtags"
else:
apiURL += "?exclude=hashtags"
try:
return simplejson.load(urllib.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getWeeklyTrends() failed with a %s error code." % `e.code`, e.code)
def getSavedSearches(self):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches.json"))
except HTTPError, e:
raise TangoError("getSavedSearches() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getSavedSearches() requires you to be authenticated.")
def showSavedSearch(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/show/" + id + ".json"))
except HTTPError, e:
raise TangoError("showSavedSearch() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("showSavedSearch() requires you to be authenticated.")
def createSavedSearch(self, query):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/create.json?query=" + query, ""))
except HTTPError, e:
raise TangoError("createSavedSearch() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createSavedSearch() requires you to be authenticated.")
def destroySavedSearch(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/destroy/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("destroySavedSearch() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroySavedSearch() requires you to be authenticated.")
# The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set.
def updateProfileBackgroundImage(self, filename, tile="true"):
if self.authenticated is True:
try:
files = [("image", filename, open(filename).read())]
fields = []
content_type, body = self.encode_multipart_formdata(fields, files)
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
r = urllib2.Request("http://twitter.com/account/update_profile_background_image.json?tile=" + tile, body, headers)
return self.opener.open(r).read()
except HTTPError, e:
raise TangoError("updateProfileBackgroundImage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You realize you need to be authenticated to change a background image, right?")
def updateProfileImage(self, filename):
if self.authenticated is True:
try:
files = [("image", filename, open(filename).read())]
fields = []
content_type, body = self.encode_multipart_formdata(fields, files)
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
r = urllib2.Request("http://twitter.com/account/update_profile_image.json", body, headers)
return self.opener.open(r).read()
except HTTPError, e:
raise TangoError("updateProfileImage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You realize you need to be authenticated to change a profile image, right?")
def encode_multipart_formdata(self, fields, files):
BOUNDARY = mimetools.choose_boundary()
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % self.get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def get_content_type(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
| Python |
#!/usr/bin/python2.4
#
# Copyright 2007 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''A library that provides a python interface to the Twitter API'''
__author__ = 'dewitt@google.com'
__version__ = '0.6-devel'
import base64
import calendar
import os
import rfc822
import simplejson
import sys
import tempfile
import textwrap
import time
import urllib
import urllib2
import urlparse
try:
from hashlib import md5
except ImportError:
from md5 import md5
CHARACTER_LIMIT = 140
class TwitterError(Exception):
'''Base class for Twitter errors'''
@property
def message(self):
'''Returns the first argument used to construct this error.'''
return self.args[0]
class Status(object):
'''A class representing the Status structure used by the twitter API.
The Status structure exposes the following properties:
status.created_at
status.created_at_in_seconds # read only
status.favorited
status.in_reply_to_screen_name
status.in_reply_to_user_id
status.in_reply_to_status_id
status.truncated
status.source
status.id
status.text
status.relative_created_at # read only
status.user
'''
def __init__(self,
created_at=None,
favorited=None,
id=None,
text=None,
user=None,
in_reply_to_screen_name=None,
in_reply_to_user_id=None,
in_reply_to_status_id=None,
truncated=None,
source=None,
now=None):
'''An object to hold a Twitter status message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
created_at: The time this status message was posted
favorited: Whether this is a favorite of the authenticated user
id: The unique id of this status message
text: The text of this status message
relative_created_at:
A human readable string representing the posting time
user:
A twitter.User instance representing the person posting the message
now:
The current time, if the client choses to set it. Defaults to the
wall clock time.
'''
self.created_at = created_at
self.favorited = favorited
self.id = id
self.text = text
self.user = user
self.now = now
self.in_reply_to_screen_name = in_reply_to_screen_name
self.in_reply_to_user_id = in_reply_to_user_id
self.in_reply_to_status_id = in_reply_to_status_id
self.truncated = truncated
self.source = source
def GetCreatedAt(self):
'''Get the time this status message was posted.
Returns:
The time this status message was posted
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set the time this status message was posted.
Args:
created_at: The time this status message was created
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The time this status message was posted.')
def GetCreatedAtInSeconds(self):
'''Get the time this status message was posted, in seconds since the epoch.
Returns:
The time this status message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
created_at_in_seconds = property(GetCreatedAtInSeconds,
doc="The time this status message was "
"posted, in seconds since the epoch")
def GetFavorited(self):
'''Get the favorited setting of this status message.
Returns:
True if this status message is favorited; False otherwise
'''
return self._favorited
def SetFavorited(self, favorited):
'''Set the favorited state of this status message.
Args:
favorited: boolean True/False favorited state of this status message
'''
self._favorited = favorited
favorited = property(GetFavorited, SetFavorited,
doc='The favorited state of this status message.')
def GetId(self):
'''Get the unique id of this status message.
Returns:
The unique id of this status message
'''
return self._id
def SetId(self, id):
'''Set the unique id of this status message.
Args:
id: The unique id of this status message
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this status message.')
def GetInReplyToScreenName(self):
return self._in_reply_to_screen_name
def SetInReplyToScreenName(self, in_reply_to_screen_name):
self._in_reply_to_screen_name = in_reply_to_screen_name
in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName,
doc='')
def GetInReplyToUserId(self):
return self._in_reply_to_user_id
def SetInReplyToUserId(self, in_reply_to_user_id):
self._in_reply_to_user_id = in_reply_to_user_id
in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId,
doc='')
def GetInReplyToStatusId(self):
return self._in_reply_to_status_id
def SetInReplyToStatusId(self, in_reply_to_status_id):
self._in_reply_to_status_id = in_reply_to_status_id
in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId,
doc='')
def GetTruncated(self):
return self._truncated
def SetTruncated(self, truncated):
self._truncated = truncated
truncated = property(GetTruncated, SetTruncated,
doc='')
def GetSource(self):
return self._source
def SetSource(self, source):
self._source = source
source = property(GetSource, SetSource,
doc='')
def GetText(self):
'''Get the text of this status message.
Returns:
The text of this status message.
'''
return self._text
def SetText(self, text):
'''Set the text of this status message.
Args:
text: The text of this status message
'''
self._text = text
text = property(GetText, SetText,
doc='The text of this status message')
def GetRelativeCreatedAt(self):
'''Get a human redable string representing the posting time
Returns:
A human readable string representing the posting time
'''
fudge = 1.25
delta = long(self.now) - long(self.created_at_in_seconds)
if delta < (1 * fudge):
return 'about a second ago'
elif delta < (60 * (1/fudge)):
return 'about %d seconds ago' % (delta)
elif delta < (60 * fudge):
return 'about a minute ago'
elif delta < (60 * 60 * (1/fudge)):
return 'about %d minutes ago' % (delta / 60)
elif delta < (60 * 60 * fudge):
return 'about an hour ago'
elif delta < (60 * 60 * 24 * (1/fudge)):
return 'about %d hours ago' % (delta / (60 * 60))
elif delta < (60 * 60 * 24 * fudge):
return 'about a day ago'
else:
return 'about %d days ago' % (delta / (60 * 60 * 24))
relative_created_at = property(GetRelativeCreatedAt,
doc='Get a human readable string representing'
'the posting time')
def GetUser(self):
'''Get a twitter.User reprenting the entity posting this status message.
Returns:
A twitter.User reprenting the entity posting this status message
'''
return self._user
def SetUser(self, user):
'''Set a twitter.User reprenting the entity posting this status message.
Args:
user: A twitter.User reprenting the entity posting this status message
'''
self._user = user
user = property(GetUser, SetUser,
doc='A twitter.User reprenting the entity posting this '
'status message')
def GetNow(self):
'''Get the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Returns:
Whatever the status instance believes the current time to be,
in seconds since the epoch.
'''
if self._now is None:
self._now = time.time()
return self._now
def SetNow(self, now):
'''Set the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Args:
now: The wallclock time for this instance.
'''
self._now = now
now = property(GetNow, SetNow,
doc='The wallclock time for this status instance.')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.created_at == other.created_at and \
self.id == other.id and \
self.text == other.text and \
self.user == other.user and \
self.in_reply_to_screen_name == other.in_reply_to_screen_name and \
self.in_reply_to_user_id == other.in_reply_to_user_id and \
self.in_reply_to_status_id == other.in_reply_to_status_id and \
self.truncated == other.truncated and \
self.favorited == other.favorited and \
self.source == other.source
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.Status instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.Status instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.Status instance.
Returns:
A JSON string representation of this twitter.Status instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.Status instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.Status instance
'''
data = {}
if self.created_at:
data['created_at'] = self.created_at
if self.favorited:
data['favorited'] = self.favorited
if self.id:
data['id'] = self.id
if self.text:
data['text'] = self.text
if self.user:
data['user'] = self.user.AsDict()
if self.in_reply_to_screen_name:
data['in_reply_to_screen_name'] = self.in_reply_to_screen_name
if self.in_reply_to_user_id:
data['in_reply_to_user_id'] = self.in_reply_to_user_id
if self.in_reply_to_status_id:
data['in_reply_to_status_id'] = self.in_reply_to_status_id
if self.truncated is not None:
data['truncated'] = self.truncated
if self.favorited is not None:
data['favorited'] = self.favorited
if self.source:
data['source'] = self.source
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Status instance
'''
if 'user' in data:
user = User.NewFromJsonDict(data['user'])
else:
user = None
return Status(created_at=data.get('created_at', None),
favorited=data.get('favorited', None),
id=data.get('id', None),
text=data.get('text', None),
in_reply_to_screen_name=data.get('in_reply_to_screen_name', None),
in_reply_to_user_id=data.get('in_reply_to_user_id', None),
in_reply_to_status_id=data.get('in_reply_to_status_id', None),
truncated=data.get('truncated', None),
source=data.get('source', None),
user=user)
class User(object):
'''A class representing the User structure used by the twitter API.
The User structure exposes the following properties:
user.id
user.name
user.screen_name
user.location
user.description
user.profile_image_url
user.profile_background_tile
user.profile_background_image_url
user.profile_sidebar_fill_color
user.profile_background_color
user.profile_link_color
user.profile_text_color
user.protected
user.utc_offset
user.time_zone
user.url
user.status
user.statuses_count
user.followers_count
user.friends_count
user.favourites_count
'''
def __init__(self,
id=None,
name=None,
screen_name=None,
location=None,
description=None,
profile_image_url=None,
profile_background_tile=None,
profile_background_image_url=None,
profile_sidebar_fill_color=None,
profile_background_color=None,
profile_link_color=None,
profile_text_color=None,
protected=None,
utc_offset=None,
time_zone=None,
followers_count=None,
friends_count=None,
statuses_count=None,
favourites_count=None,
url=None,
status=None):
self.id = id
self.name = name
self.screen_name = screen_name
self.location = location
self.description = description
self.profile_image_url = profile_image_url
self.profile_background_tile = profile_background_tile
self.profile_background_image_url = profile_background_image_url
self.profile_sidebar_fill_color = profile_sidebar_fill_color
self.profile_background_color = profile_background_color
self.profile_link_color = profile_link_color
self.profile_text_color = profile_text_color
self.protected = protected
self.utc_offset = utc_offset
self.time_zone = time_zone
self.followers_count = followers_count
self.friends_count = friends_count
self.statuses_count = statuses_count
self.favourites_count = favourites_count
self.url = url
self.status = status
def GetId(self):
'''Get the unique id of this user.
Returns:
The unique id of this user
'''
return self._id
def SetId(self, id):
'''Set the unique id of this user.
Args:
id: The unique id of this user.
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this user.')
def GetName(self):
'''Get the real name of this user.
Returns:
The real name of this user
'''
return self._name
def SetName(self, name):
'''Set the real name of this user.
Args:
name: The real name of this user
'''
self._name = name
name = property(GetName, SetName,
doc='The real name of this user.')
def GetScreenName(self):
'''Get the short username of this user.
Returns:
The short username of this user
'''
return self._screen_name
def SetScreenName(self, screen_name):
'''Set the short username of this user.
Args:
screen_name: the short username of this user
'''
self._screen_name = screen_name
screen_name = property(GetScreenName, SetScreenName,
doc='The short username of this user.')
def GetLocation(self):
'''Get the geographic location of this user.
Returns:
The geographic location of this user
'''
return self._location
def SetLocation(self, location):
'''Set the geographic location of this user.
Args:
location: The geographic location of this user
'''
self._location = location
location = property(GetLocation, SetLocation,
doc='The geographic location of this user.')
def GetDescription(self):
'''Get the short text description of this user.
Returns:
The short text description of this user
'''
return self._description
def SetDescription(self, description):
'''Set the short text description of this user.
Args:
description: The short text description of this user
'''
self._description = description
description = property(GetDescription, SetDescription,
doc='The short text description of this user.')
def GetUrl(self):
'''Get the homepage url of this user.
Returns:
The homepage url of this user
'''
return self._url
def SetUrl(self, url):
'''Set the homepage url of this user.
Args:
url: The homepage url of this user
'''
self._url = url
url = property(GetUrl, SetUrl,
doc='The homepage url of this user.')
def GetProfileImageUrl(self):
'''Get the url of the thumbnail of this user.
Returns:
The url of the thumbnail of this user
'''
return self._profile_image_url
def SetProfileImageUrl(self, profile_image_url):
'''Set the url of the thumbnail of this user.
Args:
profile_image_url: The url of the thumbnail of this user
'''
self._profile_image_url = profile_image_url
profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl,
doc='The url of the thumbnail of this user.')
def GetProfileBackgroundTile(self):
'''Boolean for whether to tile the profile background image.
Returns:
True if the background is to be tiled, False if not, None if unset.
'''
return self._profile_background_tile
def SetProfileBackgroundTile(self, profile_background_tile):
'''Set the boolean flag for whether to tile the profile background image.
Args:
profile_background_tile: Boolean flag for whether to tile or not.
'''
self._profile_background_tile = profile_background_tile
profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile,
doc='Boolean for whether to tile the background image.')
def GetProfileBackgroundImageUrl(self):
return self._profile_background_image_url
def SetProfileBackgroundImageUrl(self, profile_background_image_url):
self._profile_background_image_url = profile_background_image_url
profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl,
doc='The url of the profile background of this user.')
def GetProfileSidebarFillColor(self):
return self._profile_sidebar_fill_color
def SetProfileSidebarFillColor(self, profile_sidebar_fill_color):
self._profile_sidebar_fill_color = profile_sidebar_fill_color
profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor)
def GetProfileBackgroundColor(self):
return self._profile_background_color
def SetProfileBackgroundColor(self, profile_background_color):
self._profile_background_color = profile_background_color
profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor)
def GetProfileLinkColor(self):
return self._profile_link_color
def SetProfileLinkColor(self, profile_link_color):
self._profile_link_color = profile_link_color
profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor)
def GetProfileTextColor(self):
return self._profile_text_color
def SetProfileTextColor(self, profile_text_color):
self._profile_text_color = profile_text_color
profile_text_color = property(GetProfileTextColor, SetProfileTextColor)
def GetProtected(self):
return self._protected
def SetProtected(self, protected):
self._protected = protected
protected = property(GetProtected, SetProtected)
def GetUtcOffset(self):
return self._utc_offset
def SetUtcOffset(self, utc_offset):
self._utc_offset = utc_offset
utc_offset = property(GetUtcOffset, SetUtcOffset)
def GetTimeZone(self):
'''Returns the current time zone string for the user.
Returns:
The descriptive time zone string for the user.
'''
return self._time_zone
def SetTimeZone(self, time_zone):
'''Sets the user's time zone string.
Args:
time_zone: The descriptive time zone to assign for the user.
'''
self._time_zone = time_zone
time_zone = property(GetTimeZone, SetTimeZone)
def GetStatus(self):
'''Get the latest twitter.Status of this user.
Returns:
The latest twitter.Status of this user
'''
return self._status
def SetStatus(self, status):
'''Set the latest twitter.Status of this user.
Args:
status: The latest twitter.Status of this user
'''
self._status = status
status = property(GetStatus, SetStatus,
doc='The latest twitter.Status of this user.')
def GetFriendsCount(self):
'''Get the friend count for this user.
Returns:
The number of users this user has befriended.
'''
return self._friends_count
def SetFriendsCount(self, count):
'''Set the friend count for this user.
Args:
count: The number of users this user has befriended.
'''
self._friends_count = count
friends_count = property(GetFriendsCount, SetFriendsCount,
doc='The number of friends for this user.')
def GetFollowersCount(self):
'''Get the follower count for this user.
Returns:
The number of users following this user.
'''
return self._followers_count
def SetFollowersCount(self, count):
'''Set the follower count for this user.
Args:
count: The number of users following this user.
'''
self._followers_count = count
followers_count = property(GetFollowersCount, SetFollowersCount,
doc='The number of users following this user.')
def GetStatusesCount(self):
'''Get the number of status updates for this user.
Returns:
The number of status updates for this user.
'''
return self._statuses_count
def SetStatusesCount(self, count):
'''Set the status update count for this user.
Args:
count: The number of updates for this user.
'''
self._statuses_count = count
statuses_count = property(GetStatusesCount, SetStatusesCount,
doc='The number of updates for this user.')
def GetFavouritesCount(self):
'''Get the number of favourites for this user.
Returns:
The number of favourites for this user.
'''
return self._favourites_count
def SetFavouritesCount(self, count):
'''Set the favourite count for this user.
Args:
count: The number of favourites for this user.
'''
self._favourites_count = count
favourites_count = property(GetFavouritesCount, SetFavouritesCount,
doc='The number of favourites for this user.')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.name == other.name and \
self.screen_name == other.screen_name and \
self.location == other.location and \
self.description == other.description and \
self.profile_image_url == other.profile_image_url and \
self.profile_background_tile == other.profile_background_tile and \
self.profile_background_image_url == other.profile_background_image_url and \
self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \
self.profile_background_color == other.profile_background_color and \
self.profile_link_color == other.profile_link_color and \
self.profile_text_color == other.profile_text_color and \
self.protected == other.protected and \
self.utc_offset == other.utc_offset and \
self.time_zone == other.time_zone and \
self.url == other.url and \
self.statuses_count == other.statuses_count and \
self.followers_count == other.followers_count and \
self.favourites_count == other.favourites_count and \
self.friends_count == other.friends_count and \
self.status == other.status
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.User instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.User instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.User instance.
Returns:
A JSON string representation of this twitter.User instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.User instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.User instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.name:
data['name'] = self.name
if self.screen_name:
data['screen_name'] = self.screen_name
if self.location:
data['location'] = self.location
if self.description:
data['description'] = self.description
if self.profile_image_url:
data['profile_image_url'] = self.profile_image_url
if self.profile_background_tile is not None:
data['profile_background_tile'] = self.profile_background_tile
if self.profile_background_image_url:
data['profile_sidebar_fill_color'] = self.profile_background_image_url
if self.profile_background_color:
data['profile_background_color'] = self.profile_background_color
if self.profile_link_color:
data['profile_link_color'] = self.profile_link_color
if self.profile_text_color:
data['profile_text_color'] = self.profile_text_color
if self.protected is not None:
data['protected'] = self.protected
if self.utc_offset:
data['utc_offset'] = self.utc_offset
if self.time_zone:
data['time_zone'] = self.time_zone
if self.url:
data['url'] = self.url
if self.status:
data['status'] = self.status.AsDict()
if self.friends_count:
data['friends_count'] = self.friends_count
if self.followers_count:
data['followers_count'] = self.followers_count
if self.statuses_count:
data['statuses_count'] = self.statuses_count
if self.favourites_count:
data['favourites_count'] = self.favourites_count
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.User instance
'''
if 'status' in data:
status = Status.NewFromJsonDict(data['status'])
else:
status = None
return User(id=data.get('id', None),
name=data.get('name', None),
screen_name=data.get('screen_name', None),
location=data.get('location', None),
description=data.get('description', None),
statuses_count=data.get('statuses_count', None),
followers_count=data.get('followers_count', None),
favourites_count=data.get('favourites_count', None),
friends_count=data.get('friends_count', None),
profile_image_url=data.get('profile_image_url', None),
profile_background_tile = data.get('profile_background_tile', None),
profile_background_image_url = data.get('profile_background_image_url', None),
profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None),
profile_background_color = data.get('profile_background_color', None),
profile_link_color = data.get('profile_link_color', None),
profile_text_color = data.get('profile_text_color', None),
protected = data.get('protected', None),
utc_offset = data.get('utc_offset', None),
time_zone = data.get('time_zone', None),
url=data.get('url', None),
status=status)
class DirectMessage(object):
'''A class representing the DirectMessage structure used by the twitter API.
The DirectMessage structure exposes the following properties:
direct_message.id
direct_message.created_at
direct_message.created_at_in_seconds # read only
direct_message.sender_id
direct_message.sender_screen_name
direct_message.recipient_id
direct_message.recipient_screen_name
direct_message.text
'''
def __init__(self,
id=None,
created_at=None,
sender_id=None,
sender_screen_name=None,
recipient_id=None,
recipient_screen_name=None,
text=None):
'''An object to hold a Twitter direct message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
id: The unique id of this direct message
created_at: The time this direct message was posted
sender_id: The id of the twitter user that sent this message
sender_screen_name: The name of the twitter user that sent this message
recipient_id: The id of the twitter that received this message
recipient_screen_name: The name of the twitter that received this message
text: The text of this direct message
'''
self.id = id
self.created_at = created_at
self.sender_id = sender_id
self.sender_screen_name = sender_screen_name
self.recipient_id = recipient_id
self.recipient_screen_name = recipient_screen_name
self.text = text
def GetId(self):
'''Get the unique id of this direct message.
Returns:
The unique id of this direct message
'''
return self._id
def SetId(self, id):
'''Set the unique id of this direct message.
Args:
id: The unique id of this direct message
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this direct message.')
def GetCreatedAt(self):
'''Get the time this direct message was posted.
Returns:
The time this direct message was posted
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set the time this direct message was posted.
Args:
created_at: The time this direct message was created
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The time this direct message was posted.')
def GetCreatedAtInSeconds(self):
'''Get the time this direct message was posted, in seconds since the epoch.
Returns:
The time this direct message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
created_at_in_seconds = property(GetCreatedAtInSeconds,
doc="The time this direct message was "
"posted, in seconds since the epoch")
def GetSenderId(self):
'''Get the unique sender id of this direct message.
Returns:
The unique sender id of this direct message
'''
return self._sender_id
def SetSenderId(self, sender_id):
'''Set the unique sender id of this direct message.
Args:
sender id: The unique sender id of this direct message
'''
self._sender_id = sender_id
sender_id = property(GetSenderId, SetSenderId,
doc='The unique sender id of this direct message.')
def GetSenderScreenName(self):
'''Get the unique sender screen name of this direct message.
Returns:
The unique sender screen name of this direct message
'''
return self._sender_screen_name
def SetSenderScreenName(self, sender_screen_name):
'''Set the unique sender screen name of this direct message.
Args:
sender_screen_name: The unique sender screen name of this direct message
'''
self._sender_screen_name = sender_screen_name
sender_screen_name = property(GetSenderScreenName, SetSenderScreenName,
doc='The unique sender screen name of this direct message.')
def GetRecipientId(self):
'''Get the unique recipient id of this direct message.
Returns:
The unique recipient id of this direct message
'''
return self._recipient_id
def SetRecipientId(self, recipient_id):
'''Set the unique recipient id of this direct message.
Args:
recipient id: The unique recipient id of this direct message
'''
self._recipient_id = recipient_id
recipient_id = property(GetRecipientId, SetRecipientId,
doc='The unique recipient id of this direct message.')
def GetRecipientScreenName(self):
'''Get the unique recipient screen name of this direct message.
Returns:
The unique recipient screen name of this direct message
'''
return self._recipient_screen_name
def SetRecipientScreenName(self, recipient_screen_name):
'''Set the unique recipient screen name of this direct message.
Args:
recipient_screen_name: The unique recipient screen name of this direct message
'''
self._recipient_screen_name = recipient_screen_name
recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName,
doc='The unique recipient screen name of this direct message.')
def GetText(self):
'''Get the text of this direct message.
Returns:
The text of this direct message.
'''
return self._text
def SetText(self, text):
'''Set the text of this direct message.
Args:
text: The text of this direct message
'''
self._text = text
text = property(GetText, SetText,
doc='The text of this direct message')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.created_at == other.created_at and \
self.sender_id == other.sender_id and \
self.sender_screen_name == other.sender_screen_name and \
self.recipient_id == other.recipient_id and \
self.recipient_screen_name == other.recipient_screen_name and \
self.text == other.text
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.DirectMessage instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.DirectMessage instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.DirectMessage instance.
Returns:
A JSON string representation of this twitter.DirectMessage instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.DirectMessage instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.DirectMessage instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.created_at:
data['created_at'] = self.created_at
if self.sender_id:
data['sender_id'] = self.sender_id
if self.sender_screen_name:
data['sender_screen_name'] = self.sender_screen_name
if self.recipient_id:
data['recipient_id'] = self.recipient_id
if self.recipient_screen_name:
data['recipient_screen_name'] = self.recipient_screen_name
if self.text:
data['text'] = self.text
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.DirectMessage instance
'''
return DirectMessage(created_at=data.get('created_at', None),
recipient_id=data.get('recipient_id', None),
sender_id=data.get('sender_id', None),
text=data.get('text', None),
sender_screen_name=data.get('sender_screen_name', None),
id=data.get('id', None),
recipient_screen_name=data.get('recipient_screen_name', None))
class Api(object):
'''A python interface into the Twitter API
By default, the Api caches results for 1 minute.
Example usage:
To create an instance of the twitter.Api class, with no authentication:
>>> import twitter
>>> api = twitter.Api()
To fetch the most recently posted public twitter status messages:
>>> statuses = api.GetPublicTimeline()
>>> print [s.user.name for s in statuses]
[u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #...
To fetch a single user's public status messages, where "user" is either
a Twitter "short name" or their user id.
>>> statuses = api.GetUserTimeline(user)
>>> print [s.text for s in statuses]
To use authentication, instantiate the twitter.Api class with a
username and password:
>>> api = twitter.Api(username='twitter user', password='twitter pass')
To fetch your friends (after being authenticated):
>>> users = api.GetFriends()
>>> print [u.name for u in users]
To post a twitter status message (after being authenticated):
>>> status = api.PostUpdate('I love python-twitter!')
>>> print status.text
I love python-twitter!
There are many other methods, including:
>>> api.PostUpdates(status)
>>> api.PostDirectMessage(user, text)
>>> api.GetUser(user)
>>> api.GetReplies()
>>> api.GetUserTimeline(user)
>>> api.GetStatus(id)
>>> api.DestroyStatus(id)
>>> api.GetFriendsTimeline(user)
>>> api.GetFriends(user)
>>> api.GetFollowers()
>>> api.GetFeatured()
>>> api.GetDirectMessages()
>>> api.PostDirectMessage(user, text)
>>> api.DestroyDirectMessage(id)
>>> api.DestroyFriendship(user)
>>> api.CreateFriendship(user)
>>> api.GetUserByEmail(email)
'''
DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute
_API_REALM = 'Twitter API'
def __init__(self,
username=None,
password=None,
input_encoding=None,
request_headers=None):
'''Instantiate a new twitter.Api object.
Args:
username: The username of the twitter account. [optional]
password: The password for the twitter account. [optional]
input_encoding: The encoding used to encode input strings. [optional]
request_header: A dictionary of additional HTTP request headers. [optional]
'''
self._cache = _FileCache()
self._urllib = urllib2
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._InitializeRequestHeaders(request_headers)
self._InitializeUserAgent()
self._InitializeDefaultParameters()
self._input_encoding = input_encoding
self.SetCredentials(username, password)
def GetPublicTimeline(self, since_id=None):
'''Fetch the sequnce of public twitter.Status message for all users.
Args:
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
An sequence of twitter.Status instances, one for each message
'''
parameters = {}
if since_id:
parameters['since_id'] = since_id
url = 'http://twitter.com/statuses/public_timeline.json'
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetFriendsTimeline(self,
user=None,
count=None,
since=None,
since_id=None):
'''Fetch the sequence of twitter.Status messages for a user's friends
The twitter.Api instance must be authenticated if the user is private.
Args:
user:
Specifies the ID or screen name of the user for whom to return
the friends_timeline. If unspecified, the username and password
must be set in the twitter.Api instance. [Optional]
count:
Specifies the number of statuses to retrieve. May not be
greater than 200. [Optional]
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [Optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message
'''
if user:
url = 'http://twitter.com/statuses/friends_timeline/%s.json' % user
elif not user and not self._username:
raise TwitterError("User must be specified if API is not authenticated.")
else:
url = 'http://twitter.com/statuses/friends_timeline.json'
parameters = {}
if count is not None:
try:
if int(count) > 200:
raise TwitterError("'count' may not be greater than 200")
except ValueError:
raise TwitterError("'count' must be an integer")
parameters['count'] = count
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetUserTimeline(self, user=None, count=None, since=None, since_id=None):
'''Fetch the sequence of public twitter.Status messages for a single user.
The twitter.Api instance must be authenticated if the user is private.
Args:
user:
either the username (short_name) or id of the user to retrieve. If
not specified, then the current authenticated user is used. [optional]
count: the number of status messages to retrieve [optional]
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message up to count
'''
try:
if count:
int(count)
except:
raise TwitterError("Count must be an integer")
parameters = {}
if count:
parameters['count'] = count
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if user:
url = 'http://twitter.com/statuses/user_timeline/%s.json' % user
elif not user and not self._username:
raise TwitterError("User must be specified if API is not authenticated.")
else:
url = 'http://twitter.com/statuses/user_timeline.json'
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetStatus(self, id):
'''Returns a single status message.
The twitter.Api instance must be authenticated if the status message is private.
Args:
id: The numerical ID of the status you're trying to retrieve.
Returns:
A twitter.Status instance representing that status message
'''
try:
if id:
long(id)
except:
raise TwitterError("id must be an long integer")
url = 'http://twitter.com/statuses/show/%s.json' % id
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def DestroyStatus(self, id):
'''Destroys the status specified by the required ID parameter.
The twitter.Api instance must be authenticated and thee
authenticating user must be the author of the specified status.
Args:
id: The numerical ID of the status you're trying to destroy.
Returns:
A twitter.Status instance representing the destroyed status message
'''
try:
if id:
long(id)
except:
raise TwitterError("id must be an integer")
url = 'http://twitter.com/statuses/destroy/%s.json' % id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def PostUpdate(self, status, in_reply_to_status_id=None):
'''Post a twitter status message from the authenticated user.
The twitter.Api instance must be authenticated.
Args:
status:
The message text to be posted. Must be less than or equal to
140 characters.
in_reply_to_status_id:
The ID of an existing status that the status to be posted is
in reply to. This implicitly sets the in_reply_to_user_id
attribute of the resulting status to the user ID of the
message being replied to. Invalid/missing status IDs will be
ignored. [Optional]
Returns:
A twitter.Status instance representing the message posted.
'''
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = 'http://twitter.com/statuses/update.json'
if len(status) > CHARACTER_LIMIT:
raise TwitterError("Text must be less than or equal to %d characters. "
"Consider using PostUpdates." % CHARACTER_LIMIT)
data = {'status': status}
if in_reply_to_status_id:
data['in_reply_to_status_id'] = in_reply_to_status_id
json = self._FetchUrl(url, post_data=data)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def PostUpdates(self, status, continuation=None, **kwargs):
'''Post one or more twitter status messages from the authenticated user.
Unlike api.PostUpdate, this method will post multiple status updates
if the message is longer than 140 characters.
The twitter.Api instance must be authenticated.
Args:
status:
The message text to be posted. May be longer than 140 characters.
continuation:
The character string, if any, to be appended to all but the
last message. Note that Twitter strips trailing '...' strings
from messages. Consider using the unicode \u2026 character
(horizontal ellipsis) instead. [Defaults to None]
**kwargs:
See api.PostUpdate for a list of accepted parameters.
Returns:
A of list twitter.Status instance representing the messages posted.
'''
results = list()
if continuation is None:
continuation = ''
line_length = CHARACTER_LIMIT - len(continuation)
lines = textwrap.wrap(status, line_length)
for line in lines[0:-1]:
results.append(self.PostUpdate(line + continuation, **kwargs))
results.append(self.PostUpdate(lines[-1], **kwargs))
return results
def GetReplies(self, since=None, since_id=None, page=None):
'''Get a sequence of status messages representing the 20 most recent
replies (status updates prefixed with @username) to the authenticating
user.
Args:
page:
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.Status instances, one for each reply to the user.
'''
url = 'http://twitter.com/statuses/replies.json'
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetFriends(self, user=None, page=None):
'''Fetch the sequence of twitter.User instances, one for each friend.
Args:
user: the username or id of the user whose friends you are fetching. If
not specified, defaults to the authenticated user. [optional]
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances, one for each friend
'''
if not self._username:
raise TwitterError("twitter.Api instance must be authenticated")
if user:
url = 'http://twitter.com/statuses/friends/%s.json' % user
else:
url = 'http://twitter.com/statuses/friends.json'
parameters = {}
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [User.NewFromJsonDict(x) for x in data]
def GetFollowers(self, page=None):
'''Fetch the sequence of twitter.User instances, one for each follower
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances, one for each follower
'''
if not self._username:
raise TwitterError("twitter.Api instance must be authenticated")
url = 'http://twitter.com/statuses/followers.json'
parameters = {}
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [User.NewFromJsonDict(x) for x in data]
def GetFeatured(self):
'''Fetch the sequence of twitter.User instances featured on twitter.com
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances
'''
url = 'http://twitter.com/statuses/featured.json'
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [User.NewFromJsonDict(x) for x in data]
def GetUser(self, user):
'''Returns a single user.
The twitter.Api instance must be authenticated.
Args:
user: The username or id of the user to retrieve.
Returns:
A twitter.User instance representing that user
'''
url = 'http://twitter.com/users/show/%s.json' % user
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def GetDirectMessages(self, since=None, since_id=None, page=None):
'''Returns a list of the direct messages sent to the authenticating user.
The twitter.Api instance must be authenticated.
Args:
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.DirectMessage instances
'''
url = 'http://twitter.com/direct_messages.json'
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [DirectMessage.NewFromJsonDict(x) for x in data]
def PostDirectMessage(self, user, text):
'''Post a twitter direct message from the authenticated user
The twitter.Api instance must be authenticated.
Args:
user: The ID or screen name of the recipient user.
text: The message text to be posted. Must be less than 140 characters.
Returns:
A twitter.DirectMessage instance representing the message posted
'''
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = 'http://twitter.com/direct_messages/new.json'
data = {'text': text, 'user': user}
json = self._FetchUrl(url, post_data=data)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return DirectMessage.NewFromJsonDict(data)
def DestroyDirectMessage(self, id):
'''Destroys the direct message specified in the required ID parameter.
The twitter.Api instance must be authenticated, and the
authenticating user must be the recipient of the specified direct
message.
Args:
id: The id of the direct message to be destroyed
Returns:
A twitter.DirectMessage instance representing the message destroyed
'''
url = 'http://twitter.com/direct_messages/destroy/%s.json' % id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return DirectMessage.NewFromJsonDict(data)
def CreateFriendship(self, user):
'''Befriends the user specified in the user parameter as the authenticating user.
The twitter.Api instance must be authenticated.
Args:
The ID or screen name of the user to befriend.
Returns:
A twitter.User instance representing the befriended user.
'''
url = 'http://twitter.com/friendships/create/%s.json' % user
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def DestroyFriendship(self, user):
'''Discontinues friendship with the user specified in the user parameter.
The twitter.Api instance must be authenticated.
Args:
The ID or screen name of the user with whom to discontinue friendship.
Returns:
A twitter.User instance representing the discontinued friend.
'''
url = 'http://twitter.com/friendships/destroy/%s.json' % user
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def CreateFavorite(self, status):
'''Favorites the status specified in the status parameter as the authenticating user.
Returns the favorite status when successful.
The twitter.Api instance must be authenticated.
Args:
The twitter.Status instance to mark as a favorite.
Returns:
A twitter.Status instance representing the newly-marked favorite.
'''
url = 'http://twitter.com/favorites/create/%s.json' % status.id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def DestroyFavorite(self, status):
'''Un-favorites the status specified in the ID parameter as the authenticating user.
Returns the un-favorited status in the requested format when successful.
The twitter.Api instance must be authenticated.
Args:
The twitter.Status to unmark as a favorite.
Returns:
A twitter.Status instance representing the newly-unmarked favorite.
'''
url = 'http://twitter.com/favorites/destroy/%s.json' % status.id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def GetUserByEmail(self, email):
'''Returns a single user by email address.
Args:
email: The email of the user to retrieve.
Returns:
A twitter.User instance representing that user
'''
url = 'http://twitter.com/users/show.json?email=%s' % email
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def SetCredentials(self, username, password):
'''Set the username and password for this instance
Args:
username: The twitter username.
password: The twitter password.
'''
self._username = username
self._password = password
def ClearCredentials(self):
'''Clear the username and password for this instance
'''
self._username = None
self._password = None
def SetCache(self, cache):
'''Override the default cache. Set to None to prevent caching.
Args:
cache: an instance that supports the same API as the twitter._FileCache
'''
self._cache = cache
def SetUrllib(self, urllib):
'''Override the default urllib implementation.
Args:
urllib: an instance that supports the same API as the urllib2 module
'''
self._urllib = urllib
def SetCacheTimeout(self, cache_timeout):
'''Override the default cache timeout.
Args:
cache_timeout: time, in seconds, that responses should be reused.
'''
self._cache_timeout = cache_timeout
def SetUserAgent(self, user_agent):
'''Override the default user agent
Args:
user_agent: a string that should be send to the server as the User-agent
'''
self._request_headers['User-Agent'] = user_agent
def SetXTwitterHeaders(self, client, url, version):
'''Set the X-Twitter HTTP headers that will be sent to the server.
Args:
client:
The client name as a string. Will be sent to the server as
the 'X-Twitter-Client' header.
url:
The URL of the meta.xml as a string. Will be sent to the server
as the 'X-Twitter-Client-URL' header.
version:
The client version as a string. Will be sent to the server
as the 'X-Twitter-Client-Version' header.
'''
self._request_headers['X-Twitter-Client'] = client
self._request_headers['X-Twitter-Client-URL'] = url
self._request_headers['X-Twitter-Client-Version'] = version
def SetSource(self, source):
'''Suggest the "from source" value to be displayed on the Twitter web site.
The value of the 'source' parameter must be first recognized by
the Twitter server. New source values are authorized on a case by
case basis by the Twitter development team.
Args:
source:
The source name as a string. Will be sent to the server as
the 'source' parameter.
'''
self._default_params['source'] = source
def _BuildUrl(self, url, path_elements=None, extra_params=None):
# Break url into consituent parts
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
# Add any additional path elements to the path
if path_elements:
# Filter out the path elements that have a value of None
p = [i for i in path_elements if i]
if not path.endswith('/'):
path += '/'
path += '/'.join(p)
# Add any additional query parameters to the query string
if extra_params and len(extra_params) > 0:
extra_query = self._EncodeParameters(extra_params)
# Add it to the existing query
if query:
query += '&' + extra_query
else:
query = extra_query
# Return the rebuilt URL
return urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
def _InitializeRequestHeaders(self, request_headers):
if request_headers:
self._request_headers = request_headers
else:
self._request_headers = {}
def _InitializeUserAgent(self):
user_agent = 'Python-urllib/%s (python-twitter/%s)' % \
(self._urllib.__version__, __version__)
self.SetUserAgent(user_agent)
def _InitializeDefaultParameters(self):
self._default_params = {}
def _AddAuthorizationHeader(self, username, password):
if username and password:
basic_auth = base64.encodestring('%s:%s' % (username, password))[:-1]
self._request_headers['Authorization'] = 'Basic %s' % basic_auth
def _RemoveAuthorizationHeader(self):
if self._request_headers and 'Authorization' in self._request_headers:
del self._request_headers['Authorization']
def _GetOpener(self, url, username=None, password=None):
if username and password:
self._AddAuthorizationHeader(username, password)
handler = self._urllib.HTTPBasicAuthHandler()
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
handler.add_password(Api._API_REALM, netloc, username, password)
opener = self._urllib.build_opener(handler)
else:
opener = self._urllib.build_opener()
opener.addheaders = self._request_headers.items()
return opener
def _Encode(self, s):
if self._input_encoding:
return unicode(s, self._input_encoding).encode('utf-8')
else:
return unicode(s).encode('utf-8')
def _EncodeParameters(self, parameters):
'''Return a string in key=value&key=value form
Values of None are not included in the output string.
Args:
parameters:
A dict of (key, value) tuples, where value is encoded as
specified by self._encoding
Returns:
A URL-encoded string in "key=value&key=value" form
'''
if parameters is None:
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None]))
def _EncodePostData(self, post_data):
'''Return a string in key=value&key=value form
Values are assumed to be encoded in the format specified by self._encoding,
and are subsequently URL encoded.
Args:
post_data:
A dict of (key, value) tuples, where value is encoded as
specified by self._encoding
Returns:
A URL-encoded string in "key=value&key=value" form
'''
if post_data is None:
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()]))
def _CheckForTwitterError(self, data):
"""Raises a TwitterError if twitter returns an error message.
Args:
data: A python dict created from the Twitter json response
Raises:
TwitterError wrapping the twitter error message if one exists.
"""
# Twitter errors are relatively unlikely, so it is faster
# to check first, rather than try and catch the exception
if 'error' in data:
raise TwitterError(data['error'])
def _FetchUrl(self,
url,
post_data=None,
parameters=None,
no_cache=None):
'''Fetch a URL, optionally caching for a specified time.
Args:
url: The URL to retrieve
post_data:
A dict of (str, unicode) key/value pairs. If set, POST will be used.
parameters:
A dict whose key/value pairs should encoded and added
to the query string. [OPTIONAL]
no_cache: If true, overrides the cache on the current request
Returns:
A string containing the body of the response.
'''
# Build the extra parameters dict
extra_params = {}
if self._default_params:
extra_params.update(self._default_params)
if parameters:
extra_params.update(parameters)
# Add key/value parameters to the query string of the url
url = self._BuildUrl(url, extra_params=extra_params)
# Get a url opener that can handle basic auth
opener = self._GetOpener(url, username=self._username, password=self._password)
encoded_post_data = self._EncodePostData(post_data)
# Open and return the URL immediately if we're not going to cache
if encoded_post_data or no_cache or not self._cache or not self._cache_timeout:
url_data = opener.open(url, encoded_post_data).read()
opener.close()
else:
# Unique keys are a combination of the url and the username
if self._username:
key = self._username + ':' + url
else:
key = url
# See if it has been cached before
last_cached = self._cache.GetCachedTime(key)
# If the cached version is outdated then fetch another and store it
if not last_cached or time.time() >= last_cached + self._cache_timeout:
url_data = opener.open(url, encoded_post_data).read()
opener.close()
self._cache.Set(key, url_data)
else:
url_data = self._cache.Get(key)
# Always return the latest version
return url_data
class _FileCacheError(Exception):
'''Base exception class for FileCache related errors'''
class _FileCache(object):
DEPTH = 3
def __init__(self,root_directory=None):
self._InitializeRootDirectory(root_directory)
def Get(self,key):
path = self._GetPath(key)
if os.path.exists(path):
return open(path).read()
else:
return None
def Set(self,key,data):
path = self._GetPath(key)
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise _FileCacheError('%s exists but is not a directory' % directory)
temp_fd, temp_path = tempfile.mkstemp()
temp_fp = os.fdopen(temp_fd, 'w')
temp_fp.write(data)
temp_fp.close()
if not path.startswith(self._root_directory):
raise _FileCacheError('%s does not appear to live under %s' %
(path, self._root_directory))
if os.path.exists(path):
os.remove(path)
os.rename(temp_path, path)
def Remove(self,key):
path = self._GetPath(key)
if not path.startswith(self._root_directory):
raise _FileCacheError('%s does not appear to live under %s' %
(path, self._root_directory ))
if os.path.exists(path):
os.remove(path)
def GetCachedTime(self,key):
path = self._GetPath(key)
if os.path.exists(path):
return os.path.getmtime(path)
else:
return None
def _GetUsername(self):
'''Attempt to find the username in a cross-platform fashion.'''
try:
return os.getenv('USER') or \
os.getenv('LOGNAME') or \
os.getenv('USERNAME') or \
os.getlogin() or \
'nobody'
except (IOError, OSError), e:
return 'nobody'
def _GetTmpCachePath(self):
username = self.name()
cache_directory = 'python.cache_' + username
return os.path.join(tempfile.gettempdir(), cache_directory)
def _InitializeRootDirectory(self, root_directory):
if not root_directory:
root_directory = self._GetTmpCachePath()
root_directory = os.path.abspath(root_directory)
if not os.path.exists(root_directory):
os.mkdir(root_directory)
if not os.path.isdir(root_directory):
raise _FileCacheError('%s exists but is not a directory' %
root_directory)
self._root_directory = root_directory
def _GetPath(self,key):
try:
hashed_key = md5(key).hexdigest()
except TypeError:
hashed_key = md5.new(key).hexdigest()
return os.path.join(self._root_directory,
self._GetPrefix(hashed_key),
hashed_key)
def _GetPrefix(self,hashed_key):
return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
| Python |
# -*- coding: utf8 -*-
from twitter import Api
import simplejson
import urllib2
import logging
class Api(Api):
''' twitter.Apiクラスの拡張
self._cacheの影響でファイル入出力が発生するため、
Apiクラスのラッパーとして利用する。
'''
def __init__(self,
username=None,
password=None,
input_encoding=None,
request_headers=None):
'''gaetwitter.Api オブジェクトの初期化
Args:
username: The username of the twitter account. [optional]
password: The password for the twitter account. [optional]
input_encoding: The encoding used to encode input strings. [optional]
request_header: A dictionary of additional HTTP request headers. [optional]
'''
self._cache = None
self._urllib = urllib2
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._InitializeRequestHeaders(request_headers)
self._InitializeUserAgent()
self._InitializeDefaultParameters()
self._input_encoding = input_encoding
self.SetCredentials(username, password)
def Search(self, q=None):
parameters = {}
if q:
parameters['q'] = q
url = 'http://search.twitter.com/search.json'
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Search.NewFromJsonDict(x) for x in data['results']]
class Search(object):
def __init(self,
text=None):
self.text = text
@staticmethod
def NewFromJsonDict(data):
if 'from_user' in data:
return data['from_user']
| Python |
#!/usr/bin/python2.4
#
# Copyright 2007 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''A library that provides a python interface to the Twitter API'''
__author__ = 'dewitt@google.com'
__version__ = '0.6-devel'
import base64
import calendar
import os
import rfc822
import simplejson
import sys
import tempfile
import textwrap
import time
import urllib
import urllib2
import urlparse
try:
from hashlib import md5
except ImportError:
from md5 import md5
CHARACTER_LIMIT = 140
class TwitterError(Exception):
'''Base class for Twitter errors'''
@property
def message(self):
'''Returns the first argument used to construct this error.'''
return self.args[0]
class Status(object):
'''A class representing the Status structure used by the twitter API.
The Status structure exposes the following properties:
status.created_at
status.created_at_in_seconds # read only
status.favorited
status.in_reply_to_screen_name
status.in_reply_to_user_id
status.in_reply_to_status_id
status.truncated
status.source
status.id
status.text
status.relative_created_at # read only
status.user
'''
def __init__(self,
created_at=None,
favorited=None,
id=None,
text=None,
user=None,
in_reply_to_screen_name=None,
in_reply_to_user_id=None,
in_reply_to_status_id=None,
truncated=None,
source=None,
now=None):
'''An object to hold a Twitter status message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
created_at: The time this status message was posted
favorited: Whether this is a favorite of the authenticated user
id: The unique id of this status message
text: The text of this status message
relative_created_at:
A human readable string representing the posting time
user:
A twitter.User instance representing the person posting the message
now:
The current time, if the client choses to set it. Defaults to the
wall clock time.
'''
self.created_at = created_at
self.favorited = favorited
self.id = id
self.text = text
self.user = user
self.now = now
self.in_reply_to_screen_name = in_reply_to_screen_name
self.in_reply_to_user_id = in_reply_to_user_id
self.in_reply_to_status_id = in_reply_to_status_id
self.truncated = truncated
self.source = source
def GetCreatedAt(self):
'''Get the time this status message was posted.
Returns:
The time this status message was posted
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set the time this status message was posted.
Args:
created_at: The time this status message was created
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The time this status message was posted.')
def GetCreatedAtInSeconds(self):
'''Get the time this status message was posted, in seconds since the epoch.
Returns:
The time this status message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
created_at_in_seconds = property(GetCreatedAtInSeconds,
doc="The time this status message was "
"posted, in seconds since the epoch")
def GetFavorited(self):
'''Get the favorited setting of this status message.
Returns:
True if this status message is favorited; False otherwise
'''
return self._favorited
def SetFavorited(self, favorited):
'''Set the favorited state of this status message.
Args:
favorited: boolean True/False favorited state of this status message
'''
self._favorited = favorited
favorited = property(GetFavorited, SetFavorited,
doc='The favorited state of this status message.')
def GetId(self):
'''Get the unique id of this status message.
Returns:
The unique id of this status message
'''
return self._id
def SetId(self, id):
'''Set the unique id of this status message.
Args:
id: The unique id of this status message
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this status message.')
def GetInReplyToScreenName(self):
return self._in_reply_to_screen_name
def SetInReplyToScreenName(self, in_reply_to_screen_name):
self._in_reply_to_screen_name = in_reply_to_screen_name
in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName,
doc='')
def GetInReplyToUserId(self):
return self._in_reply_to_user_id
def SetInReplyToUserId(self, in_reply_to_user_id):
self._in_reply_to_user_id = in_reply_to_user_id
in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId,
doc='')
def GetInReplyToStatusId(self):
return self._in_reply_to_status_id
def SetInReplyToStatusId(self, in_reply_to_status_id):
self._in_reply_to_status_id = in_reply_to_status_id
in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId,
doc='')
def GetTruncated(self):
return self._truncated
def SetTruncated(self, truncated):
self._truncated = truncated
truncated = property(GetTruncated, SetTruncated,
doc='')
def GetSource(self):
return self._source
def SetSource(self, source):
self._source = source
source = property(GetSource, SetSource,
doc='')
def GetText(self):
'''Get the text of this status message.
Returns:
The text of this status message.
'''
return self._text
def SetText(self, text):
'''Set the text of this status message.
Args:
text: The text of this status message
'''
self._text = text
text = property(GetText, SetText,
doc='The text of this status message')
def GetRelativeCreatedAt(self):
'''Get a human redable string representing the posting time
Returns:
A human readable string representing the posting time
'''
fudge = 1.25
delta = long(self.now) - long(self.created_at_in_seconds)
if delta < (1 * fudge):
return 'about a second ago'
elif delta < (60 * (1/fudge)):
return 'about %d seconds ago' % (delta)
elif delta < (60 * fudge):
return 'about a minute ago'
elif delta < (60 * 60 * (1/fudge)):
return 'about %d minutes ago' % (delta / 60)
elif delta < (60 * 60 * fudge):
return 'about an hour ago'
elif delta < (60 * 60 * 24 * (1/fudge)):
return 'about %d hours ago' % (delta / (60 * 60))
elif delta < (60 * 60 * 24 * fudge):
return 'about a day ago'
else:
return 'about %d days ago' % (delta / (60 * 60 * 24))
relative_created_at = property(GetRelativeCreatedAt,
doc='Get a human readable string representing'
'the posting time')
def GetUser(self):
'''Get a twitter.User reprenting the entity posting this status message.
Returns:
A twitter.User reprenting the entity posting this status message
'''
return self._user
def SetUser(self, user):
'''Set a twitter.User reprenting the entity posting this status message.
Args:
user: A twitter.User reprenting the entity posting this status message
'''
self._user = user
user = property(GetUser, SetUser,
doc='A twitter.User reprenting the entity posting this '
'status message')
def GetNow(self):
'''Get the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Returns:
Whatever the status instance believes the current time to be,
in seconds since the epoch.
'''
if self._now is None:
self._now = time.time()
return self._now
def SetNow(self, now):
'''Set the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Args:
now: The wallclock time for this instance.
'''
self._now = now
now = property(GetNow, SetNow,
doc='The wallclock time for this status instance.')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.created_at == other.created_at and \
self.id == other.id and \
self.text == other.text and \
self.user == other.user and \
self.in_reply_to_screen_name == other.in_reply_to_screen_name and \
self.in_reply_to_user_id == other.in_reply_to_user_id and \
self.in_reply_to_status_id == other.in_reply_to_status_id and \
self.truncated == other.truncated and \
self.favorited == other.favorited and \
self.source == other.source
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.Status instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.Status instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.Status instance.
Returns:
A JSON string representation of this twitter.Status instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.Status instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.Status instance
'''
data = {}
if self.created_at:
data['created_at'] = self.created_at
if self.favorited:
data['favorited'] = self.favorited
if self.id:
data['id'] = self.id
if self.text:
data['text'] = self.text
if self.user:
data['user'] = self.user.AsDict()
if self.in_reply_to_screen_name:
data['in_reply_to_screen_name'] = self.in_reply_to_screen_name
if self.in_reply_to_user_id:
data['in_reply_to_user_id'] = self.in_reply_to_user_id
if self.in_reply_to_status_id:
data['in_reply_to_status_id'] = self.in_reply_to_status_id
if self.truncated is not None:
data['truncated'] = self.truncated
if self.favorited is not None:
data['favorited'] = self.favorited
if self.source:
data['source'] = self.source
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Status instance
'''
if 'user' in data:
user = User.NewFromJsonDict(data['user'])
else:
user = None
return Status(created_at=data.get('created_at', None),
favorited=data.get('favorited', None),
id=data.get('id', None),
text=data.get('text', None),
in_reply_to_screen_name=data.get('in_reply_to_screen_name', None),
in_reply_to_user_id=data.get('in_reply_to_user_id', None),
in_reply_to_status_id=data.get('in_reply_to_status_id', None),
truncated=data.get('truncated', None),
source=data.get('source', None),
user=user)
class User(object):
'''A class representing the User structure used by the twitter API.
The User structure exposes the following properties:
user.id
user.name
user.screen_name
user.location
user.description
user.profile_image_url
user.profile_background_tile
user.profile_background_image_url
user.profile_sidebar_fill_color
user.profile_background_color
user.profile_link_color
user.profile_text_color
user.protected
user.utc_offset
user.time_zone
user.url
user.status
user.statuses_count
user.followers_count
user.friends_count
user.favourites_count
'''
def __init__(self,
id=None,
name=None,
screen_name=None,
location=None,
description=None,
profile_image_url=None,
profile_background_tile=None,
profile_background_image_url=None,
profile_sidebar_fill_color=None,
profile_background_color=None,
profile_link_color=None,
profile_text_color=None,
protected=None,
utc_offset=None,
time_zone=None,
followers_count=None,
friends_count=None,
statuses_count=None,
favourites_count=None,
url=None,
status=None):
self.id = id
self.name = name
self.screen_name = screen_name
self.location = location
self.description = description
self.profile_image_url = profile_image_url
self.profile_background_tile = profile_background_tile
self.profile_background_image_url = profile_background_image_url
self.profile_sidebar_fill_color = profile_sidebar_fill_color
self.profile_background_color = profile_background_color
self.profile_link_color = profile_link_color
self.profile_text_color = profile_text_color
self.protected = protected
self.utc_offset = utc_offset
self.time_zone = time_zone
self.followers_count = followers_count
self.friends_count = friends_count
self.statuses_count = statuses_count
self.favourites_count = favourites_count
self.url = url
self.status = status
def GetId(self):
'''Get the unique id of this user.
Returns:
The unique id of this user
'''
return self._id
def SetId(self, id):
'''Set the unique id of this user.
Args:
id: The unique id of this user.
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this user.')
def GetName(self):
'''Get the real name of this user.
Returns:
The real name of this user
'''
return self._name
def SetName(self, name):
'''Set the real name of this user.
Args:
name: The real name of this user
'''
self._name = name
name = property(GetName, SetName,
doc='The real name of this user.')
def GetScreenName(self):
'''Get the short username of this user.
Returns:
The short username of this user
'''
return self._screen_name
def SetScreenName(self, screen_name):
'''Set the short username of this user.
Args:
screen_name: the short username of this user
'''
self._screen_name = screen_name
screen_name = property(GetScreenName, SetScreenName,
doc='The short username of this user.')
def GetLocation(self):
'''Get the geographic location of this user.
Returns:
The geographic location of this user
'''
return self._location
def SetLocation(self, location):
'''Set the geographic location of this user.
Args:
location: The geographic location of this user
'''
self._location = location
location = property(GetLocation, SetLocation,
doc='The geographic location of this user.')
def GetDescription(self):
'''Get the short text description of this user.
Returns:
The short text description of this user
'''
return self._description
def SetDescription(self, description):
'''Set the short text description of this user.
Args:
description: The short text description of this user
'''
self._description = description
description = property(GetDescription, SetDescription,
doc='The short text description of this user.')
def GetUrl(self):
'''Get the homepage url of this user.
Returns:
The homepage url of this user
'''
return self._url
def SetUrl(self, url):
'''Set the homepage url of this user.
Args:
url: The homepage url of this user
'''
self._url = url
url = property(GetUrl, SetUrl,
doc='The homepage url of this user.')
def GetProfileImageUrl(self):
'''Get the url of the thumbnail of this user.
Returns:
The url of the thumbnail of this user
'''
return self._profile_image_url
def SetProfileImageUrl(self, profile_image_url):
'''Set the url of the thumbnail of this user.
Args:
profile_image_url: The url of the thumbnail of this user
'''
self._profile_image_url = profile_image_url
profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl,
doc='The url of the thumbnail of this user.')
def GetProfileBackgroundTile(self):
'''Boolean for whether to tile the profile background image.
Returns:
True if the background is to be tiled, False if not, None if unset.
'''
return self._profile_background_tile
def SetProfileBackgroundTile(self, profile_background_tile):
'''Set the boolean flag for whether to tile the profile background image.
Args:
profile_background_tile: Boolean flag for whether to tile or not.
'''
self._profile_background_tile = profile_background_tile
profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile,
doc='Boolean for whether to tile the background image.')
def GetProfileBackgroundImageUrl(self):
return self._profile_background_image_url
def SetProfileBackgroundImageUrl(self, profile_background_image_url):
self._profile_background_image_url = profile_background_image_url
profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl,
doc='The url of the profile background of this user.')
def GetProfileSidebarFillColor(self):
return self._profile_sidebar_fill_color
def SetProfileSidebarFillColor(self, profile_sidebar_fill_color):
self._profile_sidebar_fill_color = profile_sidebar_fill_color
profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor)
def GetProfileBackgroundColor(self):
return self._profile_background_color
def SetProfileBackgroundColor(self, profile_background_color):
self._profile_background_color = profile_background_color
profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor)
def GetProfileLinkColor(self):
return self._profile_link_color
def SetProfileLinkColor(self, profile_link_color):
self._profile_link_color = profile_link_color
profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor)
def GetProfileTextColor(self):
return self._profile_text_color
def SetProfileTextColor(self, profile_text_color):
self._profile_text_color = profile_text_color
profile_text_color = property(GetProfileTextColor, SetProfileTextColor)
def GetProtected(self):
return self._protected
def SetProtected(self, protected):
self._protected = protected
protected = property(GetProtected, SetProtected)
def GetUtcOffset(self):
return self._utc_offset
def SetUtcOffset(self, utc_offset):
self._utc_offset = utc_offset
utc_offset = property(GetUtcOffset, SetUtcOffset)
def GetTimeZone(self):
'''Returns the current time zone string for the user.
Returns:
The descriptive time zone string for the user.
'''
return self._time_zone
def SetTimeZone(self, time_zone):
'''Sets the user's time zone string.
Args:
time_zone: The descriptive time zone to assign for the user.
'''
self._time_zone = time_zone
time_zone = property(GetTimeZone, SetTimeZone)
def GetStatus(self):
'''Get the latest twitter.Status of this user.
Returns:
The latest twitter.Status of this user
'''
return self._status
def SetStatus(self, status):
'''Set the latest twitter.Status of this user.
Args:
status: The latest twitter.Status of this user
'''
self._status = status
status = property(GetStatus, SetStatus,
doc='The latest twitter.Status of this user.')
def GetFriendsCount(self):
'''Get the friend count for this user.
Returns:
The number of users this user has befriended.
'''
return self._friends_count
def SetFriendsCount(self, count):
'''Set the friend count for this user.
Args:
count: The number of users this user has befriended.
'''
self._friends_count = count
friends_count = property(GetFriendsCount, SetFriendsCount,
doc='The number of friends for this user.')
def GetFollowersCount(self):
'''Get the follower count for this user.
Returns:
The number of users following this user.
'''
return self._followers_count
def SetFollowersCount(self, count):
'''Set the follower count for this user.
Args:
count: The number of users following this user.
'''
self._followers_count = count
followers_count = property(GetFollowersCount, SetFollowersCount,
doc='The number of users following this user.')
def GetStatusesCount(self):
'''Get the number of status updates for this user.
Returns:
The number of status updates for this user.
'''
return self._statuses_count
def SetStatusesCount(self, count):
'''Set the status update count for this user.
Args:
count: The number of updates for this user.
'''
self._statuses_count = count
statuses_count = property(GetStatusesCount, SetStatusesCount,
doc='The number of updates for this user.')
def GetFavouritesCount(self):
'''Get the number of favourites for this user.
Returns:
The number of favourites for this user.
'''
return self._favourites_count
def SetFavouritesCount(self, count):
'''Set the favourite count for this user.
Args:
count: The number of favourites for this user.
'''
self._favourites_count = count
favourites_count = property(GetFavouritesCount, SetFavouritesCount,
doc='The number of favourites for this user.')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.name == other.name and \
self.screen_name == other.screen_name and \
self.location == other.location and \
self.description == other.description and \
self.profile_image_url == other.profile_image_url and \
self.profile_background_tile == other.profile_background_tile and \
self.profile_background_image_url == other.profile_background_image_url and \
self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \
self.profile_background_color == other.profile_background_color and \
self.profile_link_color == other.profile_link_color and \
self.profile_text_color == other.profile_text_color and \
self.protected == other.protected and \
self.utc_offset == other.utc_offset and \
self.time_zone == other.time_zone and \
self.url == other.url and \
self.statuses_count == other.statuses_count and \
self.followers_count == other.followers_count and \
self.favourites_count == other.favourites_count and \
self.friends_count == other.friends_count and \
self.status == other.status
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.User instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.User instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.User instance.
Returns:
A JSON string representation of this twitter.User instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.User instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.User instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.name:
data['name'] = self.name
if self.screen_name:
data['screen_name'] = self.screen_name
if self.location:
data['location'] = self.location
if self.description:
data['description'] = self.description
if self.profile_image_url:
data['profile_image_url'] = self.profile_image_url
if self.profile_background_tile is not None:
data['profile_background_tile'] = self.profile_background_tile
if self.profile_background_image_url:
data['profile_sidebar_fill_color'] = self.profile_background_image_url
if self.profile_background_color:
data['profile_background_color'] = self.profile_background_color
if self.profile_link_color:
data['profile_link_color'] = self.profile_link_color
if self.profile_text_color:
data['profile_text_color'] = self.profile_text_color
if self.protected is not None:
data['protected'] = self.protected
if self.utc_offset:
data['utc_offset'] = self.utc_offset
if self.time_zone:
data['time_zone'] = self.time_zone
if self.url:
data['url'] = self.url
if self.status:
data['status'] = self.status.AsDict()
if self.friends_count:
data['friends_count'] = self.friends_count
if self.followers_count:
data['followers_count'] = self.followers_count
if self.statuses_count:
data['statuses_count'] = self.statuses_count
if self.favourites_count:
data['favourites_count'] = self.favourites_count
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.User instance
'''
if 'status' in data:
status = Status.NewFromJsonDict(data['status'])
else:
status = None
return User(id=data.get('id', None),
name=data.get('name', None),
screen_name=data.get('screen_name', None),
location=data.get('location', None),
description=data.get('description', None),
statuses_count=data.get('statuses_count', None),
followers_count=data.get('followers_count', None),
favourites_count=data.get('favourites_count', None),
friends_count=data.get('friends_count', None),
profile_image_url=data.get('profile_image_url', None),
profile_background_tile = data.get('profile_background_tile', None),
profile_background_image_url = data.get('profile_background_image_url', None),
profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None),
profile_background_color = data.get('profile_background_color', None),
profile_link_color = data.get('profile_link_color', None),
profile_text_color = data.get('profile_text_color', None),
protected = data.get('protected', None),
utc_offset = data.get('utc_offset', None),
time_zone = data.get('time_zone', None),
url=data.get('url', None),
status=status)
class DirectMessage(object):
'''A class representing the DirectMessage structure used by the twitter API.
The DirectMessage structure exposes the following properties:
direct_message.id
direct_message.created_at
direct_message.created_at_in_seconds # read only
direct_message.sender_id
direct_message.sender_screen_name
direct_message.recipient_id
direct_message.recipient_screen_name
direct_message.text
'''
def __init__(self,
id=None,
created_at=None,
sender_id=None,
sender_screen_name=None,
recipient_id=None,
recipient_screen_name=None,
text=None):
'''An object to hold a Twitter direct message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
id: The unique id of this direct message
created_at: The time this direct message was posted
sender_id: The id of the twitter user that sent this message
sender_screen_name: The name of the twitter user that sent this message
recipient_id: The id of the twitter that received this message
recipient_screen_name: The name of the twitter that received this message
text: The text of this direct message
'''
self.id = id
self.created_at = created_at
self.sender_id = sender_id
self.sender_screen_name = sender_screen_name
self.recipient_id = recipient_id
self.recipient_screen_name = recipient_screen_name
self.text = text
def GetId(self):
'''Get the unique id of this direct message.
Returns:
The unique id of this direct message
'''
return self._id
def SetId(self, id):
'''Set the unique id of this direct message.
Args:
id: The unique id of this direct message
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this direct message.')
def GetCreatedAt(self):
'''Get the time this direct message was posted.
Returns:
The time this direct message was posted
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set the time this direct message was posted.
Args:
created_at: The time this direct message was created
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The time this direct message was posted.')
def GetCreatedAtInSeconds(self):
'''Get the time this direct message was posted, in seconds since the epoch.
Returns:
The time this direct message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
created_at_in_seconds = property(GetCreatedAtInSeconds,
doc="The time this direct message was "
"posted, in seconds since the epoch")
def GetSenderId(self):
'''Get the unique sender id of this direct message.
Returns:
The unique sender id of this direct message
'''
return self._sender_id
def SetSenderId(self, sender_id):
'''Set the unique sender id of this direct message.
Args:
sender id: The unique sender id of this direct message
'''
self._sender_id = sender_id
sender_id = property(GetSenderId, SetSenderId,
doc='The unique sender id of this direct message.')
def GetSenderScreenName(self):
'''Get the unique sender screen name of this direct message.
Returns:
The unique sender screen name of this direct message
'''
return self._sender_screen_name
def SetSenderScreenName(self, sender_screen_name):
'''Set the unique sender screen name of this direct message.
Args:
sender_screen_name: The unique sender screen name of this direct message
'''
self._sender_screen_name = sender_screen_name
sender_screen_name = property(GetSenderScreenName, SetSenderScreenName,
doc='The unique sender screen name of this direct message.')
def GetRecipientId(self):
'''Get the unique recipient id of this direct message.
Returns:
The unique recipient id of this direct message
'''
return self._recipient_id
def SetRecipientId(self, recipient_id):
'''Set the unique recipient id of this direct message.
Args:
recipient id: The unique recipient id of this direct message
'''
self._recipient_id = recipient_id
recipient_id = property(GetRecipientId, SetRecipientId,
doc='The unique recipient id of this direct message.')
def GetRecipientScreenName(self):
'''Get the unique recipient screen name of this direct message.
Returns:
The unique recipient screen name of this direct message
'''
return self._recipient_screen_name
def SetRecipientScreenName(self, recipient_screen_name):
'''Set the unique recipient screen name of this direct message.
Args:
recipient_screen_name: The unique recipient screen name of this direct message
'''
self._recipient_screen_name = recipient_screen_name
recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName,
doc='The unique recipient screen name of this direct message.')
def GetText(self):
'''Get the text of this direct message.
Returns:
The text of this direct message.
'''
return self._text
def SetText(self, text):
'''Set the text of this direct message.
Args:
text: The text of this direct message
'''
self._text = text
text = property(GetText, SetText,
doc='The text of this direct message')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.created_at == other.created_at and \
self.sender_id == other.sender_id and \
self.sender_screen_name == other.sender_screen_name and \
self.recipient_id == other.recipient_id and \
self.recipient_screen_name == other.recipient_screen_name and \
self.text == other.text
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.DirectMessage instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.DirectMessage instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.DirectMessage instance.
Returns:
A JSON string representation of this twitter.DirectMessage instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.DirectMessage instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.DirectMessage instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.created_at:
data['created_at'] = self.created_at
if self.sender_id:
data['sender_id'] = self.sender_id
if self.sender_screen_name:
data['sender_screen_name'] = self.sender_screen_name
if self.recipient_id:
data['recipient_id'] = self.recipient_id
if self.recipient_screen_name:
data['recipient_screen_name'] = self.recipient_screen_name
if self.text:
data['text'] = self.text
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.DirectMessage instance
'''
return DirectMessage(created_at=data.get('created_at', None),
recipient_id=data.get('recipient_id', None),
sender_id=data.get('sender_id', None),
text=data.get('text', None),
sender_screen_name=data.get('sender_screen_name', None),
id=data.get('id', None),
recipient_screen_name=data.get('recipient_screen_name', None))
class Api(object):
'''A python interface into the Twitter API
By default, the Api caches results for 1 minute.
Example usage:
To create an instance of the twitter.Api class, with no authentication:
>>> import twitter
>>> api = twitter.Api()
To fetch the most recently posted public twitter status messages:
>>> statuses = api.GetPublicTimeline()
>>> print [s.user.name for s in statuses]
[u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #...
To fetch a single user's public status messages, where "user" is either
a Twitter "short name" or their user id.
>>> statuses = api.GetUserTimeline(user)
>>> print [s.text for s in statuses]
To use authentication, instantiate the twitter.Api class with a
username and password:
>>> api = twitter.Api(username='twitter user', password='twitter pass')
To fetch your friends (after being authenticated):
>>> users = api.GetFriends()
>>> print [u.name for u in users]
To post a twitter status message (after being authenticated):
>>> status = api.PostUpdate('I love python-twitter!')
>>> print status.text
I love python-twitter!
There are many other methods, including:
>>> api.PostUpdates(status)
>>> api.PostDirectMessage(user, text)
>>> api.GetUser(user)
>>> api.GetReplies()
>>> api.GetUserTimeline(user)
>>> api.GetStatus(id)
>>> api.DestroyStatus(id)
>>> api.GetFriendsTimeline(user)
>>> api.GetFriends(user)
>>> api.GetFollowers()
>>> api.GetFeatured()
>>> api.GetDirectMessages()
>>> api.PostDirectMessage(user, text)
>>> api.DestroyDirectMessage(id)
>>> api.DestroyFriendship(user)
>>> api.CreateFriendship(user)
>>> api.GetUserByEmail(email)
'''
DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute
_API_REALM = 'Twitter API'
def __init__(self,
username=None,
password=None,
input_encoding=None,
request_headers=None):
'''Instantiate a new twitter.Api object.
Args:
username: The username of the twitter account. [optional]
password: The password for the twitter account. [optional]
input_encoding: The encoding used to encode input strings. [optional]
request_header: A dictionary of additional HTTP request headers. [optional]
'''
self._cache = _FileCache()
self._urllib = urllib2
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._InitializeRequestHeaders(request_headers)
self._InitializeUserAgent()
self._InitializeDefaultParameters()
self._input_encoding = input_encoding
self.SetCredentials(username, password)
def GetPublicTimeline(self, since_id=None):
'''Fetch the sequnce of public twitter.Status message for all users.
Args:
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
An sequence of twitter.Status instances, one for each message
'''
parameters = {}
if since_id:
parameters['since_id'] = since_id
url = 'http://twitter.com/statuses/public_timeline.json'
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetFriendsTimeline(self,
user=None,
count=None,
since=None,
since_id=None):
'''Fetch the sequence of twitter.Status messages for a user's friends
The twitter.Api instance must be authenticated if the user is private.
Args:
user:
Specifies the ID or screen name of the user for whom to return
the friends_timeline. If unspecified, the username and password
must be set in the twitter.Api instance. [Optional]
count:
Specifies the number of statuses to retrieve. May not be
greater than 200. [Optional]
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [Optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message
'''
if user:
url = 'http://twitter.com/statuses/friends_timeline/%s.json' % user
elif not user and not self._username:
raise TwitterError("User must be specified if API is not authenticated.")
else:
url = 'http://twitter.com/statuses/friends_timeline.json'
parameters = {}
if count is not None:
try:
if int(count) > 200:
raise TwitterError("'count' may not be greater than 200")
except ValueError:
raise TwitterError("'count' must be an integer")
parameters['count'] = count
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetUserTimeline(self, user=None, count=None, since=None, since_id=None):
'''Fetch the sequence of public twitter.Status messages for a single user.
The twitter.Api instance must be authenticated if the user is private.
Args:
user:
either the username (short_name) or id of the user to retrieve. If
not specified, then the current authenticated user is used. [optional]
count: the number of status messages to retrieve [optional]
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message up to count
'''
try:
if count:
int(count)
except:
raise TwitterError("Count must be an integer")
parameters = {}
if count:
parameters['count'] = count
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if user:
url = 'http://twitter.com/statuses/user_timeline/%s.json' % user
elif not user and not self._username:
raise TwitterError("User must be specified if API is not authenticated.")
else:
url = 'http://twitter.com/statuses/user_timeline.json'
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetStatus(self, id):
'''Returns a single status message.
The twitter.Api instance must be authenticated if the status message is private.
Args:
id: The numerical ID of the status you're trying to retrieve.
Returns:
A twitter.Status instance representing that status message
'''
try:
if id:
long(id)
except:
raise TwitterError("id must be an long integer")
url = 'http://twitter.com/statuses/show/%s.json' % id
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def DestroyStatus(self, id):
'''Destroys the status specified by the required ID parameter.
The twitter.Api instance must be authenticated and thee
authenticating user must be the author of the specified status.
Args:
id: The numerical ID of the status you're trying to destroy.
Returns:
A twitter.Status instance representing the destroyed status message
'''
try:
if id:
long(id)
except:
raise TwitterError("id must be an integer")
url = 'http://twitter.com/statuses/destroy/%s.json' % id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def PostUpdate(self, status, in_reply_to_status_id=None):
'''Post a twitter status message from the authenticated user.
The twitter.Api instance must be authenticated.
Args:
status:
The message text to be posted. Must be less than or equal to
140 characters.
in_reply_to_status_id:
The ID of an existing status that the status to be posted is
in reply to. This implicitly sets the in_reply_to_user_id
attribute of the resulting status to the user ID of the
message being replied to. Invalid/missing status IDs will be
ignored. [Optional]
Returns:
A twitter.Status instance representing the message posted.
'''
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = 'http://twitter.com/statuses/update.json'
if len(status) > CHARACTER_LIMIT:
raise TwitterError("Text must be less than or equal to %d characters. "
"Consider using PostUpdates." % CHARACTER_LIMIT)
data = {'status': status}
if in_reply_to_status_id:
data['in_reply_to_status_id'] = in_reply_to_status_id
json = self._FetchUrl(url, post_data=data)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def PostUpdates(self, status, continuation=None, **kwargs):
'''Post one or more twitter status messages from the authenticated user.
Unlike api.PostUpdate, this method will post multiple status updates
if the message is longer than 140 characters.
The twitter.Api instance must be authenticated.
Args:
status:
The message text to be posted. May be longer than 140 characters.
continuation:
The character string, if any, to be appended to all but the
last message. Note that Twitter strips trailing '...' strings
from messages. Consider using the unicode \u2026 character
(horizontal ellipsis) instead. [Defaults to None]
**kwargs:
See api.PostUpdate for a list of accepted parameters.
Returns:
A of list twitter.Status instance representing the messages posted.
'''
results = list()
if continuation is None:
continuation = ''
line_length = CHARACTER_LIMIT - len(continuation)
lines = textwrap.wrap(status, line_length)
for line in lines[0:-1]:
results.append(self.PostUpdate(line + continuation, **kwargs))
results.append(self.PostUpdate(lines[-1], **kwargs))
return results
def GetReplies(self, since=None, since_id=None, page=None):
'''Get a sequence of status messages representing the 20 most recent
replies (status updates prefixed with @username) to the authenticating
user.
Args:
page:
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.Status instances, one for each reply to the user.
'''
url = 'http://twitter.com/statuses/replies.json'
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [Status.NewFromJsonDict(x) for x in data]
def GetFriends(self, user=None, page=None):
'''Fetch the sequence of twitter.User instances, one for each friend.
Args:
user: the username or id of the user whose friends you are fetching. If
not specified, defaults to the authenticated user. [optional]
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances, one for each friend
'''
if not self._username:
raise TwitterError("twitter.Api instance must be authenticated")
if user:
url = 'http://twitter.com/statuses/friends/%s.json' % user
else:
url = 'http://twitter.com/statuses/friends.json'
parameters = {}
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [User.NewFromJsonDict(x) for x in data]
def GetFollowers(self, page=None):
'''Fetch the sequence of twitter.User instances, one for each follower
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances, one for each follower
'''
if not self._username:
raise TwitterError("twitter.Api instance must be authenticated")
url = 'http://twitter.com/statuses/followers.json'
parameters = {}
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [User.NewFromJsonDict(x) for x in data]
def GetFeatured(self):
'''Fetch the sequence of twitter.User instances featured on twitter.com
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances
'''
url = 'http://twitter.com/statuses/featured.json'
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [User.NewFromJsonDict(x) for x in data]
def GetUser(self, user):
'''Returns a single user.
The twitter.Api instance must be authenticated.
Args:
user: The username or id of the user to retrieve.
Returns:
A twitter.User instance representing that user
'''
url = 'http://twitter.com/users/show/%s.json' % user
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def GetDirectMessages(self, since=None, since_id=None, page=None):
'''Returns a list of the direct messages sent to the authenticating user.
The twitter.Api instance must be authenticated.
Args:
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [optional]
since_id:
Returns only public statuses with an ID greater than (that is,
more recent than) the specified ID. [Optional]
Returns:
A sequence of twitter.DirectMessage instances
'''
url = 'http://twitter.com/direct_messages.json'
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return [DirectMessage.NewFromJsonDict(x) for x in data]
def PostDirectMessage(self, user, text):
'''Post a twitter direct message from the authenticated user
The twitter.Api instance must be authenticated.
Args:
user: The ID or screen name of the recipient user.
text: The message text to be posted. Must be less than 140 characters.
Returns:
A twitter.DirectMessage instance representing the message posted
'''
if not self._username:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = 'http://twitter.com/direct_messages/new.json'
data = {'text': text, 'user': user}
json = self._FetchUrl(url, post_data=data)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return DirectMessage.NewFromJsonDict(data)
def DestroyDirectMessage(self, id):
'''Destroys the direct message specified in the required ID parameter.
The twitter.Api instance must be authenticated, and the
authenticating user must be the recipient of the specified direct
message.
Args:
id: The id of the direct message to be destroyed
Returns:
A twitter.DirectMessage instance representing the message destroyed
'''
url = 'http://twitter.com/direct_messages/destroy/%s.json' % id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return DirectMessage.NewFromJsonDict(data)
def CreateFriendship(self, user):
'''Befriends the user specified in the user parameter as the authenticating user.
The twitter.Api instance must be authenticated.
Args:
The ID or screen name of the user to befriend.
Returns:
A twitter.User instance representing the befriended user.
'''
url = 'http://twitter.com/friendships/create/%s.json' % user
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def DestroyFriendship(self, user):
'''Discontinues friendship with the user specified in the user parameter.
The twitter.Api instance must be authenticated.
Args:
The ID or screen name of the user with whom to discontinue friendship.
Returns:
A twitter.User instance representing the discontinued friend.
'''
url = 'http://twitter.com/friendships/destroy/%s.json' % user
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def CreateFavorite(self, status):
'''Favorites the status specified in the status parameter as the authenticating user.
Returns the favorite status when successful.
The twitter.Api instance must be authenticated.
Args:
The twitter.Status instance to mark as a favorite.
Returns:
A twitter.Status instance representing the newly-marked favorite.
'''
url = 'http://twitter.com/favorites/create/%s.json' % status.id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def DestroyFavorite(self, status):
'''Un-favorites the status specified in the ID parameter as the authenticating user.
Returns the un-favorited status in the requested format when successful.
The twitter.Api instance must be authenticated.
Args:
The twitter.Status to unmark as a favorite.
Returns:
A twitter.Status instance representing the newly-unmarked favorite.
'''
url = 'http://twitter.com/favorites/destroy/%s.json' % status.id
json = self._FetchUrl(url, post_data={})
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return Status.NewFromJsonDict(data)
def GetUserByEmail(self, email):
'''Returns a single user by email address.
Args:
email: The email of the user to retrieve.
Returns:
A twitter.User instance representing that user
'''
url = 'http://twitter.com/users/show.json?email=%s' % email
json = self._FetchUrl(url)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return User.NewFromJsonDict(data)
def SetCredentials(self, username, password):
'''Set the username and password for this instance
Args:
username: The twitter username.
password: The twitter password.
'''
self._username = username
self._password = password
def ClearCredentials(self):
'''Clear the username and password for this instance
'''
self._username = None
self._password = None
def SetCache(self, cache):
'''Override the default cache. Set to None to prevent caching.
Args:
cache: an instance that supports the same API as the twitter._FileCache
'''
self._cache = cache
def SetUrllib(self, urllib):
'''Override the default urllib implementation.
Args:
urllib: an instance that supports the same API as the urllib2 module
'''
self._urllib = urllib
def SetCacheTimeout(self, cache_timeout):
'''Override the default cache timeout.
Args:
cache_timeout: time, in seconds, that responses should be reused.
'''
self._cache_timeout = cache_timeout
def SetUserAgent(self, user_agent):
'''Override the default user agent
Args:
user_agent: a string that should be send to the server as the User-agent
'''
self._request_headers['User-Agent'] = user_agent
def SetXTwitterHeaders(self, client, url, version):
'''Set the X-Twitter HTTP headers that will be sent to the server.
Args:
client:
The client name as a string. Will be sent to the server as
the 'X-Twitter-Client' header.
url:
The URL of the meta.xml as a string. Will be sent to the server
as the 'X-Twitter-Client-URL' header.
version:
The client version as a string. Will be sent to the server
as the 'X-Twitter-Client-Version' header.
'''
self._request_headers['X-Twitter-Client'] = client
self._request_headers['X-Twitter-Client-URL'] = url
self._request_headers['X-Twitter-Client-Version'] = version
def SetSource(self, source):
'''Suggest the "from source" value to be displayed on the Twitter web site.
The value of the 'source' parameter must be first recognized by
the Twitter server. New source values are authorized on a case by
case basis by the Twitter development team.
Args:
source:
The source name as a string. Will be sent to the server as
the 'source' parameter.
'''
self._default_params['source'] = source
def _BuildUrl(self, url, path_elements=None, extra_params=None):
# Break url into consituent parts
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
# Add any additional path elements to the path
if path_elements:
# Filter out the path elements that have a value of None
p = [i for i in path_elements if i]
if not path.endswith('/'):
path += '/'
path += '/'.join(p)
# Add any additional query parameters to the query string
if extra_params and len(extra_params) > 0:
extra_query = self._EncodeParameters(extra_params)
# Add it to the existing query
if query:
query += '&' + extra_query
else:
query = extra_query
# Return the rebuilt URL
return urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
def _InitializeRequestHeaders(self, request_headers):
if request_headers:
self._request_headers = request_headers
else:
self._request_headers = {}
def _InitializeUserAgent(self):
user_agent = 'Python-urllib/%s (python-twitter/%s)' % \
(self._urllib.__version__, __version__)
self.SetUserAgent(user_agent)
def _InitializeDefaultParameters(self):
self._default_params = {}
def _AddAuthorizationHeader(self, username, password):
if username and password:
basic_auth = base64.encodestring('%s:%s' % (username, password))[:-1]
self._request_headers['Authorization'] = 'Basic %s' % basic_auth
def _RemoveAuthorizationHeader(self):
if self._request_headers and 'Authorization' in self._request_headers:
del self._request_headers['Authorization']
def _GetOpener(self, url, username=None, password=None):
if username and password:
self._AddAuthorizationHeader(username, password)
handler = self._urllib.HTTPBasicAuthHandler()
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
handler.add_password(Api._API_REALM, netloc, username, password)
opener = self._urllib.build_opener(handler)
else:
opener = self._urllib.build_opener()
opener.addheaders = self._request_headers.items()
return opener
def _Encode(self, s):
if self._input_encoding:
return unicode(s, self._input_encoding).encode('utf-8')
else:
return unicode(s).encode('utf-8')
def _EncodeParameters(self, parameters):
'''Return a string in key=value&key=value form
Values of None are not included in the output string.
Args:
parameters:
A dict of (key, value) tuples, where value is encoded as
specified by self._encoding
Returns:
A URL-encoded string in "key=value&key=value" form
'''
if parameters is None:
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None]))
def _EncodePostData(self, post_data):
'''Return a string in key=value&key=value form
Values are assumed to be encoded in the format specified by self._encoding,
and are subsequently URL encoded.
Args:
post_data:
A dict of (key, value) tuples, where value is encoded as
specified by self._encoding
Returns:
A URL-encoded string in "key=value&key=value" form
'''
if post_data is None:
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()]))
def _CheckForTwitterError(self, data):
"""Raises a TwitterError if twitter returns an error message.
Args:
data: A python dict created from the Twitter json response
Raises:
TwitterError wrapping the twitter error message if one exists.
"""
# Twitter errors are relatively unlikely, so it is faster
# to check first, rather than try and catch the exception
if 'error' in data:
raise TwitterError(data['error'])
def _FetchUrl(self,
url,
post_data=None,
parameters=None,
no_cache=None):
'''Fetch a URL, optionally caching for a specified time.
Args:
url: The URL to retrieve
post_data:
A dict of (str, unicode) key/value pairs. If set, POST will be used.
parameters:
A dict whose key/value pairs should encoded and added
to the query string. [OPTIONAL]
no_cache: If true, overrides the cache on the current request
Returns:
A string containing the body of the response.
'''
# Build the extra parameters dict
extra_params = {}
if self._default_params:
extra_params.update(self._default_params)
if parameters:
extra_params.update(parameters)
# Add key/value parameters to the query string of the url
url = self._BuildUrl(url, extra_params=extra_params)
# Get a url opener that can handle basic auth
opener = self._GetOpener(url, username=self._username, password=self._password)
encoded_post_data = self._EncodePostData(post_data)
# Open and return the URL immediately if we're not going to cache
if encoded_post_data or no_cache or not self._cache or not self._cache_timeout:
url_data = opener.open(url, encoded_post_data).read()
opener.close()
else:
# Unique keys are a combination of the url and the username
if self._username:
key = self._username + ':' + url
else:
key = url
# See if it has been cached before
last_cached = self._cache.GetCachedTime(key)
# If the cached version is outdated then fetch another and store it
if not last_cached or time.time() >= last_cached + self._cache_timeout:
url_data = opener.open(url, encoded_post_data).read()
opener.close()
self._cache.Set(key, url_data)
else:
url_data = self._cache.Get(key)
# Always return the latest version
return url_data
class _FileCacheError(Exception):
'''Base exception class for FileCache related errors'''
class _FileCache(object):
DEPTH = 3
def __init__(self,root_directory=None):
self._InitializeRootDirectory(root_directory)
def Get(self,key):
path = self._GetPath(key)
if os.path.exists(path):
return open(path).read()
else:
return None
def Set(self,key,data):
path = self._GetPath(key)
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise _FileCacheError('%s exists but is not a directory' % directory)
temp_fd, temp_path = tempfile.mkstemp()
temp_fp = os.fdopen(temp_fd, 'w')
temp_fp.write(data)
temp_fp.close()
if not path.startswith(self._root_directory):
raise _FileCacheError('%s does not appear to live under %s' %
(path, self._root_directory))
if os.path.exists(path):
os.remove(path)
os.rename(temp_path, path)
def Remove(self,key):
path = self._GetPath(key)
if not path.startswith(self._root_directory):
raise _FileCacheError('%s does not appear to live under %s' %
(path, self._root_directory ))
if os.path.exists(path):
os.remove(path)
def GetCachedTime(self,key):
path = self._GetPath(key)
if os.path.exists(path):
return os.path.getmtime(path)
else:
return None
def _GetUsername(self):
'''Attempt to find the username in a cross-platform fashion.'''
try:
return os.getenv('USER') or \
os.getenv('LOGNAME') or \
os.getenv('USERNAME') or \
os.getlogin() or \
'nobody'
except (IOError, OSError), e:
return 'nobody'
def _GetTmpCachePath(self):
username = self.name()
cache_directory = 'python.cache_' + username
return os.path.join(tempfile.gettempdir(), cache_directory)
def _InitializeRootDirectory(self, root_directory):
if not root_directory:
root_directory = self._GetTmpCachePath()
root_directory = os.path.abspath(root_directory)
if not os.path.exists(root_directory):
os.mkdir(root_directory)
if not os.path.isdir(root_directory):
raise _FileCacheError('%s exists but is not a directory' %
root_directory)
self._root_directory = root_directory
def _GetPath(self,key):
try:
hashed_key = md5(key).hexdigest()
except TypeError:
hashed_key = md5.new(key).hexdigest()
return os.path.join(self._root_directory,
self._GetPrefix(hashed_key),
hashed_key)
def _GetPrefix(self,hashed_key):
return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
| Python |
from django.conf.urls.defaults import *
from django.contrib.auth import views as auth_views
from views import *
from views2 import *
from twit import *
urlpatterns =patterns(
'',
#url( r'^login/$',
# auth_views.login,
# {'template_name': 'haco/login.html',
# 'redirect_field_name': report},
# name='auth_login'),
#(r'^$',
# 'django.views.generic.simple.direct_to_template',
# {'template': 'index.html'}),
#'booklist.views', (r'^list', 'list'),
#'haco.views',
#(r'^$', 'login'),
#url(r'^$', login),
url(r'^report/$', report),
url(r'^record/$', record),
url(r'^matrix/$', matrix),
url(r'^map/$', map),
url(r'^test/$', test),
url(r'^feed/$', feed),
url(r'^csv/$',csv),
url(r'^repo_all/$',repo_all),
url(r'^cron/twitBot/$',twitBot),
)
| Python |
# -*- coding: utf-8 -*-
from decimal import *
from math import *
def v2W(volt):
if float(volt) < 0:
return -1
else:
watt = (float(volt) * 1100.0 / 1024.0) * 3000 / (0.9 * 100) / 1000 * 100
watt = Decimal(str(watt)).quantize(Decimal('.0'), rounding=ROUND_HALF_UP)
return watt
def v2L(volt):
if float(volt) <= 0:
return -1
else:
CON = 0.81
OFFS = 1.22
current = (((float(volt) * (1100.0 / 1024.0) )/ 1000.0) / 11.0) * 1000.0
light = pow(10.0, (CON * log(current,10) + OFFS));
light = Decimal(str(light)).quantize(Decimal('.0'), rounding=ROUND_HALF_UP)
return light
def v2T(volt):
if float(volt) < 0:
return -1
else:
temp = (float(volt) / 1024.0 * 1100.0 / 6.25) + (-424.0 / 6.25)
temp = Decimal(str(temp)).quantize(Decimal('.0'), rounding=ROUND_HALF_UP)
return temp
| Python |
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from haco.models import *
from haco.jsTime import *
import logging
import twython
from datetime import *
def twitBot( request):
mes ="<html><head></head><body>"
api = apimake()
t = api.getUserMentions(count="20")
for e in t:
q = Mention.all()
q =q.filter('postUser',e['user']['screen_name'])
q =q.filter('postText',e['text'])
q =q.filter('postDate >=',datetime.strptime(e['created_at'], '%a %b %d %H:%M:%S +0000 %Y')+timedelta(hours=9))
if len(q):
break
else:
# post(makeReply(e))
directMessage(e['user']['screen_name'],makeReply(e))
save(e)
return HttpResponse( "OK")
def post(msg):
api = apimake()
api.updateStatus(msg)
def directMessage(user, msg):
api = apimake()
api.sendDirectMessage(user, msg)
def save( e):
mention =Mention()
mention.postUser =e['user']['screen_name']
mention.postText =e['text']
mention.postDate =datetime.strptime(e['created_at'], '%a %b %d %H:%M:%S +0000 %Y')+timedelta(hours=9)
mention.put()
def makeReply( e):
#parse text and generate reply text
return "OK I'v got your message"
def apimake():
return twython.setup(authtype="Basic",username="user",password="pass")
| Python |
#!/usr/bin/python
"""
NOTE: Tango is being renamed to Twython; all basic strings have been changed below, but there's still work ongoing in this department.
Twython is an up-to-date library for Python that wraps the Twitter API.
Other Python Twitter libraries seem to have fallen a bit behind, and
Twitter's API has evolved a bit. Here's hoping this helps.
TODO: OAuth, Streaming API?
Questions, comments? ryan@venodesigns.net
"""
import httplib, urllib, urllib2, mimetypes, mimetools
from urllib2 import HTTPError
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
__version__ = "0.8.0.1"
"""Twython - Easy Twitter utilities in Python"""
try:
import simplejson
except ImportError:
try:
import json as simplejson
except:
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
try:
import oauth
except ImportError:
pass
class TangoError(Exception):
def __init__(self, msg, error_code=None):
self.msg = msg
if error_code == 400:
raise APILimit(msg)
def __str__(self):
return repr(self.msg)
class APILimit(TangoError):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class setup:
def __init__(self, authtype = "OAuth", username = None, password = None, oauth_keys = None, headers = None):
self.authtype = authtype
self.authenticated = False
self.username = username
self.password = password
self.oauth_keys = oauth_keys
if self.username is not None and self.password is not None:
if self.authtype == "OAuth":
self.request_token_url = 'https://twitter.com/oauth/request_token'
self.access_token_url = 'https://twitter.com/oauth/access_token'
self.authorization_url = 'http://twitter.com/oauth/authorize'
self.signin_url = 'http://twitter.com/oauth/authenticate'
# Do OAuth type stuff here - how should this be handled? Seems like a framework question...
elif self.authtype == "Basic":
self.auth_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
self.auth_manager.add_password(None, "http://twitter.com", self.username, self.password)
self.handler = urllib2.HTTPBasicAuthHandler(self.auth_manager)
self.opener = urllib2.build_opener(self.handler)
if headers is not None:
self.opener.addheaders = [('User-agent', headers)]
try:
simplejson.load(self.opener.open("http://twitter.com/account/verify_credentials.json"))
self.authenticated = True
except HTTPError, e:
raise TangoError("Authentication failed with your provided credentials. Try again? (%s failure)" % `e.code`, e.code)
# OAuth functions; shortcuts for verifying the credentials.
def fetch_response_oauth(self, oauth_request):
pass
def get_unauthorized_request_token(self):
pass
def get_authorization_url(self, token):
pass
def exchange_tokens(self, request_token):
pass
# URL Shortening function huzzah
def shortenURL(self, url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"):
try:
return urllib2.urlopen(shortener + "?" + urllib.urlencode({query: url_to_shorten})).read()
except HTTPError, e:
raise TangoError("shortenURL() failed with a %s error code." % `e.code`)
def constructApiURL(self, base_url, params):
return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.iteritems()])
def getRateLimitStatus(self, rate_for = "requestingIP"):
try:
if rate_for == "requestingIP":
return simplejson.load(urllib2.urlopen("http://twitter.com/account/rate_limit_status.json"))
else:
if self.authenticated is True:
return simplejson.load(self.opener.open("http://twitter.com/account/rate_limit_status.json"))
else:
raise TangoError("You need to be authenticated to check a rate limit status on an account.")
except HTTPError, e:
raise TangoError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % `e.code`, e.code)
def getPublicTimeline(self):
try:
return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/public_timeline.json"))
except HTTPError, e:
raise TangoError("getPublicTimeline() failed with a %s error code." % `e.code`)
def getFriendsTimeline(self, **kwargs):
if self.authenticated is True:
try:
friendsTimelineURL = self.constructApiURL("http://twitter.com/statuses/friends_timeline.json", kwargs)
return simplejson.load(self.opener.open(friendsTimelineURL))
except HTTPError, e:
raise TangoError("getFriendsTimeline() failed with a %s error code." % `e.code`)
else:
raise TangoError("getFriendsTimeline() requires you to be authenticated.")
def getUserTimeline(self, id = None, **kwargs):
if id is not None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False:
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + id + ".json", kwargs)
elif id is None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False and self.authenticated is True:
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + self.username + ".json", kwargs)
else:
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline.json", kwargs)
try:
# We do our custom opener if we're authenticated, as it helps avoid cases where it's a protected user
if self.authenticated is True:
return simplejson.load(self.opener.open(userTimelineURL))
else:
return simplejson.load(urllib2.urlopen(userTimelineURL))
except HTTPError, e:
raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline."
% `e.code`, e.code)
def getUserMentions(self, **kwargs):
if self.authenticated is True:
try:
mentionsFeedURL = self.constructApiURL("http://twitter.com/statuses/mentions.json", kwargs)
return simplejson.load(self.opener.open(mentionsFeedURL))
except HTTPError, e:
raise TangoError("getUserMentions() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getUserMentions() requires you to be authenticated.")
def showStatus(self, id):
try:
if self.authenticated is True:
return simplejson.load(self.opener.open("http://twitter.com/statuses/show/%s.json" % id))
else:
return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/show/%s.json" % id))
except HTTPError, e:
raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline."
% `e.code`, e.code)
def updateStatus(self, status, in_reply_to_status_id = None):
if self.authenticated is True:
if len(list(status)) > 140:
raise TangoError("This status message is over 140 characters. Trim it down!")
try:
return simplejson.load(self.opener.open("http://twitter.com/statuses/update.json?", urllib.urlencode({"status": status, "in_reply_to_status_id": in_reply_to_status_id})))
except HTTPError, e:
raise TangoError("updateStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateStatus() requires you to be authenticated.")
def destroyStatus(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/status/destroy/%s.json", "POST" % id))
except HTTPError, e:
raise TangoError("destroyStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyStatus() requires you to be authenticated.")
def endSession(self):
if self.authenticated is True:
try:
self.opener.open("http://twitter.com/account/end_session.json", "")
self.authenticated = False
except HTTPError, e:
raise TangoError("endSession failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You can't end a session when you're not authenticated to begin with.")
def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1"):
if self.authenticated is True:
apiURL = "http://twitter.com/direct_messages.json?page=" + page
if since_id is not None:
apiURL += "&since_id=" + since_id
if max_id is not None:
apiURL += "&max_id=" + max_id
if count is not None:
apiURL += "&count=" + count
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TangoError("getDirectMessages() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getDirectMessages() requires you to be authenticated.")
def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1"):
if self.authenticated is True:
apiURL = "http://twitter.com/direct_messages/sent.json?page=" + page
if since_id is not None:
apiURL += "&since_id=" + since_id
if max_id is not None:
apiURL += "&max_id=" + max_id
if count is not None:
apiURL += "&count=" + count
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TangoError("getSentMessages() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getSentMessages() requires you to be authenticated.")
def sendDirectMessage(self, user, text):
if self.authenticated is True:
if len(list(text)) < 140:
try:
return self.opener.open("http://twitter.com/direct_messages/new.json", urllib.urlencode({"user": user, "text": text}))
except HTTPError, e:
raise TangoError("sendDirectMessage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("Your message must not be longer than 140 characters")
else:
raise TangoError("You must be authenticated to send a new direct message.")
def destroyDirectMessage(self, id):
if self.authenticated is True:
try:
return self.opener.open("http://twitter.com/direct_messages/destroy/%s.json" % id, "")
except HTTPError, e:
raise TangoError("destroyDirectMessage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You must be authenticated to destroy a direct message.")
def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false"):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/friendships/create/" + id + ".json" + "?follow=" + follow
if user_id is not None:
apiURL = "http://twitter.com/friendships/create.json?user_id=" + user_id + "&follow=" + follow
if screen_name is not None:
apiURL = "http://twitter.com/friendships/create.json?screen_name=" + screen_name + "&follow=" + follow
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
# Rate limiting is done differently here for API reasons...
if e.code == 403:
raise TangoError("You've hit the update limit for this method. Try again in 24 hours.")
raise TangoError("createFriendship() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createFriendship() requires you to be authenticated.")
def destroyFriendship(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/friendships/destroy/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/friendships/destroy.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/friendships/destroy.json?screen_name=" + screen_name
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TangoError("destroyFriendship() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyFriendship() requires you to be authenticated.")
def checkIfFriendshipExists(self, user_a, user_b):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/friendships/exists.json", urllib.urlencode({"user_a": user_a, "user_b": user_b})))
except HTTPError, e:
raise TangoError("checkIfFriendshipExists() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("checkIfFriendshipExists(), oddly, requires that you be authenticated.")
def updateDeliveryDevice(self, device_name = "none"):
if self.authenticated is True:
try:
return self.opener.open("http://twitter.com/account/update_delivery_device.json?", urllib.urlencode({"device": device_name}))
except HTTPError, e:
raise TangoError("updateDeliveryDevice() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateDeliveryDevice() requires you to be authenticated.")
def updateProfileColors(self, **kwargs):
if self.authenticated is True:
try:
return self.opener.open(self.constructApiURL("http://twitter.com/account/update_profile_colors.json?", kwargs))
except HTTPError, e:
raise TangoError("updateProfileColors() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateProfileColors() requires you to be authenticated.")
def updateProfile(self, name = None, email = None, url = None, location = None, description = None):
if self.authenticated is True:
useAmpersands = False
updateProfileQueryString = ""
if name is not None:
if len(list(name)) < 20:
updateProfileQueryString += "name=" + name
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 20 for all usernames. Try again.")
if email is not None and "@" in email:
if len(list(email)) < 40:
if useAmpersands is True:
updateProfileQueryString += "&email=" + email
else:
updateProfileQueryString += "email=" + email
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.")
if url is not None:
if len(list(url)) < 100:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"url": url})
else:
updateProfileQueryString += urllib.urlencode({"url": url})
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 100 for all urls. Try again.")
if location is not None:
if len(list(location)) < 30:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"location": location})
else:
updateProfileQueryString += urllib.urlencode({"location": location})
useAmpersands = True
else:
raise TangoError("Twitter has a character limit of 30 for all locations. Try again.")
if description is not None:
if len(list(description)) < 160:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"description": description})
else:
updateProfileQueryString += urllib.urlencode({"description": description})
else:
raise TangoError("Twitter has a character limit of 160 for all descriptions. Try again.")
if updateProfileQueryString != "":
try:
return self.opener.open("http://twitter.com/account/update_profile.json?", updateProfileQueryString)
except HTTPError, e:
raise TangoError("updateProfile() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("updateProfile() requires you to be authenticated.")
def getFavorites(self, page = "1"):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/favorites.json?page=" + page))
except HTTPError, e:
raise TangoError("getFavorites() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getFavorites() requires you to be authenticated.")
def createFavorite(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/favorites/create/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("createFavorite() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createFavorite() requires you to be authenticated.")
def destroyFavorite(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/favorites/destroy/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("destroyFavorite() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyFavorite() requires you to be authenticated.")
def notificationFollow(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/notifications/follow/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/notifications/follow/follow.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/notifications/follow/follow.json?screen_name=" + screen_name
try:
return simplejson.load(self.opener.open(apiURL, ""))
except HTTPError, e:
raise TangoError("notificationFollow() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("notificationFollow() requires you to be authenticated.")
def notificationLeave(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/notifications/leave/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/notifications/leave/leave.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/notifications/leave/leave.json?screen_name=" + screen_name
try:
return simplejson.load(self.opener.open(apiURL, ""))
except HTTPError, e:
raise TangoError("notificationLeave() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("notificationLeave() requires you to be authenticated.")
def getFriendsIDs(self, id = None, user_id = None, screen_name = None, page = "1"):
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/friends/ids/" + id + ".json" + "?page=" + page
if user_id is not None:
apiURL = "http://twitter.com/friends/ids.json?user_id=" + user_id + "&page=" + page
if screen_name is not None:
apiURL = "http://twitter.com/friends/ids.json?screen_name=" + screen_name + "&page=" + page
try:
return simplejson.load(urllib2.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getFriendsIDs() failed with a %s error code." % `e.code`, e.code)
def getFollowersIDs(self, id = None, user_id = None, screen_name = None, page = "1"):
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/followers/ids/" + id + ".json" + "?page=" + page
if user_id is not None:
apiURL = "http://twitter.com/followers/ids.json?user_id=" + user_id + "&page=" + page
if screen_name is not None:
apiURL = "http://twitter.com/followers/ids.json?screen_name=" + screen_name + "&page=" + page
try:
return simplejson.load(urllib2.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getFollowersIDs() failed with a %s error code." % `e.code`, e.code)
def createBlock(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/create/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("createBlock() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createBlock() requires you to be authenticated.")
def destroyBlock(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/destroy/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("destroyBlock() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroyBlock() requires you to be authenticated.")
def checkIfBlockExists(self, id = None, user_id = None, screen_name = None):
apiURL = ""
if id is not None:
apiURL = "http://twitter.com/blocks/exists/" + id + ".json"
if user_id is not None:
apiURL = "http://twitter.com/blocks/exists.json?user_id=" + user_id
if screen_name is not None:
apiURL = "http://twitter.com/blocks/exists.json?screen_name=" + screen_name
try:
return simplejson.load(urllib2.urlopen(apiURL))
except HTTPError, e:
raise TangoError("checkIfBlockExists() failed with a %s error code." % `e.code`, e.code)
def getBlocking(self, page = "1"):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking.json?page=" + page))
except HTTPError, e:
raise TangoError("getBlocking() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getBlocking() requires you to be authenticated")
def getBlockedIDs(self):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking/ids.json"))
except HTTPError, e:
raise TangoError("getBlockedIDs() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getBlockedIDs() requires you to be authenticated.")
def searchTwitter(self, search_query, **kwargs):
searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.urlencode({"q": search_query})
try:
return simplejson.load(urllib2.urlopen(searchURL))
except HTTPError, e:
raise TangoError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code)
def getCurrentTrends(self, excludeHashTags = False):
apiURL = "http://search.twitter.com/trends/current.json"
if excludeHashTags is True:
apiURL += "?exclude=hashtags"
try:
return simplejson.load(urllib.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getCurrentTrends() failed with a %s error code." % `e.code`, e.code)
def getDailyTrends(self, date = None, exclude = False):
apiURL = "http://search.twitter.com/trends/daily.json"
questionMarkUsed = False
if date is not None:
apiURL += "?date=" + date
questionMarkUsed = True
if exclude is True:
if questionMarkUsed is True:
apiURL += "&exclude=hashtags"
else:
apiURL += "?exclude=hashtags"
try:
return simplejson.load(urllib.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getDailyTrends() failed with a %s error code." % `e.code`, e.code)
def getWeeklyTrends(self, date = None, exclude = False):
apiURL = "http://search.twitter.com/trends/daily.json"
questionMarkUsed = False
if date is not None:
apiURL += "?date=" + date
questionMarkUsed = True
if exclude is True:
if questionMarkUsed is True:
apiURL += "&exclude=hashtags"
else:
apiURL += "?exclude=hashtags"
try:
return simplejson.load(urllib.urlopen(apiURL))
except HTTPError, e:
raise TangoError("getWeeklyTrends() failed with a %s error code." % `e.code`, e.code)
def getSavedSearches(self):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches.json"))
except HTTPError, e:
raise TangoError("getSavedSearches() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("getSavedSearches() requires you to be authenticated.")
def showSavedSearch(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/show/" + id + ".json"))
except HTTPError, e:
raise TangoError("showSavedSearch() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("showSavedSearch() requires you to be authenticated.")
def createSavedSearch(self, query):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/create.json?query=" + query, ""))
except HTTPError, e:
raise TangoError("createSavedSearch() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("createSavedSearch() requires you to be authenticated.")
def destroySavedSearch(self, id):
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/destroy/" + id + ".json", ""))
except HTTPError, e:
raise TangoError("destroySavedSearch() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("destroySavedSearch() requires you to be authenticated.")
# The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set.
def updateProfileBackgroundImage(self, filename, tile="true"):
if self.authenticated is True:
try:
files = [("image", filename, open(filename).read())]
fields = []
content_type, body = self.encode_multipart_formdata(fields, files)
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
r = urllib2.Request("http://twitter.com/account/update_profile_background_image.json?tile=" + tile, body, headers)
return self.opener.open(r).read()
except HTTPError, e:
raise TangoError("updateProfileBackgroundImage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You realize you need to be authenticated to change a background image, right?")
def updateProfileImage(self, filename):
if self.authenticated is True:
try:
files = [("image", filename, open(filename).read())]
fields = []
content_type, body = self.encode_multipart_formdata(fields, files)
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
r = urllib2.Request("http://twitter.com/account/update_profile_image.json", body, headers)
return self.opener.open(r).read()
except HTTPError, e:
raise TangoError("updateProfileImage() failed with a %s error code." % `e.code`, e.code)
else:
raise TangoError("You realize you need to be authenticated to change a profile image, right?")
def encode_multipart_formdata(self, fields, files):
BOUNDARY = mimetools.choose_boundary()
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % self.get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def get_content_type(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
| Python |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
from django.template import Context, RequestContext, loader
from django.views.generic.list_detail import object_list
from django.views.generic.simple import direct_to_template
from django.forms.formsets import formset_factory
from haco.models import *
from httpauth import *
from haco.jsTime import *
from haco.convert import *
import logging
import time
import csv
@http_login_required()
def record( request):
logging.info(request.user.username + ":" + request.GET['pnum'])
mes ="<html><body>"
haco =Haco(key_name= now().strftime("%Y-%m-%d")
+ ":" + str(request.GET['pnum'])
+ ":" + request.user.username)
haco.user =request.user
haco.username =request.user.username
haco.date = today()
if request.GET['pnum'] == "0":
if now().strftime("%H") == "23":
haco.date = tomorrow()
haco.timestamp = now()
mes +=request.user.username+"<br/>"
if request.GET.has_key( 'pnum'):
haco.pnum =int( request.GET['pnum'])
mes +="pnum:"+str(haco.pnum)+"<br/>"
if request.GET.has_key( 'temp'):
haco.temp =float( v2T(request.GET['temp']))
mes +="temp:"+str(haco.temp)+"<br/>"
if request.GET.has_key( 'light'):
haco.light =float( v2L(request.GET['light']))
mes +="light:"+str(haco.light)+"<br/>"
if request.GET.has_key( 'watt'):
haco.watt =float( v2W(request.GET['watt']))
mes +="watt:"+str(haco.watt)+"<br/>"
mes +="</body></html>"
haco.put()
return HttpResponse( mes)
@login_required()
def report( request):
delta = 0
if request.GET.has_key( 'delta'):
delta = int(request.GET['delta'])
day = someday(delta)
else:
day = today()
t_list = [-1.0] * 144
l_list = [-1.0] * 144
w_list = [-1.0] * 144
q =Haco.all()
q =q.filter( 'user', request.user)
q =q.filter( 'date', day)
q =q.order( 'pnum')
for h in q:
t_list[h.pnum] = h.temp
l_list[h.pnum] = h.light
w_list[h.pnum] = h.watt
if max(w_list) < 200:
w_scale = 200
w_line = 25
else:
w_scale = 1000
w_line = 20
return direct_to_template(request, 'report.html',
{
'day' : day.strftime("%m/%d"),
'delta' : delta,
'prev_url' : "./?delta="+str(delta -1 ),
'next_url' : "./?delta="+str(delta +1 ),
't_list': chartmake(t_list),
'l_list': chartmake(l_list),
'w_list': chartmake(w_list),
'w_scale': w_scale,
'w_line': w_line,
})
def chartmake( a_list):
chart =""
for data in a_list:
chart += str(data) +","
chart = chart[0:len(chart)-1]
return chart
@login_required()
def matrix( request):
if request.GET.has_key( 'delta'):
day = someday(int(request.GET['delta']))
else:
day = today()
q =Haco.all()
q =q.filter( 'user', request.user)
q =q.filter( 'date', day)
q =q.order( 'pnum')
return object_list( request, q)
@login_required
def map( request):
return direct_to_template(request, 'map.html',
{
'ido': str(36.054148),
'kdo': str(140.140033),
})
@login_required
def feed( request):
delta = 0
if request.GET.has_key( 'delta'):
delta = int(request.GET['delta'])
day = someday(delta)
else:
day = today()
q =Haco.all()
q =q.filter( 'user', request.user)
q =q.filter( 'date', day)
q =q.order( 'pnum')
return object_list( request, queryset=q ,template_name="feed.xml"
,extra_context = {'date':day.strftime("%Y-%m-%d"),
'username':request.user.username}
,mimetype="application/xml")
@login_required
def csv( request):
delta = 0
if request.GET.has_key( 'delta'):
delta = int(request.GET['delta'])
day = someday(delta)
else:
day = today()
mes =""
q =Haco.all()
q =q.filter( 'user', request.user)
q =q.filter( 'date', day)
q =q.order( 'pnum')
mes = ""
for h in q:
mes += str(h.username)+","
mes += str(h.date)+","
mes += str(h.pnum)+","
mes += str(h.light)+","
mes += str(h.temp)+","
mes += str(h.watt)+","
mes += str(h.timestamp)
mes +="\n"
return HttpResponse(mes,mimetype = "text/plain" )
@login_required
def test( request):
if request.GET.has_key( 'delta'):
day = someday(int(request.GET['delta']))
else:
day = today()
q =Haco.all()
q =q.filter( 'user', request.user)
q =q.filter( 'date', day)
q =q.order( 'pnum')
return object_list( request, q, template_name = "test.html",
extra_context ={
'count': len(q),
}
)
| Python |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
from django.template import Context, loader
from django.views.generic.list_detail import object_list
from haco.models import *
from httpauth import *
from haco.jsTime import *
| Python |
from django.contrib import admin
from haco.models import HacoUser, Haco
class HacoUserAdmin( admin.ModelAdmin):
list_display =( 'user', 'prefecture', 'city')
class HacoAdmin( admin.ModelAdmin):
list_display =( 'temp', 'light', 'watt', 'date')
admin.site.register( HacoUser)
admin.site.register( Haco)
| Python |
# -*- coding: utf-8 -*-
from datetime import *
def now():
return datetime.now() + timedelta(hours=9)
def today():
return now().replace(hour=0,minute=0,second=0,microsecond=0)
def tomorrow():
return (now() + timedelta(days=1)).replace(hour=0,minute=0,second=0,microsecond=0)
def someday(delta):
return (now() + timedelta(days=delta)).replace(hour=0,minute=0,second=0,microsecond=0)
| Python |
from ragendja.settings_post import settings
settings.add_app_media('combined-%(LANGUAGE_DIR)s.css',
'blueprintcss/reset.css',
'blueprintcss/typography.css',
'blueprintcss/forms.css',
'blueprintcss/grid.css',
'blueprintcss/lang-%(LANGUAGE_DIR)s.css',
)
settings.add_app_media('combined-print-%(LANGUAGE_DIR)s.css',
'blueprintcss/print.css',
)
settings.add_app_media('ie.css',
'blueprintcss/ie.css',
)
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from ragendja.urlsauto import urlpatterns
from ragendja.auth.urls import urlpatterns as auth_patterns
#from myapp.forms import UserRegistrationForm
from django.contrib import admin
from django.contrib.auth import views as auth_views
from haco import views as haco_views
from haco.forms import UserRegistrationForm
admin.autodiscover()
handler500 = 'ragendja.views.server_error'
urlpatterns = auth_patterns + patterns(
'',
('^admin/(.*)', admin.site.root),
#(r'^$', 'django.views.generic.simple.direct_to_template',
# {'template': 'main.html'}),
# Override the default registration form
url(r'^account/register/$', 'registration.views.register',
kwargs={'form_class': UserRegistrationForm},
name='registration_register'),
#url(r'^$', 'haco.views.login'),
url( r'^$',
auth_views.login,
{'template_name': 'registration/login.html'},
name='auth_login'),
(r'^accounts/change-password/$', 'django.contrib.auth.views.password_change',
{'post_change_redirect': '/'}),
(r'^haco/', include( 'haco.urls')),
) + urlpatterns
| Python |
from ragendja.settings_post import settings
if not hasattr(settings, 'ACCOUNT_ACTIVATION_DAYS'):
settings.ACCOUNT_ACTIVATION_DAYS = 30
| Python |
from django.conf.urls.defaults import *
rootpatterns = patterns('',
(r'^account/', include('registration.urls')),
)
| Python |
import datetime
import random
import re
import sha
from google.appengine.ext import db
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db import models
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""
Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generation and emailing of activation
keys), and for cleaning out expired inactive accounts.
"""
def activate_user(self, activation_key):
"""
Validate an activation key and activate the corresponding
``User`` if valid.
If the key is valid and has not expired, return the ``User``
after activating.
If the key is not valid or has expired, return ``False``.
If the key is valid but the ``User`` is already active,
return ``False``.
To prevent reactivation of an account which has been
deactivated by site administrators, the activation key is
reset to the string constant ``RegistrationProfile.ACTIVATED``
after successful activation.
To execute customized logic when a ``User`` is activated,
connect a function to the signal
``registration.signals.user_activated``; this signal will be
sent (with the ``User`` as the value of the keyword argument
``user``) after a successful activation.
"""
from registration.signals import user_activated
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.search(activation_key):
profile = RegistrationProfile.get_by_key_name("key_"+activation_key)
if not profile:
return False
if not profile.activation_key_expired():
user = profile.user
user.is_active = True
user.put()
profile.activation_key = RegistrationProfile.ACTIVATED
profile.put()
user_activated.send(sender=self.model, user=user)
return user
return False
def create_inactive_user(self, username, password, email, domain_override="",
send_email=True):
"""
Create a new, inactive ``User``, generate a
``RegistrationProfile`` and email its activation key to the
``User``, returning the new ``User``.
To disable the email, call with ``send_email=False``.
The activation email will make use of two templates:
``registration/activation_email_subject.txt``
This template will be used for the subject line of the
email. It receives one context variable, ``site``, which
is the currently-active
``django.contrib.sites.models.Site`` instance. Because it
is used as the subject line of an email, this template's
output **must** be only a single line of text; output
longer than one line will be forcibly joined into only a
single line.
``registration/activation_email.txt``
This template will be used for the body of the email. It
will receive three context variables: ``activation_key``
will be the user's activation key (for use in constructing
a URL to activate the account), ``expiration_days`` will
be the number of days for which the key will be valid and
``site`` will be the currently-active
``django.contrib.sites.models.Site`` instance.
To execute customized logic once the new ``User`` has been
created, connect a function to the signal
``registration.signals.user_registered``; this signal will be
sent (with the new ``User`` as the value of the keyword
argument ``user``) after the ``User`` and
``RegistrationProfile`` have been created, and the email (if
any) has been sent..
"""
from registration.signals import user_registered
# prepend "key_" to the key_name, because key_names can't start with numbers
new_user = User(username=username, key_name="key_"+username.lower(),
email=email, is_active=False)
new_user.set_password(password)
new_user.put()
registration_profile = self.create_profile(new_user)
if send_email:
# from django.core.mail import send_mail
# from google.appengine.api.mail import send_mail
current_site = domain_override
# current_site = Site.objects.get_current()
subject = render_to_string('registration/activation_email_subject.txt',
{ 'site': current_site })
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('registration/activation_email.txt',
{ 'activation_key': registration_profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': current_site })
#send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
# send_mail( sender =settings.DEFAULT_FROM_EMAIL,
# to =[new_user.email],
# subject =subject,
# body =message)
user_registered.send(sender=self.model, user=new_user)
return new_user
def create_profile(self, user):
"""
Create a ``RegistrationProfile`` for a given
``User``, and return the ``RegistrationProfile``.
The activation key for the ``RegistrationProfile`` will be a
SHA1 hash, generated from a combination of the ``User``'s
username and a random salt.
"""
salt = sha.new(str(random.random())).hexdigest()[:5]
activation_key = sha.new(salt+user.username).hexdigest()
# prepend "key_" to the key_name, because key_names can't start with numbers
registrationprofile = RegistrationProfile(user=user, activation_key=activation_key, key_name="key_"+activation_key)
registrationprofile.put()
return registrationprofile
def delete_expired_users(self):
"""
Remove expired instances of ``RegistrationProfile`` and their
associated ``User``s.
Accounts to be deleted are identified by searching for
instances of ``RegistrationProfile`` with expired activation
keys, and then checking to see if their associated ``User``
instances have the field ``is_active`` set to ``False``; any
``User`` who is both inactive and has an expired activation
key will be deleted.
It is recommended that this method be executed regularly as
part of your routine site maintenance; this application
provides a custom management command which will call this
method, accessible as ``manage.py cleanupregistration``.
Regularly clearing out accounts which have never been
activated serves two useful purposes:
1. It alleviates the ocasional need to reset a
``RegistrationProfile`` and/or re-send an activation email
when a user does not receive or does not act upon the
initial activation email; since the account will be
deleted, the user will be able to simply re-register and
receive a new activation key.
2. It prevents the possibility of a malicious user registering
one or more accounts and never activating them (thus
denying the use of those usernames to anyone else); since
those accounts will be deleted, the usernames will become
available for use again.
If you have a troublesome ``User`` and wish to disable their
account while keeping it in the database, simply delete the
associated ``RegistrationProfile``; an inactive ``User`` which
does not have an associated ``RegistrationProfile`` will not
be deleted.
"""
for profile in RegistrationProfile.all():
if profile.activation_key_expired():
user = profile.user
if not user.is_active:
user.delete()
profile.delete()
class RegistrationProfile(db.Model):
"""
A simple profile which stores an activation key for use during
user account registration.
Generally, you will not want to interact directly with instances
of this model; the provided manager includes methods
for creating and activating new accounts, as well as for cleaning
out accounts which have never been activated.
While it is possible to use this model as the value of the
``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
so. This model's sole purpose is to store data temporarily during
account registration and activation.
"""
ACTIVATED = u"ALREADY_ACTIVATED"
user = db.ReferenceProperty(User, verbose_name=_('user'))
activation_key = db.StringProperty(_('activation key'))
objects = RegistrationManager()
class Meta:
verbose_name = _('registration profile')
verbose_name_plural = _('registration profiles')
def __unicode__(self):
return u"Registration information for %s" % self.user
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string constant ``ACTIVATED``. Re-activating
is not permitted, and so this method returns ``True`` in
this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key == RegistrationProfile.ACTIVATED or \
(self.user.date_joined + expiration_date <= datetime.datetime.now())
activation_key_expired.boolean = True
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.