简单的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 框架发送结果到浏览器。

相关推荐
hef2884 小时前
如何生成特定SQL的AWR报告_@awrsqrpt.sql深度剖析单条语句性能
jvm·数据库·python
Jinkxs5 小时前
从语法纠错到项目重构:Python+Copilot 的全流程开发效率提升指南
python·重构·copilot
技术专家5 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
段一凡-华北理工大学5 小时前
【大模型+知识图谱+工业智能体技术架构】~系列文章01:快速了解与初学入门!!!
人工智能·python·架构·知识图谱·工业智能体
IT小Qi5 小时前
iperf3网络测试工具
网络·python·测试工具·信息与通信·ip
以神为界5 小时前
Python入门实操:基础语法+爬虫入门+模块使用全指南
开发语言·网络·爬虫·python·安全·web
xcjbqd05 小时前
Python API怎么加Token认证_JWT生成与验证拦截器实现
jvm·数据库·python
io_T_T6 小时前
如何调用google api 进行开发(使用免费版本)
python
逻辑驱动的ken6 小时前
Java高频面试题:03
java·开发语言·面试·求职招聘·春招
噜噜大王_6 小时前
深入理解 C 语言内存操作函数:memcpy、memmove、memset、memcmp
c语言·开发语言