当前位置: 首页>>代码示例>>Python>>正文


Python yattag.indent方法代码示例

本文整理汇总了Python中yattag.indent方法的典型用法代码示例。如果您正苦于以下问题:Python yattag.indent方法的具体用法?Python yattag.indent怎么用?Python yattag.indent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yattag的用法示例。


在下文中一共展示了yattag.indent方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_token

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def get_token(request, data):
    """ Issue a token to user after verying his API_KEY
    """
    output_format = data.get('format', 'xml')
    api_key = data.get('api_key')

    if not api_key:
        raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format)   # Missing required params
    if not Token.is_valid_api_key(api_key):
        raise InvalidAPIUsage(CompatError.INVALID_API_KEY, output_format=output_format)      # Invalid API_KEY

    token = Token.generate(api_key)

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('token'):
            text(token.token)
    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           output_format) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:21,代码来源:api_compat.py

示例2: get_xml_from_daily_schedule

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def get_xml_from_daily_schedule(self, currentTime, bgImageURL, datalist):

        now = datetime.now()
        time = now.strftime("%B %d, %Y")
        doc, tag, text, line = Doc(

        ).ttl()
        doc.asis('<?xml version="1.0" encoding="UTF-8"?>')
        with tag('schedule', currently_playing_bg_image=bgImageURL if bgImageURL != None else ''):
            for row in datalist:
                if str(row[11]) == "Commercials" and self.DEBUG == False:
                    continue
                timeB = datetime.strptime(row[8], '%I:%M:%S %p')
                if currentTime == None:
                    with tag('time',
                            ('data-key', str(row[12])),
                            ('data-current', 'false'),
                            ('data-type', str(row[11])),
                            ('data-title', str(row[3])),
                            ('data-start-time', str(row[8])),
                        ):
                        text(row[8])
                elif currentTime.hour == timeB.hour and currentTime.minute == timeB.minute:
                    with tag('time',
                            ('data-key', str(row[12])),
                            ('data-current', 'true'),
                            ('data-type', str(row[11])),
                            ('data-title', str(row[3])),
                            ('data-start-time', str(row[8])),
                        ):
                        text(row[8])
                else:
                    with tag('time',
                            ('data-key', str(row[12])),
                            ('data-current', 'false'),
                            ('data-type', str(row[11])),
                            ('data-title', str(row[3])),
                            ('data-start-time', str(row[8])),
                        ):
                        text(row[8])
        return indent(doc.getvalue()) 
开发者ID:justinemter,项目名称:pseudo-channel,代码行数:43,代码来源:PseudoDailyScheduleController.py

示例3: writeReport

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def writeReport(self):
        with open("{}/report.html".format(self.reportDir), 'w') as report:
            report.write(indent(self.doc.getvalue())) 
开发者ID:BishopFox,项目名称:IDontSpeakSSL,代码行数:5,代码来源:idontspeakssl_report.py

示例4: write_report

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def write_report(self):
		with open("{}/report.html".format(self.report_folder), 'w') as report:
			report.write(indent(self.doc.getvalue())) 
开发者ID:BishopFox,项目名称:IDontSpeakSSL,代码行数:5,代码来源:idontspeakssl_reporter.py

示例5: get_html_report

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def get_html_report(orig_sents: List[str], sys_sents: List[str], refs_sents: List[List[str]], test_set: str,
                    lowercase: bool = False, tokenizer: str = '13a', metrics: List[str] = DEFAULT_METRICS):
    doc = Doc()
    doc.asis('<!doctype html>')
    with doc.tag('html', lang='en'):
        doc.asis(get_head_html())
        with doc.tag('body', klass='container-fluid m-2 mb-5'):
            doc.line('h1', 'EASSE report', klass='mt-4')
            with doc.tag('a', klass='btn btn-link', href='https://forms.gle/J8KVkJsqYe8GvYW46'):
                doc.text('Any feedback welcome!')
            doc.stag('hr')
            doc.line('h2', 'Test set')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_test_set_description_html(
                    test_set=test_set,
                    orig_sents=orig_sents,
                    refs_sents=refs_sents,
                ))
            doc.line('h2', 'Scores')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.line('h3', 'System vs. Reference')
                doc.stag('hr')
                doc.asis(get_score_table_html_single_system(orig_sents, sys_sents, refs_sents, lowercase, tokenizer, metrics))
                doc.line('h3', 'By sentence length (characters)')
                doc.stag('hr')
                doc.asis(get_scores_by_length_html(orig_sents, sys_sents, refs_sents))
            doc.line('h2', 'Plots')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_plots_html(orig_sents, sys_sents, refs_sents[0]))
            doc.line('h2', 'Qualitative evaluation')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_qualitative_examples_html(orig_sents, sys_sents, refs_sents))
    return indent(doc.getvalue()) 
开发者ID:feralvam,项目名称:easse,代码行数:39,代码来源:report.py

示例6: get_multiple_systems_html_report

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def get_multiple_systems_html_report(orig_sents, sys_sents_list, refs_sents, system_names, test_set, lowercase, tokenizer, metrics):
    doc = Doc()
    doc.asis('<!doctype html>')
    with doc.tag('html', lang='en'):
        doc.asis(get_head_html())
        with doc.tag('body', klass='container-fluid m-2 mb-5'):
            doc.line('h1', 'EASSE report', klass='mt-4')
            with doc.tag('a', klass='btn btn-link', href='https://forms.gle/J8KVkJsqYe8GvYW46'):
                doc.text('Any feedback welcome!')
            doc.stag('hr')
            doc.line('h2', 'Test set')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_test_set_description_html(
                    test_set=test_set,
                    orig_sents=orig_sents,
                    refs_sents=refs_sents,
                ))
            doc.line('h2', 'Scores')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.line('h3', 'System vs. Reference')
                doc.stag('hr')
                doc.asis(get_score_table_html_multiple_systems(orig_sents, sys_sents_list, refs_sents, system_names, lowercase, tokenizer, metrics))
            doc.line('h2', 'Qualitative evaluation')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_multiple_systems_qualitative_examples_html(orig_sents, sys_sents_list, refs_sents, system_names))
    return indent(doc.getvalue()) 
开发者ID:feralvam,项目名称:easse,代码行数:31,代码来源:report.py

示例7: session_info

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def session_info(request, data):
    try:
        sk = data['sk']
        api_key = data['api_key']
        output_format = data.get('format', 'xml')
        username = data['username']
    except KeyError:
        raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format)        # Missing Required Params

    session = Session.load(sk)
    if (not session) or User.load_by_name(username).id != session.user.id:
        raise InvalidAPIUsage(CompatError.INVALID_SESSION_KEY, output_format=output_format)       # Invalid Session KEY

    print("SESSION INFO for session %s, user %s" % (session.id, session.user.name))

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('application'):
            with tag('session'):
                with tag('name'):
                    text(session.user.name)
                with tag('key'):
                    text(session.id)
                with tag('subscriber'):
                    text('0')
                with tag('country'):
                    text('US')

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           output_format) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:32,代码来源:api_compat.py

示例8: get_session

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def get_session(request, data):
    """ Create new session after validating the API_key and token.
    """
    output_format = data.get('format', 'xml')
    try:
        api_key = data['api_key']
        token = Token.load(data['token'], api_key)
    except KeyError:
        raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format)   # Missing Required Params

    if not token:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(CompatError.INVALID_API_KEY, output_format=output_format)  # Invalid API_key
        raise InvalidAPIUsage(CompatError.INVALID_TOKEN, output_format=output_format)        # Invalid token
    if token.has_expired():
        raise InvalidAPIUsage(CompatError.TOKEN_EXPIRED, output_format=output_format)        # Token expired
    if not token.user:
        raise InvalidAPIUsage(CompatError.UNAUTHORIZED_TOKEN, output_format=output_format)   # Unauthorized token

    session = Session.create(token)

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('session'):
            with tag('name'):
                text(session.user.name)
            with tag('key'):
                text(session.sid)
            with tag('subscriber'):
                text('0')

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           data.get('format', "xml")) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:35,代码来源:api_compat.py

示例9: to_json

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def to_json(self):
        return ujson.dumps({
            "error": self.api_error.code,
            "message": self.api_error.message
        }, indent=4) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:7,代码来源:errors.py

示例10: to_xml

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def to_xml(self):
        doc, tag, text = Doc().tagtext()
        with tag('lfm', status="failed"):
            with tag('error', code=self.api_error.code):
                text(self.api_error.message)
        return '<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:8,代码来源:errors.py

示例11: dump_html

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def dump_html(args, results):

    doc = yattag.Doc()

    with doc.tag('style', type='text/css'):
        doc.asis(css)

    logging.info('Dumping Localisation')
    doc.line('h2', 'Fishing Localisation')
    ydump_fishing_localisation(doc, results['localisation'])
    doc.stag('hr')

    with open(args.dest_path, 'w') as f:
        logging.info('Writing output')
        f.write(yattag.indent(doc.getvalue(), indent_text=True)) 
开发者ID:GlobalFishingWatch,项目名称:vessel-classification,代码行数:17,代码来源:compute_fishing_metrics.py

示例12: dump_html

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def dump_html(args, results):

    doc = yattag.Doc()

    with doc.tag('style', type='text/css'):
        doc.asis(css)

    for key, heading in CLASSIFICATION_METRICS:
        if results[key]:
            logging.info('Dumping "{}"'.format(heading))
            doc.line('h2', heading)
            wts = results['class_weights'] if (key=='fine') else None
            ydump_metrics(doc, results[key], results['class_weights'])
            doc.stag('hr')

    logging.info('Dumping Length')
    doc.line('h2', 'Length Inference')
    ydump_attrs(doc, results['length'])
    doc.stag('hr')
    logging.info('Dumping Tonnage')
    doc.line('h2', 'Tonnage Inference')
    ydump_attrs(doc, results['tonnage'])
    doc.stag('hr')
    logging.info('Dumping Engine Power')
    doc.line('h2', 'Engine Power Inference')
    ydump_attrs(doc, results['engine_power'])
    doc.stag('hr')
    logging.info('Dumping Crew Size')
    doc.line('h2', 'Crew Size Inference')
    ydump_attrs(doc, results['crew_size'])
    doc.stag('hr')


    with open(args.dest_path, 'w') as f:
        logging.info('Writing output')
        f.write(yattag.indent(doc.getvalue(), indent_text=True)) 
开发者ID:GlobalFishingWatch,项目名称:vessel-classification,代码行数:38,代码来源:compute_vessel_metrics.py

示例13: record_listens

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def record_listens(request, data):
    """ Submit the listen in the lastfm format to be inserted in db.
        Accepts listens for both track.updateNowPlaying and track.scrobble methods.
    """
    output_format = data.get('format', 'xml')
    try:
        sk, api_key = data['sk'], data['api_key']
    except KeyError:
        raise InvalidAPIUsage(CompatError.INVALID_PARAMETERS, output_format=output_format)    # Invalid parameters

    session = Session.load(sk)
    if not session:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(CompatError.INVALID_API_KEY, output_format=output_format)   # Invalid API_KEY
        raise InvalidAPIUsage(CompatError.INVALID_SESSION_KEY, output_format=output_format)   # Invalid Session KEY

    lookup = defaultdict(dict)
    for key, value in data.items():
        if key in ["sk", "token", "api_key", "method", "api_sig"]:
            continue
        matches = re.match('(.*)\[(\d+)\]', key)
        if matches:
            key = matches.group(1)
            number = matches.group(2)
        else:
            number = 0
        lookup[number][key] = value

    if request.form['method'].lower() == 'track.updatenowplaying':
        for i, listen in lookup.items():
            if 'timestamp' not in listen:
                listen['timestamp'] = calendar.timegm(datetime.now().utctimetuple())

    # Convert to native payload then submit 'em after validation.
    listen_type, native_payload = _to_native_api(lookup, data['method'], output_format)
    for listen in native_payload:
        validate_listen(listen, listen_type)

    user = db_user.get(session.user_id)
    augmented_listens = insert_payload(native_payload, user, listen_type=listen_type)

    # With corrections than the original submitted listen.
    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        if listen_type == 'playing_now':
            doc.asis(create_response_for_single_listen(list(lookup.values())[0], augmented_listens[0], listen_type))
        else:
            accepted_listens = len(lookup.values())
            # Currently LB accepts all the listens and ignores none
            with tag('scrobbles', accepted=accepted_listens, ignored='0'):
                for original_listen, augmented_listen in zip(list(lookup.values()), augmented_listens):
                    doc.asis(create_response_for_single_listen(original_listen, augmented_listen, listen_type))

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           output_format) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:57,代码来源:api_compat.py

示例14: format_response

# 需要导入模块: import yattag [as 别名]
# 或者: from yattag import indent [as 别名]
def format_response(data, format="xml"):
    """ Convert the XML response to required format.
        NOTE: The order of attributes may change while converting from XML to other formats.
        NOTE: The rendering format for the error does not follow these rules and has been managed separately
              in the error handlers.
        The response is a translation of the XML response format, converted according to the
        following rules:

        1. Attributes are expressed as string member values with the attribute name as key.
        2. Element child nodes are expressed as object members values with the node name as key.
        3. Text child nodes are expressed as string values, unless the element also contains
           attributes, in which case the text node is expressed as a string member value with the
           key #text.
        4. Repeated child nodes will be grouped as an array member with the shared node name as key.

        (The #text notation is rarely used in XML responses.)
    """
    if format == 'xml':
        return data
    elif format == 'json':
        # Remove the <lfm> tag and its attributes
        jsonData = xmltodict.parse(data)['lfm']
        for k in jsonData.keys():
            if k[0] == '@':
                jsonData.pop(k)

        def remove_attrib_prefix(data):
            """ Filter the JSON response to merge some attributes and clean dict.
                NOTE: This won't keep the dict ordered !!
            """
            if not isinstance(data, dict):
                return data
            for k in list(data.keys()):
                if k[0] == "@":
                    data[k[1:]] = data.pop(k)
                elif isinstance(data[k], str):
                    continue
                elif isinstance(data[k], list):
                    for ind, item in enumerate(data[k]):
                        data[k][ind] = remove_attrib_prefix(item)
                elif isinstance(data[k], dict):
                    data[k] = remove_attrib_prefix(data[k])
                else:
                    print(type(data[k]))
            return data

        return json.dumps(remove_attrib_prefix(jsonData), indent=4) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:49,代码来源:api_compat.py


注:本文中的yattag.indent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。