【问题标题】:Trying to use Mako template in python to render json data尝试在 python 中使用 Mako 模板来呈现 json 数据
【发布时间】:2017-03-28 16:26:55
【问题描述】:

我不了解在 python 中使用 Mako 模板的文档。我有一个 python 文件,我有以下代码:

import json, requests, urllib2
from mako.template import Template
from mako.lookup import TemplateLookup
from pylons.templating import render_mako as render

url="www.data&format=json"
response = urllib2.urlopen(url)
data = json.load(response)
return (Template("hello Luisito! Here is the data: ${data}!").render(json_data=data))

有人能给我提供一些关于如何使用 mako 模板将这个 json 数据呈现到网页中的更多细节吗?我需要另一个包含模板的文件吗?如果是这样,如何?

【问题讨论】:

  • 您的问题的哪一部分需要字符串格式无法实现的 HTML 模板库?
  • 您使用的是什么网络框架?你应该去阅读关于那个的文档。 def navigation(self): 自己什么都不做。
  • @cricket_007 基本上输入将是一个 json 对象,我想使用模板来显示该对象的结果
  • 作为 HTML,还是只是一个 JSON 字符串?你可以print(data)。在您的问题中,我认为不需要 Mako。您甚至有运行网络服务器以在页面上显示 HTML 吗?
  • @cricket_007 到目前为止,我已经对代码进行了编辑,取消了导航方法。我不确定如何让服务器运行

标签: python web mako


【解决方案1】:

你需要为json数据添加一个变量:

url="www.data&format=json"
response = urllib2.urlopen(url)
data = json.load(response)   
from mako.template import Template
print(Template("hello Luisito! Here is the data: ${json_data}!").render(json_data=data))

【讨论】:

  • 我认为 OP 想要呈现 HTML 模板。这只是打印到控制台
  • @rofls 我将如何在 mako 模板上显示该响应?
  • @cricket_007 说的对,你知道怎么渲染成html模板吗?
【解决方案2】:
from mako.template import Template
from mako.lookup import TemplateLookup
from mako import exceptions
from mako.exceptions import RichTraceback
import json

 var data = {
    "Records": [
        { 
            "pageName":"oracle.html", 
            "seoMetaData":"A page's description, usually one or two sentences.", 
            "logoImg":"./images/oracle-cloud-logo-400x336.png", 
            "logoImgUrl":"http://www.oracle.com",
            "description": "Oracle Cloud is a cloud computing service offered by Oracle Corporation providing servers, storage, network, applications and services through a global network of Oracle Corporation managed data centers. The company allows these services to be provisioned on demand over the Internet. Also, we provide the list of companies that use Oracle Cloud.",
            "product": "Oracle",
            "category": "CRM & Related",
            "customerAccount": "125,000 - 150,000"
        },
        { 
            "pageName":"microsoft.html", 
            "seoMetaData":"A page's description, usually one or two sentences.", 
            "logoImg":"./images/oracle-cloud-logo-400x336.png", 
            "logoImgUrl":"http://www.microsoft.com",
            "description": "Microsoft Cloud is a cloud computing service offered by Microsoft Corporation providing servers, storage, network, applications and services through a global network of Microsoft Corporation managed data centers. The company allows these services to be provisioned on demand over the Internet. Also, we provide the list of companies that use Microsoft Cloud.",
            "product": "Microsoft",
            "category": "CRM & Related",
            "customerAccount": "200,000 - 250,000"
        }
    ]
}

mylookup = TemplateLookup(directories=['./html'], output_encoding='utf-8', encoding_errors='replace')
uri = 'base.html'

def browseLocal(webpageText, filename):
    '''Start your webbrowser on a local file containing the text
    with given filename.'''
    import webbrowser, os.path
    strToFile(webpageText, filename)
    # webbrowser.open("file:///" + os.path.abspath(filename)) #elaborated for Mac.

def strToFile(text, filename):
    """Write a file with the given name and the given text."""
    output = open(filename,"w")
    output.write(text)
    output.close()

def fileToStr(fileName): # NEW
    """Return a string containing the contents of the named file."""
    fin = open(fileName); 
    contents = fin.read();  
    fin.close() 
    return contents

f = open("data.json", "r")
data = f.read()
jsonData = json.loads(data)
list1 = jsonData["Records"]
for val in list1:
    pageName = val["pageName"]
    seoMetaData = val["seoMetaData"]
    logoImg = val["logoImg"]
    logoImgUrl = val["logoImgUrl"]
    description = val["description"]
    product = val["product"]
    category = val["category"]
    customerAccount = val["customerAccount"]

    template = mylookup.get_template(uri)
    htmlContent = template.render_unicode(name=pageName, seoMetaData=seoMetaData, logoImg=logoImg, logoImgUrl=logoImgUrl, description=description, product=product, category=category, customerAccount=customerAccount)
    browseLocal(htmlContent, pageName)
f.close()

【讨论】:

  • 我现在正在尝试这种方法。希望这会有所帮助
猜你喜欢
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多