简单的Python HTML 输出

1、问题背景

一名初学者在尝试将 Python 脚本输出到网页上时遇到了一些问题。他当前使用 Python 和 HTML 进行开发,并且遇到了以下问题:

  • 担心自己的代码过于复杂,尤其是 WebOutput() 函数。
  • 希望通过 JavaScript 使用 HTML 模板文件更新数据。
  • 不确定在什么情况下框架对应用程序是合适的。

2、解决方案

  • 优化 WebOutput() 函数,使其更加简洁和高效,并替换繁琐的代码为内联字符串。
  • 使用渲染模板引擎(例如 Mako)将 WebOutput() 函数改写为模板,以便在将来更容易地更改脚本的输出。
  • 修改搜索结果函数,使其返回结果列表而不是修改全局变量。
  • 使用 CherryPy 等 Web 框架将数据发送到浏览器,而不是不断地写入文件。
  • 使用模板系统(例如 Django)来生成输出,以避免 Python 代码和 HTML 代码的紧耦合。

代码例子:

python 复制代码
import simplejson, urllib, time, cherrypy

#query, results per page 
query = "swineflu"
rpp = 25
jsonURL = "http://search.twitter.com/search.json?q=" + query + "&rpp=" + str(rpp)

# iterate over search results
def SearchResults():
    jsonResults = simplejson.load(urllib.urlopen(jsonURL))
    data = []
    for tweet in jsonResults["results"]:
        try:
            # terminal output
            feed = tweet["from_user"] + " | " + tweet["text"]
            print(feed)
            data.append(feed)
        except:
            print("exception??")
    return data

# writes latest tweets to file/web
def WriteHTML(data):
    f = open("outw.html", "w")
    f.write("<html>\n")
    f.write("<title>python newb's twitter search</title>\n")
    f.write("<head><meta http-equiv='refresh' content='60'></head>\n")
    f.write("<body>\n")
    f.write("<h1 style='font-size:150%'>Python Newb's Twitter Search</h1>")
    f.write("<h2 style='font-size:125%'>Searching Twitter for: " + query + "</h2>\n")
    f.write("<h2 style='font-size:125%'>" + time.ctime() + " (updates every 60 seconds)</h2>\n")

    for i in range(1,rpp):
        try:
            f.write("<p style='font-size:90%'>" + data[-i] + "</p>\n")
        except:
            continue

    f.write("</body>\n")
    f.write("</html>\n")
    f.close()

while True:
    print("")
    print("\nSearching Twitter for: " + query + " | current date/time is: " + time.ctime())
    print("")
    data = SearchResults()
    WriteHTML(data)
    time.sleep(60)


class TwitterSearcher(object):
    def index(self):
        data = SearchResults()
        html = """<html>
        <head>
        <meta http-equiv='refresh' content='60'>
        <title>python newb's twitter search</title>
        </head>
        <body>
            <h1 style='font-size:150%%'>Python Newb's Twitter Search</h1>
            <h2 style='font-size:125%%'>Searching Twitter for: %(query)s</h2>
            <h2 style='font-size:125%%'> %(ctime)s (updates every 60 seconds)</h2>
        %(results_html)s
        </body>
        </html>
        """ % {
            'query': query,
            'ctime': time.ctime(),
            'results_html': "".join(["<p style='font-size:90%%'>%s</p>\n" % (result) for result in data])
        }
        return html
    index.exposed = True

cherrypy.quickstart(TwitterSearcher())

这个改进后的示例使用了模板系统来生成 HTML,并使用了 CherryPy 框架发送结果到浏览器。

相关推荐
xyq20248 分钟前
Vue3 条件语句详解
开发语言
这个名有人用不16 分钟前
解决 uv 虚拟环境使用 pip 命令提示command not found的办法
python·pip·uv·claude code
浩浩kids31 分钟前
R•Homework
开发语言·r语言
Oueii38 分钟前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
qq_4160187244 分钟前
设计模式在C++中的实现
开发语言·c++·算法
Evand J1 小时前
【MATLAB教程】在matlab中,gscatter和scatter两个命令的区别
开发语言·matlab·教程·绘图·命令·教学
2501_908329851 小时前
使用Python自动收发邮件
jvm·数据库·python
2301_776508721 小时前
C++与机器学习框架
开发语言·c++·算法
Albertbreak1 小时前
STL容器内部实现剖析
开发语言·c++·算法