desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'The Soup object is initialized as the \'root tag\', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless ...
def __init__(self, markup='', parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False):
self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities if self.convertEntities: self.smartQuotesTo = None if (convertEntities == self.HTML_ENTITIES): self.convertXMLEntities = False ...
'This method fixes a bug in Python\'s SGMLParser.'
def convert_charref(self, name):
try: n = int(name) except ValueError: return if (not (0 <= n <= 127)): return return self.convert_codepoint(n)
'This method routes method call requests to either the SGMLParser superclass or the Tag superclass, depending on the method name.'
def __getattr__(self, methodName):
if ((methodName.find('start_') == 0) or (methodName.find('end_') == 0) or (methodName.find('do_') == 0)): return SGMLParser.__getattr__(self, methodName) elif (methodName.find('__') != 0): return Tag.__getattr__(self, methodName) else: raise AttributeError
'Returns true iff the given string is the name of a self-closing tag according to this parser.'
def isSelfClosingTag(self, name):
return (self.SELF_CLOSING_TAGS.has_key(name) or self.instanceSelfClosingTags.has_key(name))
'Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.'
def _popToTag(self, name, inclusivePop=True):
if (name == self.ROOT_TAG_NAME): return numPops = 0 mostRecentTag = None for i in range((len(self.tagStack) - 1), 0, (-1)): if (name == self.tagStack[i].name): numPops = (len(self.tagStack) - i) break if (not inclusivePop): numPops = (numPops - 1) ...
'We need to pop up to the previous tag of this type, unless one of this tag\'s nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of this type. Examples: <p>Foo<b...
def _smartPop(self, name):
nestingResetTriggers = self.NESTABLE_TAGS.get(name) isNestable = (nestingResetTriggers != None) isResetNesting = self.RESET_NESTING_TAGS.has_key(name) popTo = None inclusive = True for i in range((len(self.tagStack) - 1), 0, (-1)): p = self.tagStack[i] if (((not p) or (p.name == ...
'Adds a certain piece of text to the tree as a NavigableString subclass.'
def _toStringSubclass(self, text, subclass):
self.endData() self.handle_data(text) self.endData(subclass)
'Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.'
def handle_pi(self, text):
if (text[:3] == 'xml'): text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self._toStringSubclass(text, ProcessingInstruction)
'Handle comments as Comment objects.'
def handle_comment(self, text):
self._toStringSubclass(text, Comment)
'Handle character references as data.'
def handle_charref(self, ref):
if self.convertEntities: data = unichr(int(ref)) else: data = ('&#%s;' % ref) self.handle_data(data)
'Handle entity references as data, possibly converting known HTML and/or XML entity references to the corresponding Unicode characters.'
def handle_entityref(self, ref):
data = None if self.convertHTMLEntities: try: data = unichr(name2codepoint[ref]) except KeyError: pass if ((not data) and self.convertXMLEntities): data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) if ((not data) and self.convertHTMLEntities and (not self...
'Handle DOCTYPEs and the like as Declaration objects.'
def handle_decl(self, data):
self._toStringSubclass(data, Declaration)
'Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.'
def parse_declaration(self, i):
j = None if (self.rawdata[i:(i + 9)] == '<![CDATA['): k = self.rawdata.find(']]>', i) if (k == (-1)): k = len(self.rawdata) data = self.rawdata[(i + 9):k] j = (k + 3) self._toStringSubclass(data, CData) else: try: j = SGMLParser.parse_d...
'Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.'
def start_meta(self, attrs):
httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSubstitution = False for i in range(0, len(attrs)): (key, value) = attrs[i] key = key.lower() if (key == 'http-equiv'): httpEquiv = value elif (key == 'content'): conte...
'Changes a MS smart quote character to an XML or HTML entity.'
def _subMSChar(self, orig):
sub = self.MS_CHARS.get(orig) if (type(sub) == types.TupleType): if (self.smartQuotesTo == 'xml'): sub = ('&#x%s;' % sub[1]) else: sub = ('&%s;' % sub[0]) return sub
'Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases'
def _toUnicode(self, data, encoding):
if ((len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00')): encoding = 'utf-16be' data = data[2:] elif ((len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00')): encoding = 'utf-16le' data = data[2:] elif (data[:3] == '\xef\xbb\xbf'):...
'Given a document, tries to detect its XML encoding.'
def _detectEncoding(self, xml_data, isHTML=False):
xml_encoding = sniffed_xml_encoding = None try: if (xml_data[:4] == 'Lo\xa7\x94'): xml_data = self._ebcdic_to_ascii(xml_data) elif (xml_data[:4] == '\x00<\x00?'): sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') ...
'Apply the path to a node. Return the resulting list of nodes. Apply the steps in the path sequentially by sending the output of each step as input to the next step.'
def apply(self, node):
if (self.path[0] == '/'): if ((not isinstance(node, BeautifulSoup.Tag)) or (node.name != '[document]')): node = node.findParent('[document]') nodes = [node] for step in self.steps: nodes = step.apply(nodes) return nodes
'Parse the predicate. Return a callable that can be used to filter nodes. Update `self.soup_args` to take advantage of BeautifulSoup search features.'
def __parse_predicate(self, predicate):
try: position = int(predicate) if (self.axis == AXIS_DESCENDANT): return PredicateFilter('position', value=position) else: self.soup_args['limit'] = position self.index = (position - 1) return None except ValueError: pass if (pr...
'Apply the step to a list of nodes. Return the list of nodes for the next step.'
def apply(self, nodes):
if (self.step == '.'): return nodes elif (self.step == '..'): return [node.parent for node in nodes] result = [] for node in nodes: if (self.axis == AXIS_CHILD): found = node.findAll(recursive=False, **self.soup_args) elif (self.axis == AXIS_DESCENDANT): ...
'Repeat td elements according to their rowspan attributes in subsequent tr elements.'
def preprocess_dom(self, dom):
cols = self.xpath(dom, '//td[@rowspan]') for col in cols: span = int(col.get('rowspan')) del col.attrib['rowspan'] position = len(self.xpath(col, './preceding-sibling::td')) row = col.getparent() for tr in self.xpath(row, './following-sibling::tr')[:(span - 1)]: ...
'Normalize the retrieve html.'
def _clean_html(self, html):
html = re_spaces.sub(' ', html) html = html.replace('&nbsp;&raquo;', '') return subXMLRefs(html)
'Retrieve an html page and normalize it.'
def _mretrieve(self, url, size=(-1)):
cont = self._retrieve(url, size=size) return self._clean_html(cont)
'Return a list of Person objects, from the string s; items are assumed to be separated by the sep string.'
def _getPersons(self, s, sep='<br/>'):
names = s.split(sep) pl = [] plappend = pl.append counter = 1 for name in names: pid = re_imdbID.findall(name) if (not pid): continue characters = _getTagsWith(name, 'class="char"', toClosure=True, maxRes=1) chpids = [] if characters: f...
'Initialize the access system.'
def __init__(self, uri, adultSearch=1, useORM=None, *arguments, **keywords):
IMDbBase.__init__(self, *arguments, **keywords) if (useORM is None): useORM = ('sqlobject', 'sqlalchemy') if (not isinstance(useORM, (tuple, list))): if (',' in useORM): useORM = useORM.split(',') else: useORM = [useORM] self.useORM = useORM nrMods = l...
'Find titles or names references in strings.'
def _findRefs(self, o, trefs, nrefs):
if isinstance(o, (unicode, str)): for title in re_titleRef.findall(o): a_title = analyze_title(title, canonical=0) rtitle = build_title(a_title, ptdf=1) if trefs.has_key(rtitle): continue movieID = self._getTitleID(rtitle) if (movie...
'Scan for titles or names references in strings.'
def _extractRefs(self, o):
trefs = {} nrefs = {} try: return self._findRefs(o, trefs, nrefs) except RuntimeError as e: import warnings warnings.warn(("RuntimeError in imdb.parser.sql.IMDbSqlAccessSystem; if it's not a recursion limit exceeded and we're not running ...
'Return akatitle in the correct charset, as specified in the akanotes field; if akatitle doesn\'t need to be modified, return None.'
def _changeAKAencoding(self, akanotes, akatitle):
oti = akanotes.find('(original ') if (oti == (-1)): return None ote = akanotes[(oti + 10):].find(' title)') if (ote != (-1)): cs_info = akanotes[(oti + 10):((oti + 10) + ote)].lower().split() for e in cs_info: if (e in ('script', '', 'cyrillic', 'greek')): ...
'Build a comparison for columns where values can be NULL.'
def _buildNULLCondition(self, col, val):
if (val is None): return ISNULL(col) elif isinstance(val, (int, long)): return (col == val) else: return (col == self.toUTF8(val))
'Given a long imdb canonical title, returns a movieID or None if not found.'
def _getTitleID(self, title):
td = analyze_title(title) condition = None if (td['kind'] == 'episode'): epof = td['episode of'] seriesID = [s.id for s in Title.select(AND((Title.q.title == self.toUTF8(epof['title'])), self._buildNULLCondition(Title.q.imdbIndex, epof.get('imdbIndex')), (Title.q.kindID == self._kindRev[e...
'Given a long imdb canonical name, returns a personID or None if not found.'
def _getNameID(self, name):
nd = analyze_name(name) res = Name.select(AND((Name.q.name == self.toUTF8(nd['name'])), self._buildNULLCondition(Name.q.imdbIndex, nd.get('imdbIndex')))) try: c = res.count() if (res.count() != 1): return None except (UnicodeDecodeError, TypeError): return None re...
'Normalize the given movieID.'
def _normalize_movieID(self, movieID):
try: return int(movieID) except (ValueError, OverflowError): raise IMDbError(('movieID "%s" can\'t be converted to integer' % movieID))
'Normalize the given personID.'
def _normalize_personID(self, personID):
try: return int(personID) except (ValueError, OverflowError): raise IMDbError(('personID "%s" can\'t be converted to integer' % personID))
'Normalize the given characterID.'
def _normalize_characterID(self, characterID):
try: return int(characterID) except (ValueError, OverflowError): raise IMDbError(('characterID "%s" can\'t be converted to integer' % characterID))
'Normalize the given companyID.'
def _normalize_companyID(self, companyID):
try: return int(companyID) except (ValueError, OverflowError): raise IMDbError(('companyID "%s" can\'t be converted to integer' % companyID))
'Translate a movieID in an imdbID. If not in the database, try an Exact Primary Title search on IMDb; return None if it\'s unable to get the imdbID.'
def get_imdbMovieID(self, movieID):
try: movie = Title.get(movieID) except NotFoundError: return None imdbID = movie.imdbID if (imdbID is not None): return ('%07d' % imdbID) m_dict = get_movie_data(movie.id, self._kind) titline = build_title(m_dict, ptdf=0) imdbID = self.title2imdbID(titline, m_dict['ki...
'Translate a personID in an imdbID. If not in the database, try an Exact Primary Name search on IMDb; return None if it\'s unable to get the imdbID.'
def get_imdbPersonID(self, personID):
try: person = Name.get(personID) except NotFoundError: return None imdbID = person.imdbID if (imdbID is not None): return ('%07d' % imdbID) n_dict = {'name': person.name, 'imdbIndex': person.imdbIndex} namline = build_name(n_dict, canonical=False) imdbID = self.name2i...
'Translate a characterID in an imdbID. If not in the database, try an Exact Primary Name search on IMDb; return None if it\'s unable to get the imdbID.'
def get_imdbCharacterID(self, characterID):
try: character = CharName.get(characterID) except NotFoundError: return None imdbID = character.imdbID if (imdbID is not None): return ('%07d' % imdbID) n_dict = {'name': character.name, 'imdbIndex': character.imdbIndex} namline = build_name(n_dict, canonical=False) i...
'Translate a companyID in an imdbID. If not in the database, try an Exact Primary Name search on IMDb; return None if it\'s unable to get the imdbID.'
def get_imdbCompanyID(self, companyID):
try: company = CompanyName.get(companyID) except NotFoundError: return None imdbID = company.imdbID if (imdbID is not None): return ('%07d' % imdbID) n_dict = {'name': company.name, 'country': company.countryCode} namline = build_company_name(n_dict) imdbID = self.com...
'If set to 0 or False, movies in the Adult category are not episodeOf = title_dict.get(\'episode of\') shown in the results of a search.'
def do_adult_search(self, doAdult):
self.doAdult = doAdult
'Ensure that the connection is closed.'
def __del__(self):
if (not hasattr(self, '_connection')): return self._sql_logger.debug('closing connection to the database') self._connection.close()
'Initialize a TableAdapter object.'
def __init__(self, table, uri=None):
self._imdbpySchema = table self._imdbpyName = table.name self.connectionURI = uri self.colMap = {} columns = [] for col in table.cols: params = {'nullable': True} params.update(col.params) if (col.name == 'id'): params['primary_key'] = True if ('notNon...
'Return a list of results.'
def select(self, conditions=None):
result = self._ta_select(conditions).execute() return ResultAdapter(result, self.table, colMap=self.colMap)
'Get an object given its ID.'
def get(self, theID):
result = self.select((self.table.c.id == theID)) try: return result[0] except KeyError: raise NotFoundError(('no data for ID %s' % theID))
'Drop the table.'
def dropTable(self, checkfirst=True):
dropParams = {'checkfirst': checkfirst} if self.table.bind.engine.url.drivername.startswith('ibm_db'): del dropParams['checkfirst'] try: self.table.drop(**dropParams) except exc.ProgrammingError: if (not self.table.bind.engine.url.drivername.startswith('ibm_db')): rai...
'Create the table.'
def createTable(self, checkfirst=True):
self.table.create(checkfirst=checkfirst) for col in self._imdbpySchema.cols: if (col.name == 'id'): continue if col.params.get('alternateID', False): self._createIndex(col, checkfirst=checkfirst)
'Create an index for a given (schema) column.'
def _createIndex(self, col, checkfirst=True):
idx_name = ('%s_%s' % (self.table.name, (col.index or col.name))) if checkfirst: for index in self.table.indexes: if (index.name == idx_name): return idx = Index(idx_name, getattr(self.table.c, self.colMap[col.name])) try: idx.create() except exc.Operation...
'Create all required indexes.'
def addIndexes(self, ifNotExists=True):
for col in self._imdbpySchema.cols: if col.index: self._createIndex(col, checkfirst=ifNotExists)
'Create all required foreign keys.'
def addForeignKeys(self, mapTables, ifNotExists=True):
if (not HAS_MC): return countCols = 0 for col in self._imdbpySchema.cols: countCols += 1 if (not col.foreignKey): continue fks = col.foreignKey.split('.', 1) foreignTableName = fks[0] if (len(fks) == 2): foreignColName = fks[1] ...
'To insert a new row with the syntax: TableClass(key=value, ...)'
def __call__(self, *args, **kwds):
taArgs = {} for (key, value) in kwds.items(): taArgs[self.colMap.get(key, key)] = value self._ta_insert.execute(*args, **taArgs)
'Class representation.'
def __str__(self):
s = ('<DBCol %s %s' % (self.name, _strMap[self.kind])) if self.index: s += ' INDEX' if self.indexLen: s += ('[:%d]' % self.indexLen) if self.foreignKey: s += ' FOREIGN' if ('default' in self.params): val = self.params['default'] if (val is ...
'Class representation.'
def __repr__(self):
s = ('<DBCol(name="%s", %s' % (self.name, _strMap[self.kind])) if self.index: s += (', index="%s"' % self.index) if self.indexLen: s += (', indexLen=%d' % self.indexLen) if self.foreignKey: s += (', foreignKey="%s"' % self.foreignKey) for param in self.params: ...
'Class representation.'
def __str__(self):
return ('<DBTable %s (%d cols, %d values)>' % (self.name, len(self.cols), sum([len(v) for v in self.values.values()])))
'Class representation.'
def __repr__(self):
s = ('<DBTable(name="%s"' % self.name) col_s = ', '.join([repr(col).rstrip('>').lstrip('<') for col in self.cols]) if col_s: s += (', %s' % col_s) if self.values: s += (', values=%s' % self.values) s += ')>' return s
'Initialize the exception and pass the message to the log system.'
def __init__(self, *args, **kwargs):
self._logger.critical('%s exception raised; args: %s; kwds: %s', self.__class__.__name__, args, kwargs, exc_info=True) Exception.__init__(self, *args, **kwargs)
'Initialize a Movie object. *movieID* -- the unique identifier for the movie. *title* -- the title of the Movie, if not in the data dictionary. *myTitle* -- your personal title for the movie. *myID* -- your personal identifier for the movie. *data* -- a dictionary used to initialize the object. *currentRole* -- a Chara...
def _init(self, **kwds):
title = kwds.get('title') if (title and (not self.data.has_key('title'))): self.set_title(title) self.movieID = kwds.get('movieID', None) self.myTitle = kwds.get('myTitle', u'')
'Reset the Movie object.'
def _reset(self):
self.movieID = None self.myTitle = u''
'Set the title of the movie.'
def set_title(self, title):
d_title = analyze_title(title) self.data.update(d_title)
'Valid keys to append to the data.keys() list.'
def _additional_keys(self):
addkeys = [] if self.data.has_key('title'): addkeys += ['canonical title', 'long imdb title', 'long imdb canonical title', 'smart canonical title', 'smart long imdb canonical title'] if self.data.has_key('episode of'): addkeys += ['long imdb episo...
'Guess the language of the title of this movie; returns None if there are no hints.'
def guessLanguage(self):
lang = self.get('languages') if lang: lang = lang[0] else: country = self.get('countries') if country: lang = linguistics.COUNTRY_LANG.get(country[0]) return lang
'Return the canonical title, guessing its language. The title can be forces with the \'title\' argument (internally used) and the language can be forced with the \'lang\' argument, otherwise it\'s auto-detected.'
def smartCanonicalTitle(self, title=None, lang=None):
if (title is None): title = self.data.get('title', u'') if (lang is None): lang = self.guessLanguage() return canonicalTitle(title, lang=lang)
'Handle special keys.'
def _getitem(self, key):
if self.data.has_key('episode of'): if (key == 'long imdb episode title'): return build_title(self.data) elif (key == 'series title'): return self.data['episode of']['title'] elif (key == 'canonical series title'): ser_title = self....
'Return the movieID.'
def getID(self):
return self.movieID
'The Movie is "false" if the self.data does not contain a title.'
def __nonzero__(self):
if self.data.has_key('title'): return 1 return 0
'Return true if this and the compared object have the same long imdb title and/or movieID.'
def isSameTitle(self, other):
if (not isinstance(other, self.__class__)): return 0 if (self.data.has_key('title') and other.data.has_key('title') and (build_title(self.data, canonical=0) == build_title(other.data, canonical=0))): return 1 if ((self.accessSystem == other.accessSystem) and (self.movieID is not None) and (s...
'Return true if the given Person object is listed in this Movie, or if the the given Character is represented in this Movie.'
def __contains__(self, item):
from Person import Person from Character import Character from Company import Company if isinstance(item, Person): for p in flatten(self.data, yieldDictKeys=1, scalar=Person, toDescend=(list, dict, tuple, Movie)): if item.isSame(p): return 1 elif isinstance(item, ...
'Return a deep copy of a Movie instance.'
def __deepcopy__(self, memo):
m = Movie(title=u'', movieID=self.movieID, myTitle=self.myTitle, myID=self.myID, data=deepcopy(self.data, memo), currentRole=deepcopy(self.currentRole, memo), roleIsPerson=self._roleIsPerson, notes=self.notes, accessSystem=self.accessSystem, titlesRefs=deepcopy(self.titlesRefs, memo), namesRefs=deepcopy(self.namesR...
'String representation of a Movie object.'
def __repr__(self):
if self.has_key('long imdb episode title'): title = self.get('long imdb episode title') else: title = self.get('long imdb title') r = ('<Movie id:%s[%s] title:_%s_>' % (self.movieID, self.accessSystem, title)) if isinstance(r, unicode): r = r.encode(...
'Simply print the short title.'
def __str__(self):
return self.get('title', u'').encode('utf_8', 'replace')
'Simply print the short title.'
def __unicode__(self):
return self.get('title', u'')
'Return a string with a pretty-printed summary for the movie.'
def summary(self):
if (not self): return u'' def _nameAndRole(personList, joiner=u', '): 'Build a pretty string with name and role.' nl = [] for person in personList: n = person.get('name', u'') if person.currentRole: n += (u' (%s)'...
'Initialize a company object. *companyID* -- the unique identifier for the company. *name* -- the name of the company, if not in the data dictionary. *myName* -- the nickname you use for this company. *myID* -- your personal id for this company. *data* -- a dictionary used to initialize the object. *notes* -- notes abo...
def _init(self, **kwds):
name = kwds.get('name') if (name and (not self.data.has_key('name'))): self.set_name(name) self.companyID = kwds.get('companyID', None) self.myName = kwds.get('myName', u'')
'Reset the company object.'
def _reset(self):
self.companyID = None self.myName = u''
'Set the name of the company.'
def set_name(self, name):
oname = name = name.strip() notes = u'' if name.endswith(')'): fparidx = name.find('(') if (fparidx != (-1)): notes = name[fparidx:] name = name[:fparidx].rstrip() if self.notes: name = oname d = analyze_company_name(name) self.data.update(d) i...
'Valid keys to append to the data.keys() list.'
def _additional_keys(self):
if self.data.has_key('name'): return ['long imdb name'] return []
'Handle special keys.'
def _getitem(self, key):
if self.data.has_key('name'): if (key == 'long imdb name'): return build_company_name(self.data) return None
'Return the companyID.'
def getID(self):
return self.companyID
'The company is "false" if the self.data does not contain a name.'
def __nonzero__(self):
if self.data.get('name'): return 1 return 0
'Return true if this company and the given Movie are related.'
def __contains__(self, item):
from Movie import Movie if isinstance(item, Movie): for m in flatten(self.data, yieldDictKeys=1, scalar=Movie): if item.isSame(m): return 1 return 0
'Return true if two company have the same name and/or companyID.'
def isSameName(self, other):
if (not isinstance(other, self.__class__)): return 0 if (self.data.has_key('name') and other.data.has_key('name') and (build_company_name(self.data) == build_company_name(other.data))): return 1 if ((self.accessSystem == other.accessSystem) and (self.companyID is not None) and (self.companyI...
'Return a deep copy of a company instance.'
def __deepcopy__(self, memo):
c = Company(name=u'', companyID=self.companyID, myName=self.myName, myID=self.myID, data=deepcopy(self.data, memo), notes=self.notes, accessSystem=self.accessSystem, titlesRefs=deepcopy(self.titlesRefs, memo), namesRefs=deepcopy(self.namesRefs, memo), charactersRefs=deepcopy(self.charactersRefs, memo)) c.curren...
'String representation of a Company object.'
def __repr__(self):
r = ('<Company id:%s[%s] name:_%s_>' % (self.companyID, self.accessSystem, self.get('long imdb name'))) if isinstance(r, unicode): r = r.encode('utf_8', 'replace') return r
'Simply print the short name.'
def __str__(self):
return self.get('name', u'').encode('utf_8', 'replace')
'Simply print the short title.'
def __unicode__(self):
return self.get('name', u'')
'Return a string with a pretty-printed summary for the company.'
def summary(self):
if (not self): return u'' s = (u'Company\n=======\nName: %s\n' % self.get('name', u'')) for k in ('distributor', 'production company', 'miscellaneous company', 'special effects company'): d = self.get(k, [])[:5] if (not d): continue s += (u'Last ...
'A hack to get around the deprecation errors in 2.6.'
@property def message(self):
return self._message
'Returns this token as a plain string, suitable for storage. The resulting string includes the token\'s secret, so you should never send or store this string where a third party can read it.'
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)
'Deserializes a token from a string like one returned by `to_string()`.'
@staticmethod def from_string(s):
if (not len(s)): raise ValueError('Invalid parameter string.') params = parse_qs(s, keep_blank_values=False) if (not len(params)): raise ValueError('Invalid parameter string.') try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_...
'Get any non-OAuth parameters.'
def get_nonoauth_parameters(self):
return dict([(k, v) for (k, v) in self.iteritems() if (not k.startswith('oauth_'))])
'Serialize as a header for an HTTPAuth request.'
def to_header(self, realm=''):
oauth_params = ((k, v) for (k, v) in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for (k, v) in oauth_params) header_params = (('%s="%s"' % (k, v)) for (k, v) in stringy_params) params_header = ', '.join(header_params) auth_header = ('OAuth realm="%s"' % realm)...
'Serialize as post data for a POST request.'
def to_postdata(self):
return self.encode_postdata(self)
'Serialize as a URL for a GET request.'
def to_url(self):
return ('%s?%s' % (self.url, self.to_postdata()))
'Return a string that contains the parameters that must be signed.'
def get_normalized_parameters(self):
items = [(k, v) for (k, v) in self.items() if (k != 'oauth_signature')] encoded_str = urllib.urlencode(sorted(items), True) return encoded_str.replace('+', '%20')
'Set the signature parameter to the result of sign.'
def sign_request(self, signature_method, consumer, token):
if ('oauth_consumer_key' not in self): self['oauth_consumer_key'] = consumer.key if (token and ('oauth_token' not in self)): self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token)
'Get seconds since epoch (UTC).'
@classmethod def make_timestamp(cls):
return str(int(time.time()))
'Generate pseudorandom number.'
@classmethod def make_nonce(cls):
return str(random.randint(0, 100000000))
'Combines multiple parameter sources.'
@classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None):
if (parameters is None): parameters = {} if (headers and ('Authorization' in headers)): auth_header = headers['Authorization'] if (auth_header[:6] == 'OAuth '): auth_header = auth_header[6:] try: header_params = cls._split_header(auth_header) ...
'Turn Authorization: header into parameters.'
@staticmethod def _split_header(header):
params = {} parts = header.split(',') for param in parts: if (param.find('realm') > (-1)): continue param = param.strip() param_parts = param.split('=', 1) params[param_parts[0]] = urllib.unquote(param_parts[1].strip('"')) return params
'Turn URL string into parameters.'
@staticmethod def _split_url_string(param_str):
parameters = parse_qs(param_str, keep_blank_values=False) for (k, v) in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters
'Verifies an api call and checks all the parameters.'
def verify_request(self, request, consumer, token):
version = self._get_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters