code stringlengths 1 18.2k |
|---|
def render(self, xml, context, raise_on_errors=True): """Render xml string and apply XSLT transfomation with context""" if xml: self.xml = xml # render XSL self.render_xsl(self.root, context) # create root XSL sheet xsl_ns = self.namespaces['xsl'] rootName = etree.QName(xsl_ns, 'stylesheet') root = etree.Element(rootNa... |
l.filename) if raise_on_errors: raise return self.xml else: return xml |
def handle_image_posts(function=None): """ Decorator for views that handles ajax image posts in base64 encoding, saving the image and returning the url """ @wraps(function, assigned=available_attrs(function)) def _wrapped_view(request, *args, **kwargs): if 'image' in request.META['CONTENT_TYPE']: name = default_storage... |
def verboselogs_class_transform(cls): """Make Pylint aware of our custom logger methods.""" if cls.name == 'RootLogger': for meth in ['notice', 'spam', 'success', 'verbose']: cls.locals[meth] = [scoped_nodes.Function(meth, None)] |
def verboselogs_module_transform(mod): """Make Pylint aware of our custom log levels.""" if mod.name == 'logging': for const in ['NOTICE', 'SPAM', 'SUCCESS', 'VERBOSE']: mod.locals[const] = [nodes.Const(const)] |
def cache_etag(request, *argz, **kwz): '''Produce etag value for a cached page. Intended for usage in conditional views (@condition decorator).''' response, site, cachekey = kwz.get('_view_data') or initview(request) if not response: return None return fjcache.str2md5( '{0}--{1}--{2}'.format( site.id if site else 'x', ... |
def cache_last_modified(request, *argz, **kwz): '''Last modification date for a cached page. Intended for usage in conditional views (@condition decorator).''' response, site, cachekey = kwz.get('_view_data') or initview(request) if not response: return None return response[1] |
def initview(request, response_cache=True): '''Retrieves the basic data needed by all feeds (host, feeds, etc) Returns a tuple of: 1. A valid cached response or None 2. The current site object 3. The cache key 4. The subscribers for the site (objects) 5. The feeds for the site (ids)''' http_host, path_info = ( smart_un... |
the user # didn't create a site yet. Creating a default one... site = models.Site( name='Default Feedjack Site/Planet', url=request.build_absolute_uri(request.path), title='Feedjack Site Title', description='Feedjack Site Description.' ' Please change this in the admin interface.', template='bootstrap' ) site.save() el... |
'') ) return (response, timezone.now()), None, cachekey hostdict[url] = site_id = site.id fjcache.hostcache_set(hostdict) if response_cache: response = fjcache.cache_get(site_id, cachekey) if response: return response, None, cachekey return None, site, cachekey |
def blogroll(request, btype): 'View that handles the generation of blogrolls.' response, site, cachekey = initview(request) if response: return response[0] template = loader.get_template('feedjack/{0}.xml'.format(btype)) ctx = dict() fjlib.get_extra_context(site, ctx) ctx = Context(ctx) response = HttpResponse( templat... |
def buildfeed(request, feedclass, **criterias): 'View that handles the feeds.' view_data = initview(request) wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias) return condition( etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified) )\ (_buildfeed)(request, feedclass, view_data, *... |
def mainview(request, **criterias): 'View that handles all page requests.' view_data = initview(request) wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias) return condition( etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified) )\ (_mainview)(request, view_data, **criterias) |
def index(request, obj_id=None): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request, obj_id) elif request.method == 'POST': return post(request) elif request.method == 'PUT': getPutData(request) return put(request, obj_id) elif request.method == 'DE... |
def post(request): """ Create a Gallery """ defaultname = 'New Gallery %i' % Gallery.objects.all().count() data = request.POST or json.loads(request.body)['body'] title = data.get('title', defaultname) description = data.get('description', '') security = int(data.get('security', Gallery.PUBLIC)) g, created = Gallery.ob... |
def put(request, obj_id=None): """ Adds Image and Video objects to Gallery based on GUIDs """ data = request.PUT or json.loads(request.body)['body'] guids = data.get('guids', '').split(',') move = data.get('from') security = request.PUT.get('security') gallery = Gallery.objects.get(pk=obj_id) if guids: objects = getObj... |
def delete(request, obj_id=None): """ Removes ImageVideo objects from Gallery """ data = request.DELETE or json.loads(request.body) guids = data.get('guids').split(',') objects = getObjectsFromGuids(guids) gallery = Gallery.objects.get(pk=obj_id) LOGGER.info('{} removed {} from {}'.format(request.user.email, guids, gal... |
def filterObjects(request, obj_id): """ Filters Gallery for the requested ImageVideo objects. Returns a Result object with serialized objects """ if int(obj_id) == 0: obj = None else: obj = Gallery.objects.get(pk=obj_id) isanonymous = request.user.is_anonymous() if isanonymous and obj is None: LOGGER.warn('There was an... |
def _filter(request, object_, tags=None, more=False, orderby='created'): """Filters Piece objects from self based on filters, search, and range :param tags: List of tag IDs to filter :type tags: list :param more -- bool, Returns more of the same filtered set of images based on session range return list, Objects filtere... |
o: o = Q() o |= Q(num_tags__lte=1) break elif isinstance(item, six.integer_types): # -- filter by tag if not o: o = Q() o |= Q(tags__id=item) else: # -- add to search string searchQuery += item + ' ' if not HAYSTACK: if not o: o = Q() # -- use a basic search o |= Q(title__icontains=item) if HAYSTACK and searchQuery != ... |
continue if not more: lastid = idDict[m.model][0] index = idDict[m.model].index(lastid) if more and lastid != 0: index += 1 idDict[m.model] = idDict[m.model][index:index + length] # -- perform the main query to retrieve the objects we want objDict[m.model] = m.model_class().objects.filter(id__in=idDict[m.model]) objDic... |
def _sortObjects(orderby='created', **kwargs): """Sorts lists of objects and combines them into a single list""" o = [] for m in kwargs.values(): for l in iter(m): o.append(l) o = list(set(o)) sortfunc = _sortByCreated if orderby == 'created' else _sortByModified if six.PY2: o.sort(sortfunc) else: o.sort(key=functools.... |
def _sortByCreated(a, b): """Sort function for object by created date""" if a.created < b.created: return 1 elif a.created > b.created: return -1 else: return 0 |
def _sortByModified(a, b): """Sort function for object by modified date""" if a.modified < b.modified: return 1 elif a.modified > b.modified: return -1 else: return 0 |
def search(query, model): """ Performs a search query and returns the object ids """ query = query.strip() LOGGER.debug(query) sqs = SearchQuerySet() results = sqs.raw_search('{}*'.format(query)).models(model) if not results: results = sqs.raw_search('*{}'.format(query)).models(model) if not results: results = sqs.raw_... |
def find(whatever=None, language=None, iso639_1=None, iso639_2=None, native=None): """Find data row with the language. :param whatever: key to search in any of the following fields :param language: key to search in English language name :param iso639_1: key to search in ISO 639-1 code (2 digits) :param iso639_2: key to... |
elif iso639_2: keys = [u'iso639_2_b', u'iso639_2_t'] val = iso639_2 elif native: keys = [u'native'] val = native else: raise ValueError('Invalid search criteria.') val = unicode(val).lower() return next((item for item in data if any( val in item[key].lower().split("; ") for key in keys)), None) |
def to_iso639_1(key): """Find ISO 639-1 code for language specified by key. >>> to_iso639_1("swe") u'sv' >>> to_iso639_1("English") u'en' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'iso639_1'] |
def to_iso639_2(key, type='B'): """Find ISO 639-2 code for language specified by key. :param type: "B" - bibliographical (default), "T" - terminological >>> to_iso639_2("German") u'ger' >>> to_iso639_2("German", "T") u'deu' """ if type not in ('B', 'T'): raise ValueError('Type must be either "B" or "T".') item = find(w... |
def to_name(key): """Find the English name for the language specified by key. >>> to_name('br') u'Breton' >>> to_name('sw') u'Swahili' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'name'] |
def to_native(key): """Find the native name for the language specified by key. >>> to_native('br') u'brezhoneg' >>> to_native('sw') u'Kiswahili' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'native'] |
def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"): """ Displays postal address with localized fields """ country_prefix = "country" prefix = request.POST.get('prefix', prefix) if prefix: country_prefix = prefix + '-country' country_code = request.POST.get(country_prefix, countr... |
def write_log(self, fs=None): """ Write the results of the benchmark to a log file. :param fs: file-like object. """ log = StringIO.StringIO() log.write(self.setup_src) # If the function is not bound, write the test score to the log if not self.is_class_method: time_avg = convert_time_units(self.time_average_seconds) l... |
def run_timeit(self, stmt, setup): """ Create the function call statement as a string used for timeit. """ _timer = timeit.Timer(stmt=stmt, setup=setup) trials = _timer.repeat(self.timeit_repeat, self.timeit_number) self.time_average_seconds = sum(trials) / len(trials) / self.timeit_number # Convert into reasonable tim... |
def _get_mx_exchanges(domain): """Fetch the MX records for the specified domain :param str domain: The domain to get the MX records for :rtype: list """ try: answer = resolver.query(domain, 'MX') return [str(record.exchange).lower()[:-1] for record in answer] except (resolver.NoAnswer, resolver.NoNameservers, resolver.... |
def _domain_check(domain, domain_list, resolve): """Returns ``True`` if the ``domain`` is serviced by the ``domain_list``. :param str domain: The domain to check :param list domain_list: The domains to check for :param bool resolve: Resolve the domain :rtype: bool """ if domain in domain_list: return True if resolve: f... |
def normalize(email_address, resolve=True): """Return the normalized email address, removing :param str email_address: The normalized email address :param bool resolve: Resolve the domain :rtype: str """ address = utils.parseaddr(email_address) local_part, domain_part = address[1].lower().split('@') # Plus addressing i... |
def validate(filename, verbose=False): """ Validate file and return JSON result as dictionary. "filename" can be a file name or an HTTP URL. Return "" if the validator does not return valid JSON. Raise OSError if curl command returns an error status. """ # is_css = filename.endswith(".css") is_remote = filename.startsw... |
def main(): """Parser the command line and run the validator.""" parser = argparse.ArgumentParser( description="[v" + __version__ + "] " + __doc__, prog="w3c_validator", ) parser.add_argument( "--log", default="INFO", help=("log level: DEBUG, INFO or INFO " "(default: INFO)")) parser.add_argument( "--version", action="... |
= result["cssvalidation"]["result"]["warningcount"] errors += errorcount warnings += warningcount if errorcount > 0: LOGGER.info("errors: %d" % errorcount) if warningcount > 0: LOGGER.info("warnings: %d" % warningcount) else: for msg in result["messages"]: print_msg(msg) if msg["type"] == "error": errors += 1 else: war... |
def format_info_response(value): """Format the response from redis :param str value: The return response from redis :rtype: dict """ info = {} for line in value.decode('utf-8').splitlines(): if not line or line[0] == '#': continue if ':' in line: key, value = line.split(':', 1) info[key] = parse_info_value(value) retur... |
def update(self, *args): """ Updates information about colors and their multiplicity in respective :class:`Multicolor` instance. By iterating over supplied arguments each of which should represent a color object, updates information about colors and their multiplicity in current :class:`Multicolor` instance. :param arg... |
def __delete(self, multicolor): """ Reduces information :class:`Multicolor` attribute by iterating over supplied colors data. In case supplied argument is a :class:`Multicolor` instance, multi-color specific information to de deleted is set to its :attr:`Multicolor.multicolors`. In other cases multi-color specific info... |
def __merge(cls, *multicolors): """ Produces a new :class:`Multicolor` object resulting from gathering information from all supplied :class:`Multicolor` instances. New :class:`Multicolor` is created and its :attr:`Multicolor.multicolors` attribute is updated with similar attributes of supplied :class:`Multicolor` objec... |
def __left_merge(multicolor1, multicolor2): """ Updates first supplied :class:`Multicolor` instance with information from second supplied :class:`Multicolor` instance. First supplied instances attribute :attr:`Multicolor.multicolors` is updated with a help of ``+`` method of python Counter object. :param multicolor1: i... |
def similarity_score(multicolor1, multicolor2): """ Computes how similar two :class:`Multicolor` objects are from perspective of information, that they contain. Two multicolors are called to be similar if they contain same colors (at least one). Multiplicity of colors is taken into account as well. :param multicolor1: ... |
def split_colors(cls, multicolor, guidance=None, sorted_guidance=False, account_for_color_multiplicity_in_guidance=True): """ Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object. Guidance is an iterable type of object whe... |
the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded. After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own. Multiplicity of all separated colors in respective chunks is p... |
# if guidance is not specified, it will be derived from colors in the targeted multicolor # initially the multiplicity of colors remains as is # ############################################################################################### guidance = [Multicolor(*(color for _ in range(multicolor.multicolors[color]))) ... |
guidance (even if original is perfect) # a new one shall preserve the order of the original, but all multicolors in it # while keeping information about the actual colors itself, shall have multiplicity equal to 1 # ############################################################################################### splittin... |
guidance shall be used "as is" # it is sorted to put "bigger" multicolors in front, and smaller at the back # as bigger multicolor might contain several smaller multicolors from the guidance, but the correct splitting # always assumes that the smaller is the splitted result, the better it is # and such minimization can... |
# and retrieve as many copies of it from the multicolor, as we can # Example: # multicolor has only one color "blue" with multiplicity "4" # in guidance we have multicolor with color "blue" with multiplicity "2" # we must retrieve it fully twice # ########################################################################... |
g_multicolor.intersect(splitting_multicolor) appendix = splitting_multicolor result = deepcopy(first_run_result) + deepcopy(second_run_result) + deepcopy([appendix] if len(appendix.multicolors) > 0 else []) if not account_for_color_multiplicity_in_guidance: ##############################################################... |
return result |
def intersect(self, other): """ Computes the multiset intersection, between the current Multicolor and the supplied Multicolor :param other: another Multicolor object to compute a multiset intersection with :return: :raise TypeError: an intersection can be computed only between two Multicolor objects """ if not isinsta... |
def text2wfreq(text, output_file, hashtablesize=1000000, verbosity=2): """ List of every word which occurred in the text, along with its number of occurrences. Notes : Uses a hash-table to provide an efficient method of counting word occurrences. Output list is not sorted (due to "randomness" of the hash-table), but ca... |
type(text) is str else text) input_f.seek(0) with open(output_file,'w+') as output_f: with output_to_debuglogger() as err_f: exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f) logger = logging.getLogger(__name__) logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exit... |
def wfreq2vocab(wfreq_file, output_file, top=None, gt=None, records=1000000, verbosity=2): """ Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file. The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, the... |
words. The records parameter (default: 1000000) allows the user to specify how many of the word and count records to allocate memory for. If the number of words in the input exceeds this number, then the function will fail and raise a ConversionError, but a high number will obviously result in a higher memory requireme... |
'%s'" % (cmd[0], exitcode)) |
def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2): """ List of every word n-gram which occurred in the text, along with its number of occurrences. The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and words parameters. "... |
% (' '.join(cmd), exitcode)) if exitcode != 0: raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) |
def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False): """ Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n. """ cmd = ['ngram2mgram', '-n', n, '-m', m] if words and ascii_idngram: raise ConversionError("Parameters 'words' and 'ascii_idngra... |
def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10): """ Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in ei... |
[str(x) for x in cmd] with tempfile.SpooledTemporaryFile() as output_f: with tempfile.SpooledTemporaryFile() as input_f: input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text) input_f.seek(0) with output_to_debuglogger() as err_f: with do_in_tempdir(): exitcode = subprocess.call... |
def idngram2stats(input_file, output_file, n=3, fof_size=50, verbosity=2, ascii_input=False): """ Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in idngram2lm.... |
def mergeidngram(output_file, input_files, n=3, ascii_input=False, ascii_output=False): """ Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram. Notes : This function can also be used to c... |
'.join(cmd), exitcode)) if exitcode != 0: raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) |
def idngram2lm(idngram_file, vocab_file, output_file, context_file=None, vocab_type=1, oov_fraction=0.5, four_byte_counts=False, min_unicount=0, zeroton_fraction=False, n=3, verbosity=2, arpa_output=True, ascii_input=False): """ Takes an idngram-file (in either binary (by default) or ASCII (if specified) format), a voc... |
os.path.abspath(idngram_file), '-vocab', os.path.abspath(vocab_file), '-vocab_type', vocab_type, '-oov_fraction', oov_fraction, '-min_unicount',min_unicount, '-verbosity',verbosity, '-n',n] if arpa_output: cmd.extend(['-arpa',output_file]) else: cmd.extend(['-binary',output_file]) if four_byte_counts: cmd.append('-four... |
def binlm2arpa(input_file, output_file, verbosity=2): """ Converts a binary format language model, as generated by idngram2lm, into an an ARPA format language model. """ cmd = ['binlm2arpa', '-binary', input_file, '-arpa'. output_file] if verbosity: cmd.extend(['-verbosity', verbosity]) # Ensure that every parameter is... |
def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}): """ Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text. """ with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f: wfreq_file = f.name try: text2wfreq(text, wfreq_file, **text2wfr... |
def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}): """ Convienience function to directly convert text (and vocabulary) into a language model. """ if vocab_file: used_vocab_file = vocab_file else: # Create temporary vocab file with tempfile.NamedTemporaryFile(suffix='.vocab', ... |
def pfadd(self, key, *elements): """Adds all the element arguments to the HyperLogLog data structure stored at the variable name specified as first argument. As a side effect of this command the HyperLogLog internals may be updated to reflect a different estimation of the number of unique items added so far (the cardin... |
exists, or just the creation of the data structure if the key does not exist (in the latter case ``1`` is returned). For an introduction to HyperLogLog data structure check :meth:`~tredis.RedisClient.pfcount`. .. versionadded:: 0.2.0 .. note:: **Time complexity**: ``O(1)`` to add every element. :param key: The key to a... |
def pfmerge(self, dest_key, *keys): """Merge multiple HyperLogLog values into an unique value that will approximate the cardinality of the union of the observed Sets of the source HyperLogLog structures. The computed merged HyperLogLog is set to the destination variable, which is created if does not exist (defaulting t... |
def construct(self): """ Recursively serialize a lot of types, and in cases where it doesn't recognize the type, it will fall back to Django's `smart_unicode`. Returns `dict`. """ def _any(thing, fields=None): """ Dispatch, all types are routed through here. """ ret = None if isinstance(thing, QuerySet): ret = _qs(thin... |
field.name)) def _related(data, fields=None): """ Foreign keys. """ return [ _model(m, fields) for m in data.iterator() ] def _m2m(data, field, fields=None): """ Many to many (re-route to `_model`.) """ return [ _model(m, fields) for m in getattr(data, field.name).iterator() ] def _model(data, fields=None): """ Models.... |
= set([ f.attname.replace("_id", "", 1) for f in data._meta.fields + data._meta.virtual_fields]) if hasattr(mapped, 'extra_fields'): get_fields.update(mapped.extra_fields) # sets can be negated. for exclude in exclude_fields: if isinstance(exclude, basestring): get_fields.discard(exclude) elif isinstance(exclude, re._p... |
inst = getattr(data, model, None) if inst: if hasattr(inst, 'all'): ret[model] = _related(inst, fields) elif callable(inst): if len(inspect.getargspec(inst)[0]) == 1: ret[model] = _any(inst(), fields) else: ret[model] = _model(inst, fields) elif maybe_field in met_fields: # Overriding normal field which has a "resource... |
= _any(getattr(data, k)) # resouce uri if self.in_typemapper(type(data), self.anonymous): handler = self.in_typemapper(type(data), self.anonymous) if hasattr(handler, 'resource_uri'): url_id, fields = handler.resource_uri(data) try: ret['resource_uri'] = permalink(lambda: (url_id, fields))() except NoReverseMatch, e: p... |
def get(cls, format): """ Gets an emitter, returns the class and a content-type. """ if cls.EMITTERS.has_key(format): return cls.EMITTERS.get(format) raise ValueError("No emitters found for type %s" % format) |
def register(cls, name, klass, content_type='text/plain'): """ Register an emitter. Parameters:: - `name`: The name of the emitter ('json', 'xml', 'yaml', ...) - `klass`: The emitter class. - `content_type`: The content type to serve response as. """ cls.EMITTERS[name] = (klass, content_type) |
def determine_emitter(self, request, *args, **kwargs): """ Function for determening which emitter to use for output. It lives here so you can easily subclass `Resource` in order to change how emission is detected. You could also check for the `Accept` HTTP header here, since that pretty much makes sense. Refer to `Mime... |
def form_validation_response(self, e): """ Method to return form validation error information. You will probably want to override this in your own `Resource` subclass. """ resp = rc.BAD_REQUEST resp.write(' '+str(e.form.errors)) return resp |
def anonymous(self): """ Gets the anonymous handler. Also tries to grab a class if the `anonymous` value is a string, so that we can define anonymous handlers that aren't defined yet (like, when you're subclassing your basehandler into an anonymous one.) """ if hasattr(self.handler, 'anonymous'): anon = self.handler.an... |
def cleanup_request(request): """ Removes `oauth_` keys from various dicts on the request object, and returns the sanitized version. """ for method_type in ('GET', 'PUT', 'POST', 'DELETE'): block = getattr(request, method_type, { }) if True in [ k.startswith("oauth_") for k in block.keys() ]: sanitized = block.copy() f... |
def error_handler(self, e, request, meth, em_format): """ Override this method to add handling of errors customized for your needs """ if isinstance(e, FormValidationError): return self.form_validation_response(e) elif isinstance(e, TypeError): result = rc.BAD_REQUEST hm = HandlerMethod(meth) sig = hm.signature msg = '... |
people in `settings.ADMINS`. - `PISTON_DISPLAY_ERRORS`: Will return a simple traceback to the caller, so he can tell you what error they got. If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will receive a basic "500 Internal Server Error" message. """ exc_type, exc_value, tb = sys.exc_info() rep = ExceptionReport... |
def parse(path): """ Parses xml and returns a formatted dict. Example: wpparser.parse("./blog.wordpress.2014-09-26.xml") Will return: { "blog": { "tagline": "Tagline", "site_url": "http://marteinn.se/blog", "blog_url": "http://marteinn.se/blog", "language": "en-US", "title": "Marteinn / Blog" }, "authors: [{ "login": "... |
"Text", "post_parent": "0", "post_password": None, "status": "publish", "description": None, "tags": ["tag"], "ping_status": "open", "post_id": "828", "link": "http://www.marteinn.se/blog/slug/", "pub_date": "Mon, 22 Sep 2014 20:10:40 +0000", "categories": ["category"], "is_sticky": "0", "post_name": "slug" }] } """ do... |
def _parse_blog(element): """ Parse and return genral blog data (title, tagline etc). """ title = element.find("./title").text tagline = element.find("./description").text language = element.find("./language").text site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text blog_url = element.find("./{%s}base_bl... |
def _parse_authors(element): """ Returns a well formatted list of users that can be matched against posts. """ authors = [] items = element.findall("./{%s}author" % WP_NAMESPACE) for item in items: login = item.find("./{%s}author_login" % WP_NAMESPACE).text email = item.find("./{%s}author_email" % WP_NAMESPACE).text fi... |
def _parse_categories(element): """ Returns a list with categories with relations. """ reference = {} items = element.findall("./{%s}category" % WP_NAMESPACE) for item in items: term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text nicename = item.find("./{%s}category_nicename" % WP_NAMESPACE).text name = item.find(... |
def _build_category_tree(slug, reference=None, items=None): """ Builds a recursive tree with category relations as children. """ if items is None: items = [] for key in reference: category = reference[key] if category["parent"] == slug: children = _build_category_tree(category["nicename"], reference=reference) category... |
def _parse_tags(element): """ Retrieves and parses tags into a array/dict. Example: [{"term_id": 1, "slug": "python", "name": "Python"}, {"term_id": 2, "slug": "java", "name": "Java"}] """ tags = [] items = element.findall("./{%s}tag" % WP_NAMESPACE) for item in items: term_id = item.find("./{%s}term_id" % WP_NAMESPACE... |
def _parse_posts(element): """ Returns a list with posts. """ posts = [] items = element.findall("item") for item in items: title = item.find("./title").text link = item.find("./link").text pub_date = item.find("./pubDate").text creator = item.find("./{%s}creator" % DC_NAMESPACE).text guid = item.find("./guid").text de... |
item_list.append(category_item.attrib["nicename"]) post = { "title": title, "link": link, "pub_date": pub_date, "creator": creator, "guid": guid, "description": description, "content": content, "excerpt": excerpt, "post_id": post_id, "post_date": post_date, "post_date_gmt": post_date_gmt, "status": status, "post_parent... |
def _parse_postmeta(element): import phpserialize """ Retrive post metadata as a dictionary """ metadata = {} fields = element.findall("./{%s}postmeta" % WP_NAMESPACE) for field in fields: key = field.find("./{%s}meta_key" % WP_NAMESPACE).text value = field.find("./{%s}meta_value" % WP_NAMESPACE).text if key == "_wp_at... |
def _parse_comments(element): """ Returns a list with comments. """ comments = [] items = element.findall("./{%s}comment" % WP_NAMESPACE) for item in items: comment_id = item.find("./{%s}comment_id" % WP_NAMESPACE).text author = item.find("./{%s}comment_author" % WP_NAMESPACE).text email = item.find("./{%s}comment_auth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.