desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get the callback URL.'
def get_callback(self, oauth_request):
return oauth_request.get_parameter('oauth_callback')
'Optional support for the authenticate header.'
def build_authenticate_header(self, realm=''):
return {'WWW-Authenticate': ('OAuth realm="%s"' % realm)}
'Verify the correct version request for this server.'
def _get_version(self, oauth_request):
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
'Figure out the signature with some defaults.'
def _get_signature_method(self, oauth_request):
try: signature_method = oauth_request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: 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
'Try to find the token for the provided request token key.'
def _get_token(self, oauth_request, token_type='access'):
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
'Verify that timestamp is recentish.'
def _check_timestamp(self, timestamp):
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)))
'Verify that the nonce is uniqueish.'
def _check_nonce(self, consumer, token, nonce):
nonce = self.data_store.lookup_nonce(consumer, token, nonce) if nonce: raise OAuthError(('Nonce already used: %s' % str(nonce)))
'-> OAuthToken.'
def fetch_request_token(self, oauth_request):
raise NotImplementedError
'-> OAuthToken.'
def fetch_access_token(self, oauth_request):
raise NotImplementedError
'-> Some protected resource.'
def access_resource(self, oauth_request):
raise NotImplementedError
'-> OAuthConsumer.'
def lookup_consumer(self, key):
raise NotImplementedError
'-> OAuthToken.'
def lookup_token(self, oauth_consumer, token_type, token_token):
raise NotImplementedError
'-> OAuthToken.'
def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
raise NotImplementedError
'-> OAuthToken.'
def fetch_request_token(self, oauth_consumer, oauth_callback):
raise NotImplementedError
'-> OAuthToken.'
def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
raise NotImplementedError
'-> OAuthToken.'
def authorize_request_token(self, oauth_token, user):
raise NotImplementedError
'-> str.'
def get_name(self):
raise NotImplementedError
'-> str key, str raw.'
def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token):
raise NotImplementedError
'-> str.'
def build_signature(self, oauth_request, oauth_consumer, oauth_token):
raise NotImplementedError
'Builds the base signature string.'
def build_signature(self, oauth_request, consumer, token):
(key, raw) = self.build_signature_base_string(oauth_request, consumer, token) try: import hashlib hashed = hmac.new(key, raw, hashlib.sha1) except: import sha hashed = hmac.new(key, raw, sha) return binascii.b2a_base64(hashed.digest())[:(-1)]
'Concatenates the consumer key and secret.'
def build_signature_base_string(self, oauth_request, consumer, token):
sig = ('%s&' % escape(consumer.secret)) if token: sig = (sig + escape(token.secret)) return (sig, sig)
'Pack image from file into multipart-formdata post body'
@staticmethod def _pack_image(filename, max_size, source=None, status=None, lat=None, long=None, contentname='image'):
try: if (os.path.getsize(filename) > (max_size * 1024)): raise WeibopError('File is too big, must be less than 700kb.') except os.error: raise WeibopError('Unable to access file') 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)) 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) headers = {'Content-Type': 'multipart/form-data; boundary=Tw3ePy', 'Content-Length': len(body)} return (headers, body)
'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.'
def on_data(self, data):
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
'Called when a new status arrives'
def on_status(self, status):
return
'Called when a delete notice arrives for a status'
def on_delete(self, status_id, user_id):
return
'Called when a limitation notice arrvies'
def on_limit(self, track):
return
'Called when a non-200 status code is returned'
def on_error(self, status_code):
return False
'Called when stream connection times out'
def on_timeout(self):
return
'Initialize the cache timeout: number of seconds to keep a cached entry'
def __init__(self, timeout=60):
self.timeout = timeout
'Add new record to cache key: entry key value: data of entry'
def store(self, key, value):
raise NotImplementedError
'Get cached entry if exists and not expired key: which entry to get timeout: override timeout with this value [optional]'
def get(self, key, timeout=None):
raise NotImplementedError
'Get count of entries currently stored in cache'
def count(self):
raise NotImplementedError
'Delete any expired entries in cache.'
def cleanup(self):
raise NotImplementedError
'Delete all cached entries'
def flush(self):
raise NotImplementedError
'Return iterator for pages'
def pages(self, limit=0):
if (limit > 0): self.iterator.limit = limit return self.iterator
'Return iterator for items in each page'
def items(self, limit=0):
i = ItemIterator(self.iterator) i.limit = limit return i
'甚于获取sina埮博 access_token 和access_secret'
def auth(self):
if (len(self.consumer_key) == 0): print 'Please set consumer_key' return if (len(self.consumer_key) == 0): print 'Please set consumer_secret' return 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)
'通过oauth协议以䟿胜获取sina埮博数据'
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 get_userprofile(self, id):
try: userprofile = {} userprofile['id'] = id user = self.api.get_user(id) self.obj = user userprofile['screen_name'] = self.getAtt('screen_name') userprofile['name'] = self.getAtt('name') userprofile['province'] = self.getAtt('province') userprofile['city'] = self.getAtt('city') userprofile['location'] = self.getAtt('location') userprofile['description'] = self.getAtt('description') userprofile['url'] = self.getAtt('url') userprofile['profile_image_url'] = self.getAtt('profile_image_url') userprofile['domain'] = self.getAtt('domain') userprofile['gender'] = self.getAtt('gender') userprofile['followers_count'] = self.getAtt('followers_count') userprofile['friends_count'] = self.getAtt('friends_count') userprofile['statuses_count'] = self.getAtt('statuses_count') userprofile['favourites_count'] = self.getAtt('favourites_count') userprofile['created_at'] = self.getAtt('created_at') userprofile['following'] = self.getAtt('following') userprofile['allow_all_act_msg'] = self.getAtt('allow_all_act_msg') userprofile['geo_enabled'] = self.getAtt('geo_enabled') userprofile['verified'] = self.getAtt('verified') except WeibopError as e: print 'error occured when access userprofile use user_id:', id print 'Error:', e log.error('Error occured when access userprofile use user_id:{0}\nError:{1}'.format(id, e), exc_info=sys.exc_info()) return None return userprofile
'获取甚户最近发衚的50条埮博'
def get_specific_weibo(self, id):
statusprofile = {} statusprofile['id'] = id try: get_status = bind_api(path='/statuses/show/{id}.json', payload_type='status', allowed_param=['id']) except: return '**\xe7\xbb\x91\xe5\xae\x9a\xe9\x94\x99\xe8\xaf\xaf**' status = get_status(self.api, id) self.obj = status statusprofile['created_at'] = self.getAtt('created_at') statusprofile['text'] = self.getAtt('text') statusprofile['source'] = self.getAtt('source') statusprofile['favorited'] = self.getAtt('favorited') statusprofile['truncated'] = self.getAtt('ntruncatedame') statusprofile['in_reply_to_status_id'] = self.getAtt('in_reply_to_status_id') statusprofile['in_reply_to_user_id'] = self.getAtt('in_reply_to_user_id') statusprofile['in_reply_to_screen_name'] = self.getAtt('in_reply_to_screen_name') statusprofile['thumbnail_pic'] = self.getAtt('thumbnail_pic') statusprofile['bmiddle_pic'] = self.getAtt('bmiddle_pic') statusprofile['original_pic'] = self.getAtt('original_pic') statusprofile['geo'] = self.getAtt('geo') statusprofile['mid'] = self.getAtt('mid') statusprofile['retweeted_status'] = self.getAtt('retweeted_status') return statusprofile
'获取甚户最新发衚的count条数据'
def get_latest_weibo(self, user_id, count):
(statuses, statusprofile) = ([], {}) try: timeline = self.api.user_timeline(count=count, user_id=user_id) except Exception as e: print 'error occured when access status use user_id:', user_id print 'Error:', e log.error('Error occured when access status use user_id:{0}\nError:{1}'.format(user_id, e), exc_info=sys.exc_info()) return None for line in timeline: self.obj = line statusprofile['usr_id'] = user_id statusprofile['id'] = self.getAtt('id') statusprofile['created_at'] = self.getAtt('created_at') statusprofile['text'] = self.getAtt('text') statusprofile['source'] = self.getAtt('source') statusprofile['favorited'] = self.getAtt('favorited') statusprofile['truncated'] = self.getAtt('ntruncatedame') statusprofile['in_reply_to_status_id'] = self.getAtt('in_reply_to_status_id') statusprofile['in_reply_to_user_id'] = self.getAtt('in_reply_to_user_id') statusprofile['in_reply_to_screen_name'] = self.getAtt('in_reply_to_screen_name') statusprofile['thumbnail_pic'] = self.getAtt('thumbnail_pic') statusprofile['bmiddle_pic'] = self.getAtt('bmiddle_pic') statusprofile['original_pic'] = self.getAtt('original_pic') statusprofile['geo'] = repr(pickle.dumps(self.getAtt('geo'), pickle.HIGHEST_PROTOCOL)) statusprofile['mid'] = self.getAtt('mid') statusprofile['retweeted_status'] = repr(pickle.dumps(self.getAtt('retweeted_status'), pickle.HIGHEST_PROTOCOL)) statuses.append(statusprofile) return statuses
'获取甚户关泚列衚id'
def friends_ids(self, id):
(next_cursor, cursor) = (1, 0) ids = [] while (0 != next_cursor): fids = self.api.friends_ids(user_id=id, cursor=cursor) self.obj = fids ids.extend(self.getAtt('ids')) cursor = next_cursor = self.getAtt('next_cursor') previous_cursor = self.getAtt('previous_cursor') return ids
'管理应甚访问API速床,适时进行沉睡'
def manage_access(self):
info = self.api.rate_limit_status() self.obj = info sleep_time = (round((float(self.getAtt('reset_time_in_seconds')) / self.getAtt('remaining_hits')), 2) if self.getAtt('remaining_hits') else self.getAtt('reset_time_in_seconds')) print self.getAtt('remaining_hits'), self.getAtt('reset_time_in_seconds'), self.getAtt('hourly_limit'), self.getAtt('reset_time') print 'sleep time:', sleep_time, 'pid:', os.getpid() time.sleep((sleep_time + 1.5))
'Generate a channel attached to this site.'
def buildProtocol(self, addr):
channel = http.HTTPFactory.buildProtocol(self, addr) class MyRequest(Request, ): actualfunc = staticmethod(self.func) channel.requestFactory = MyRequest channel.site = self return channel
'Creates a new SQLQuery. >>> SQLQuery("x") <sql: \'x\'> >>> q = SQLQuery([\'SELECT * FROM \', \'test\', \' WHERE x=\', SQLParam(1)]) >>> q <sql: \'SELECT * FROM test WHERE x=1\'> >>> q.query(), q.values() (\'SELECT * FROM test WHERE x=%s\', [1]) >>> SQLQuery(SQLParam(1)) <sql: \'1\'>'
def __init__(self, items=None):
if (items is None): self.items = [] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] for (i, item) in enumerate(self.items): if (isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral)): self.items[i] = item.value.v
'Returns the query part of the sql query. >>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam(\'joe\')]) >>> q.query() \'SELECT * FROM test WHERE name=%s\' >>> q.query(paramstyle=\'qmark\') \'SELECT * FROM test WHERE name=?\''
def query(self, paramstyle=None):
s = [] for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) if (paramstyle in ['format', 'pyformat']): if (('%' in x) and ('%%' not in x)): x = x.replace('%', '%%') s.append(x) return ''.join(s)
'Returns the values of the parameters used in the sql query. >>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam(\'joe\')]) >>> q.values() [\'joe\']'
def values(self):
return [i.value for i in self.items if isinstance(i, SQLParam)]
'Joins multiple queries. >>> SQLQuery.join([\'a\', \'b\'], \', \') <sql: \'a, b\'> Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join([\'a\', \'b\'], \', \', prefix=\'(\', suffix=\')\') <sql: \'(a, b)\'> If target argument is provided, the items are appended to target instead of creating a new SQLQuery.'
def join(items, sep=' ', prefix=None, suffix=None, target=None):
if (target is None): target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for (i, item) in enumerate(items): if (i != 0): target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target
'Creates a database.'
def __init__(self, db_module, keywords):
keywords.pop('driver', None) self.db_module = db_module self.keywords = keywords self._ctx = threadeddict() self.printing = config.get('debug_sql', config.get('debug', False)) self.supports_multiple_insert = False try: import DBUtils self.has_pooling = True except ImportError: self.has_pooling = False self.has_pooling = (self.keywords.pop('pooling', True) and self.has_pooling)
'Returns parameter marker based on paramstyle attribute if this database.'
def _param_marker(self):
style = getattr(self, 'paramstyle', 'pyformat') if (style == 'qmark'): return '?' elif (style == 'numeric'): return ':1' elif (style in ['format', 'pyformat']): return '%s' raise UnknownParamstyle(style)
'executes an sql query'
def _db_execute(self, cur, sql_query):
self.ctx.dbq_count += 1 try: a = time.time() (query, params) = self._process_query(sql_query) out = cur.execute(query, params) b = time.time() except: if self.printing: print('ERR:', str(sql_query), file=debug) if self.ctx.transactions: self.ctx.transactions[(-1)].rollback() else: self.ctx.rollback() raise if self.printing: print(('%s (%s): %s' % (round((b - a), 2), self.ctx.dbq_count, str(sql_query))), file=debug) return out
'Takes the SQLQuery object and returns query string and parameters.'
def _process_query(self, sql_query):
paramstyle = getattr(self, 'paramstyle', 'pyformat') query = sql_query.query(paramstyle) params = sql_query.values() return (query, params)
'Execute SQL query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style list to use instead of interpolating. >>> db = DB(None, {}) >>> db.query("SELECT * FROM foo", _test=True) <sql: \'SELECT * FROM foo\'> >>> db.query("SELECT * FROM foo WHERE x = $x", vars=dict(x=\'f\'), _test=True) <sql: "SELECT * FROM foo WHERE x = \'f\'"> >>> db.query("SELECT * FROM foo WHERE x = " + sqlquote(\'f\'), _test=True) <sql: "SELECT * FROM foo WHERE x = \'f\'">'
def query(self, sql_query, vars=None, processed=False, _test=False):
if (vars is None): vars = {} if ((not processed) and (not isinstance(sql_query, SQLQuery))): sql_query = reparam(sql_query, vars) if _test: return sql_query db_cursor = self._db_cursor() self._db_execute(db_cursor, sql_query) if db_cursor.description: names = [x[0] for x in db_cursor.description] def iterwrapper(): row = db_cursor.fetchone() while row: (yield storage(dict(zip(names, row)))) row = db_cursor.fetchone() out = iterbetter(iterwrapper()) out.__len__ = (lambda : int(db_cursor.rowcount)) out.list = (lambda : [storage(dict(zip(names, x))) for x in db_cursor.fetchall()]) else: out = db_cursor.rowcount if (not self.ctx.transactions): self.ctx.commit() return out
'Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause can be a SQLQuery. >>> db = DB(None, {}) >>> db.select(\'foo\', _test=True) <sql: \'SELECT * FROM foo\'> >>> db.select([\'foo\', \'bar\'], where="foo.bar_id = bar.id", limit=5, _test=True) <sql: \'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5\'> >>> db.select(\'foo\', where={\'id\': 5}, _test=True) <sql: \'SELECT * FROM foo WHERE id = 5\'>'
def select(self, tables, vars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False):
if (vars is None): vars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, vars) for (sql, val) in sql_clauses if (val is not None)] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True)
'Selects from `table` where keys are equal to values in `kwargs`. >>> db = DB(None, {}) >>> db.where(\'foo\', bar_id=3, _test=True) <sql: \'SELECT * FROM foo WHERE bar_id = 3\'> >>> db.where(\'foo\', source=2, crust=\'dewey\', _test=True) <sql: "SELECT * FROM foo WHERE crust = \'dewey\' AND source = 2"> >>> db.where(\'foo\', _test=True) <sql: \'SELECT * FROM foo\'>'
def where(self, table, what='*', order=None, group=None, limit=None, offset=None, _test=False, **kwargs):
where = self._where_dict(kwargs) return self.select(table, what=what, order=order, group=group, limit=limit, offset=offset, _test=_test, where=where)
'Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname` to the ID if it\'s not the default, or to `False` if there isn\'t one. >>> db = DB(None, {}) >>> q = db.insert(\'foo\', name=\'bob\', age=2, created=SQLLiteral(\'NOW()\'), _test=True) >>> q <sql: "INSERT INTO foo (age, created, name) VALUES (2, NOW(), \'bob\')"> >>> q.query() \'INSERT INTO foo (age, created, name) VALUES (%s, NOW(), %s)\' >>> q.values() [2, \'bob\']'
def insert(self, tablename, seqname=None, _test=False, **values):
def q(x): return (('(' + x) + ')') if values: sorted_values = sorted(values.items(), key=(lambda t: t[0])) _keys = SQLQuery.join(map((lambda t: t[0]), sorted_values), ', ') _values = SQLQuery.join([sqlparam(v) for v in map((lambda t: t[1]), sorted_values)], ', ') sql_query = (((('INSERT INTO %s ' % tablename) + q(_keys)) + ' VALUES ') + q(_values)) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) if _test: return sql_query db_cursor = self._db_cursor() if (seqname is not False): sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): (q1, q2) = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] except Exception: out = None if (not self.ctx.transactions): self.ctx.commit() return out
'Inserts multiple rows into `tablename`. The `values` must be a list of dictioanries, one for each row to be inserted, each with the same set of keys. Returns the list of ids of the inserted rows. Set `seqname` to the ID if it\'s not the default, or to `False` if there isn\'t one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{"name": "foo", "email": "[email protected]"}, {"name": "bar", "email": "[email protected]"}] >>> db.multiple_insert(\'person\', values=values, _test=True) <sql: "INSERT INTO person (email, name) VALUES (\'[email protected]\', \'foo\'), (\'[email protected]\', \'bar\')">'
def multiple_insert(self, tablename, values, seqname=None, _test=False):
if (not values): return [] if (not self.supports_multiple_insert): out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if (seqname is False): return None else: return out keys = values[0].keys() for v in values: if (v.keys() != keys): raise ValueError('Not all rows have the same keys') keys = sorted(keys) sql_query = SQLQuery(('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys)))) for (i, row) in enumerate(values): if (i != 0): sql_query.append(', ') SQLQuery.join([SQLParam(row[k]) for k in keys], sep=', ', target=sql_query, prefix='(', suffix=')') if _test: return sql_query db_cursor = self._db_cursor() if (seqname is not False): sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): (q1, q2) = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(((out - len(values)) + 1), (out + 1)) except Exception: out = None if (not self.ctx.transactions): self.ctx.commit() return out
'Update `tables` with clause `where` (interpolated using `vars`) and setting `values`. >>> db = DB(None, {}) >>> name = \'Joseph\' >>> q = db.update(\'foo\', where=\'name = $name\', name=\'bob\', age=2, ... created=SQLLiteral(\'NOW()\'), vars=locals(), _test=True) >>> q <sql: "UPDATE foo SET age = 2, created = NOW(), name = \'bob\' WHERE name = \'Joseph\'"> >>> q.query() \'UPDATE foo SET age = %s, created = NOW(), name = %s WHERE name = %s\' >>> q.values() [2, \'bob\', \'Joseph\']'
def update(self, tables, where, vars=None, _test=False, **values):
if (vars is None): vars = {} where = self._where(where, vars) values = sorted(values.items(), key=(lambda t: t[0])) query = ((((('UPDATE ' + sqllist(tables)) + ' SET ') + sqlwhere(values, ', ')) + ' WHERE ') + where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if (not self.ctx.transactions): self.ctx.commit() return db_cursor.rowcount
'Deletes from `table` with clauses `where` and `using`. >>> db = DB(None, {}) >>> name = \'Joe\' >>> db.delete(\'foo\', where=\'name = $name\', vars=locals(), _test=True) <sql: "DELETE FROM foo WHERE name = \'Joe\'">'
def delete(self, table, where, using=None, vars=None, _test=False):
if (vars is None): vars = {} where = self._where(where, vars) q = ('DELETE FROM ' + table) if using: q += (' USING ' + sqllist(using)) if where: q += (' WHERE ' + where) if _test: return q db_cursor = self._db_cursor() self._db_execute(db_cursor, q) if (not self.ctx.transactions): self.ctx.commit() return db_cursor.rowcount
'Start a transaction.'
def transaction(self):
return Transaction(self.ctx)
'Query postgres to find names of all sequences used in this database.'
def _get_all_sequences(self):
if (self._sequences is None): q = "SELECT c.relname FROM pg_class c WHERE c.relkind = 'S'" self._sequences = set([c.relname for c in self.query(q)]) return self._sequences
'Takes the SQLQuery object and returns query string and parameters.'
def _process_query(self, sql_query):
paramstyle = getattr(self, 'paramstyle', 'pyformat') query = sql_query.query(paramstyle) params = sql_query.values() return (query, tuple(params))
'Test LIMIT. Fake presence of pymssql module for running tests. >>> import sys >>> sys.modules[\'pymssql\'] = sys.modules[\'sys\'] MSSQL has TOP clause instead of LIMIT clause. >>> db = MSSQLDB(db=\'test\', user=\'joe\', pw=\'secret\') >>> db.select(\'foo\', limit=4, _test=True) <sql: \'SELECT * TOP 4 FROM foo\'>'
def _test(self):
pass
'Returns a `status` redirect to the new URL. `url` is joined with the base URL so that things like `redirect("about") will work properly.'
def __init__(self, url, status='301 Moved Permanently', absolute=False):
newloc = urljoin(ctx.path, url) if newloc.startswith('/'): if absolute: home = ctx.realhome else: home = ctx.home newloc = (home + newloc) headers = {'Content-Type': 'text/html', 'Location': newloc} HTTPError.__init__(self, status, headers, '')
'Returns the keys with maximum count.'
def most(self):
m = max(itervalues(self)) return [k for (k, v) in iteritems(self) if (v == m)]
'Returns the keys with mininum count.'
def least(self):
m = min(self.itervalues()) return [k for (k, v) in iteritems(self) if (v == m)]
'Returns what percentage a certain key is of all entries. >>> c = counter() >>> c.add(\'x\') >>> c.add(\'x\') >>> c.add(\'x\') >>> c.add(\'y\') >>> c.percent(\'x\') 0.75 >>> c.percent(\'y\') 0.25'
def percent(self, key):
return (float(self[key]) / sum(self.values()))
'Returns keys sorted by value. >>> c = counter() >>> c.add(\'x\') >>> c.add(\'x\') >>> c.add(\'y\') >>> c.sorted_keys() [\'x\', \'y\']'
def sorted_keys(self):
return sorted(self.keys(), key=(lambda k: self[k]), reverse=True)
'Returns values sorted by value. >>> c = counter() >>> c.add(\'x\') >>> c.add(\'x\') >>> c.add(\'y\') >>> c.sorted_values() [2, 1]'
def sorted_values(self):
return [self[k] for k in self.sorted_keys()]
'Returns items sorted by value. >>> c = counter() >>> c.add(\'x\') >>> c.add(\'x\') >>> c.add(\'y\') >>> c.sorted_items() [(\'x\', 2), (\'y\', 1)]'
def sorted_items(self):
return [(k, self[k]) for k in self.sorted_keys()]
'Returns the first element of the iterator or None when there are no elements. If the optional argument default is specified, that is returned instead of None when there are no elements.'
def first(self, default=None):
try: return next(iter(self)) except StopIteration: return default
'Clears all ThreadedDict instances.'
def clear_all():
for t in list(ThreadedDict._instances): t.clear()
'Reads one section from the given text. section -> block | assignment | line >>> read_section = Parser().read_section >>> read_section(\'foo\nbar\n\') (<line: [t\'foo\n\']>, \'bar\n\') >>> read_section(\'$ a = b + 1\nfoo\n\') (<assignment: \'a = b + 1\'>, \'foo\n\') read_section(\'$for in range(10):\n hello $i\nfoo)'
def read_section(self, text):
if text.lstrip(' ').startswith('$'): index = text.index('$') (begin_indent, text2) = (text[:index], text[(index + 1):]) ahead = self.python_lookahead(text2) if (ahead == 'var'): return self.read_var(text2) elif (ahead in self.statement_nodes): return self.read_block_section(text2, begin_indent) elif (ahead in self.keywords): return self.read_keyword(text2) elif (ahead.strip() == ''): return self.read_assignment(text2) return self.readline(text)
'Reads a var statement. >>> read_var = Parser().read_var >>> read_var(\'var x=10\nfoo\') (<var: x = 10>, \'foo\') >>> read_var(\'var x: hello $name\nfoo\') (<var: x = join_(u\'hello \', escape_(name, True))>, \'foo\')'
def read_var(self, text):
(line, text) = splitline(text) tokens = self.python_tokens(line) if (len(tokens) < 4): raise SyntaxError('Invalid var statement') name = tokens[1] sep = tokens[2] value = line.split(sep, 1)[1].strip() if (sep == '='): pass elif (sep == ':'): if (tokens[3] == '\n'): (block, text) = self.read_indented_block(text, ' ') lines = [self.readline(x)[0] for x in block.splitlines()] nodes = [] for x in lines: nodes.extend(x.nodes) nodes.append(TextNode('\n')) else: (linenode, _) = self.readline(value) nodes = linenode.nodes parts = [node.emit('') for node in nodes] value = ('join_(%s)' % ', '.join(parts)) else: raise SyntaxError('Invalid var statement') return (VarNode(name, value), text)
'Reads section by section till end of text. >>> read_suite = Parser().read_suite >>> read_suite(\'hello $name\nfoo\n\') [<line: [t\'hello \', $name, t\'\n\']>, <line: [t\'foo\n\']>]'
def read_suite(self, text):
sections = [] while text: (section, text) = self.read_section(text) sections.append(section) return SuiteNode(sections)
'Reads one line from the text. Newline is supressed if the line ends with \. >>> readline = Parser().readline >>> readline(\'hello $name!\nbye!\') (<line: [t\'hello \', $name, t\'!\n\']>, \'bye!\') >>> readline(\'hello $name!\\\nbye!\') (<line: [t\'hello \', $name, t\'!\']>, \'bye!\') >>> readline(\'$f()\n\n\') (<line: [$f(), t\'\n\']>, \'\n\')'
def readline(self, text):
(line, text) = splitline(text) if line.endswith('\\\n'): line = line[:(-2)] nodes = [] while line: (node, line) = self.read_node(line) nodes.append(node) return (LineNode(nodes), text)
'Reads a node from the given text and returns the node and remaining text. >>> read_node = Parser().read_node >>> read_node(\'hello $name\') (t\'hello \', \'$name\') >>> read_node(\'$name\') ($name, \'\')'
def read_node(self, text):
if text.startswith('$$'): return (TextNode('$'), text[2:]) elif text.startswith('$#'): (line, text) = splitline(text) return (TextNode('\n'), text) elif text.startswith('$'): text = text[1:] if text.startswith(':'): escape = False text = text[1:] else: escape = True return self.read_expr(text, escape=escape) else: return self.read_text(text)
'Reads a text node from the given text. >>> read_text = Parser().read_text >>> read_text(\'hello $name\') (t\'hello \', \'$name\')'
def read_text(self, text):
index = text.find('$') if (index < 0): return (TextNode(text), '') else: return (TextNode(text[:index]), text[index:])
'Reads a python expression from the text and returns the expression and remaining text. expr -> simple_expr | paren_expr simple_expr -> id extended_expr extended_expr -> attr_access | paren_expr extended_expr | \'\' attr_access -> dot id extended_expr paren_expr -> [ tokens ] | ( tokens ) | { tokens } >>> read_expr = Parser().read_expr >>> read_expr("name") ($name, \'\') >>> read_expr("a.b and c") ($a.b, \' and c\') >>> read_expr("a. b") ($a, \'. b\') >>> read_expr("name</h1>") ($name, \'</h1>\') >>> read_expr("(limit)ing") ($(limit), \'ing\') >>> read_expr(\'a[1, 2][:3].f(1+2, "weird string[).", 3 + 4) done.\') ($a[1, 2][:3].f(1+2, "weird string[).", 3 + 4), \' done.\')'
def read_expr(self, text, escape=True):
def simple_expr(): identifier() extended_expr() def identifier(): next(tokens) def extended_expr(): lookahead = tokens.lookahead() if (lookahead is None): return elif (lookahead.value == '.'): attr_access() elif (lookahead.value in parens): paren_expr() extended_expr() else: return def attr_access(): from token import NAME dot = tokens.lookahead() if (tokens.lookahead2().type == NAME): next(tokens) identifier() extended_expr() def paren_expr(): begin = next(tokens).value end = parens[begin] while True: if (tokens.lookahead().value in parens): paren_expr() else: t = next(tokens) if (t.value == end): break return parens = {'(': ')', '[': ']', '{': '}'} def get_tokens(text): 'tokenize text using python tokenizer.\n Python tokenizer ignores spaces, but they might be important in some cases. \n This function introduces dummy space tokens when it identifies any ignored space.\n Each token is a storage object containing type, value, begin and end.\n ' i = iter([text]) readline = (lambda : next(i)) end = None for t in tokenize.generate_tokens(readline): t = storage(type=t[0], value=t[1], begin=t[2], end=t[3]) if ((end is not None) and (end != t.begin)): (_, x1) = end (_, x2) = t.begin (yield storage(type=(-1), value=text[x1:x2], begin=end, end=t.begin)) end = t.end (yield t) class BetterIter: 'Iterator like object with 2 support for 2 look aheads.' def __init__(self, items): self.iteritems = iter(items) self.items = [] self.position = 0 self.current_item = None def lookahead(self): if (len(self.items) <= self.position): self.items.append(self._next()) return self.items[self.position] def _next(self): try: return next(self.iteritems) except StopIteration: return None def lookahead2(self): if (len(self.items) <= (self.position + 1)): self.items.append(self._next()) return self.items[(self.position + 1)] def __next__(self): self.current_item = self.lookahead() self.position += 1 return self.current_item next = __next__ tokens = BetterIter(get_tokens(text)) if (tokens.lookahead().value in parens): paren_expr() else: simple_expr() (row, col) = tokens.current_item.end return (ExpressionNode(text[:col], escape=escape), text[col:])
'Reads assignment statement from text. >>> read_assignment = Parser().read_assignment >>> read_assignment(\'a = b + 1\nfoo\') (<assignment: \'a = b + 1\'>, \'foo\')'
def read_assignment(self, text):
(line, text) = splitline(text) return (AssignmentNode(line.strip()), text)
'Returns the first python token from the given text. >>> python_lookahead = Parser().python_lookahead >>> python_lookahead(\'for i in range(10):\') \'for\' >>> python_lookahead(\'else:\') \'else\' >>> python_lookahead(\' x = 1\')'
def python_lookahead(self, text):
i = iter([text]) readline = (lambda : next(i)) tokens = tokenize.generate_tokens(readline) return next(tokens)[1]
'Read a block of text. A block is what typically follows a for or it statement. It can be in the same line as that of the statement or an indented block. >>> read_indented_block = Parser().read_indented_block >>> read_indented_block(\' a\n b\nc\', \' \') (\'a\nb\n\', \'c\') >>> read_indented_block(\' a\n b\n c\nd\', \' \') (\'a\n b\nc\n\', \'d\') >>> read_indented_block(\' a\n\n b\nc\', \' \') (\'a\n\n b\n\', \'c\')'
def read_indented_block(self, text, indent):
if (indent == ''): return ('', text) block = '' while text: (line, text2) = splitline(text) if (line.strip() == ''): block += '\n' elif line.startswith(indent): block += line[len(indent):] else: break text = text2 return (block, text)
'Reads a python statement. >>> read_statement = Parser().read_statement >>> read_statement(\'for i in range(10): hello $name\') (\'for i in range(10):\', \' hello $name\')'
def read_statement(self, text):
tok = PythonTokenizer(text) tok.consume_till(':') return (text[:tok.index], text[tok.index:])
'>>> read_block_section = Parser().read_block_section >>> read_block_section(\'for i in range(10): hello $i\nfoo\') (<block: \'for i in range(10):\', [<line: [t\'hello \', $i, t\'\n\']>]>, \'foo\') >>> read_block_section(\'for i in range(10):\n hello $i\n foo\', begin_indent=\' \') (<block: \'for i in range(10):\', [<line: [t\'hello \', $i, t\'\n\']>]>, \' foo\') >>> read_block_section(\'for i in range(10):\n hello $i\nfoo\') (<block: \'for i in range(10):\', [<line: [t\'hello \', $i, t\'\n\']>]>, \'foo\')'
def read_block_section(self, text, begin_indent=''):
(line, text) = splitline(text) (stmt, line) = self.read_statement(line) keyword = self.python_lookahead(stmt) if line.strip(): block = line.lstrip() else: def find_indent(text): rx = re_compile(' +') match = rx.match(text) first_indent = (match and match.group(0)) return (first_indent or '') first_indent = find_indent(text)[len(begin_indent):] if (keyword == 'code'): indent = (begin_indent + first_indent) else: indent = (begin_indent + min(first_indent, INDENT)) (block, text) = self.read_indented_block(text, indent) return (self.create_block_node(keyword, stmt, block, begin_indent), text)
'Consumes tokens till colon. >>> tok = PythonTokenizer(\'for i in range(10): hello $i\') >>> tok.consume_till(\':\') >>> tok.text[:tok.index] \'for i in range(10):\' >>> tok.text[tok.index:] \' hello $i\''
def consume_till(self, delim):
try: while True: t = next(self) if (t.value == delim): break elif (t.value == '('): self.consume_till(')') elif (t.value == '['): self.consume_till(']') elif (t.value == '{'): self.consume_till('}') if (t.value == '\n'): break except: return
'Normalizes template text by correcting , tabs and BOM chars.'
def normalize_text(text):
text = text.replace('\r\n', '\n').replace('\r', '\n').expandtabs() if (not text.endswith('\n')): text += '\n' BOM = '\xef\xbb\xbf' if (isinstance(text, str) and text.startswith(BOM)): text = text[len(BOM):] text = text.replace('\\$', '$$') return text
'Add a global to this rendering instance.'
def _add_global(self, obj, name=None):
if ('globals' not in self._keywords): self._keywords['globals'] = {} if (not name): name = obj.__name__ self._keywords['globals'][name] = obj
'Initialize visitor by generating callbacks for all AST node types.'
def __init__(self, *args, **kwargs):
super(SafeVisitor, self).__init__(*args, **kwargs) self.errors = []
'Validate each node in AST and raise SecurityError if the code is not safe.'
def walk(self, tree, filename):
self.filename = filename self.visit(tree) if self.errors: raise SecurityError('\n'.join([str(err) for err in self.errors]))
'Prepare value of __body__ by joining parts.'
def _prepare_body(self):
if self._parts: value = u''.join(self._parts) self._parts[:] = [] body = self._d.get('__body__') if body: self._d['__body__'] = (body + value) else: self._d['__body__'] = value
'Clears all cookies and history.'
def reset(self):
self.cookiejar.clear()
'Builds the opener using (urllib2/urllib.request).build_opener. Subclasses can override this function to prodive custom openers.'
def build_opener(self):
return urllib_build_opener()
'Opens the specified url.'
def open(self, url, data=None, headers={}):
url = urljoin(self.url, url) req = Request(url, data, headers) return self.do_request(req)
'Opens the current page in real web browser.'
def show(self):
f = open('page.html', 'w') f.write(self.data) f.close() import webbrowser, os url = ('file://' + os.path.abspath('page.html')) webbrowser.open(url)
'Returns a copy of the current response.'
def get_response(self):
return addinfourl(BytesIO(self.data), self._response.info(), self._response.geturl())
'Returns beautiful soup of the current document.'
def get_soup(self):
import BeautifulSoup return BeautifulSoup.BeautifulSoup(self.data)
'Returns content of e or the current document as plain text.'
def get_text(self, e=None):
e = (e or self.get_soup()) return ''.join([htmlunquote(c) for c in e.recursiveChildGenerator() if isinstance(c, unicode)])
'Returns all links in the document.'
def get_links(self, text=None, text_regex=None, url=None, url_regex=None, predicate=None):
return self._filter_links(self._get_links(), text=text, text_regex=text_regex, url=url, url_regex=url_regex, predicate=predicate)
'Returns all forms in the current document. The returned form objects implement the ClientForm.HTMLForm interface.'
def get_forms(self):
if (self._forms is None): import ClientForm self._forms = ClientForm.ParseResponse(self.get_response(), backwards_compat=False) return self._forms
'Selects the specified form.'
def select_form(self, name=None, predicate=None, index=0):
forms = self.get_forms() if (name is not None): forms = [f for f in forms if (f.name == name)] if predicate: forms = [f for f in forms if predicate(f)] if forms: self.form = forms[index] return self.form else: raise BrowserError('No form selected.')