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())
... |
'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... |
'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 Non... |
'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 Fal... |
'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()
... |
'éè¿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['c... |
'è·åçšæ·æè¿å衚ç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
statu... |
'è·åçšæ·ææ°å衚ç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 ... |
'è·åçšæ·å
³æ³šå衚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')
... |
'管çåºçšè®¿é®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'),... |
'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 enumera... |
'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... |
'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 SQ... | 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)
... |
'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 ImportE... |
'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:
... |
'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... | 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... |
'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, _... | 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,... |
'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(\'... | 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 ... | 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)], ', ')
sq... |
'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_... | 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:
... |
'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(... | 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_c... |
'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... |
'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):
retur... |
'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] ==... |
'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:... | 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... |
'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 = P... | 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... |
'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\... | 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... |
'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 rang... | 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 = (ma... |
'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.con... |
'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.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.