cherrypy@Tutoril 6:What about m javascripts,CSS and images?

关注微信公众号(瓠悠笑软件部落),一起学习,一起摸鱼
huyouxiao.com
Web应用程序通常也由静态内容组成,例如javascript,CSS文件或图像。 CherryPy支持向最终用户提供静态内容。
假设您希望将样式表与应用程序相关联以显示蓝色背景颜色(为什么不呢?)。
首先,将以下样式表保存到名为style.css的文件中,并存储到本地目录public / css中。

body {
  background-color: blue;
}

现在让我们更新HTML代码,以便使用http:// localhost:8080 / static / css / style.css URL链接到样式表。

#! /usr/bin/python3
import os, os.path
import random
import string

import cherrypy

class StringGenerator(object):
    @cherrypy.expose
    def index(self):
        return """<html>
            <head>
                <link href="/static/css/style.css" rel="stylesheet">
            </head>
            <body>
                <form method="get" action="generate">
                    <input type="text"  value="8" name="length" />
                    <button type="submit">Give it now!</button>
                </form>
            </body>
         </html>"""

    @cherrypy.expose
    def generate(self, length=8):
        some_string = ''.join(random.sample(string.hexdigits, int(length)))
        cherrypy.session['mystring'] = some_string
        return some_string

    @cherrypy.expose
    def display(self):
        return cherrypy.session['mystring']

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    cherrypy.quickstart(StringGenerator(), '/', conf)

将其保存到名为tut06.py的文件中,并按如下方式运行:

$ python tut06.py

转到http://localhost:8080/,你会看到一个华丽的蓝色页面。

CherryPy支持提供单个文件或完整的目录结构。 大多数情况下,这就是你最终要做的事情,所以这就是上面代码所展示的内容。 首先,我们指出所有静态内容的根目录。 出于安全原因,这必须是绝对的路径。 如果您在查找与您的网址匹配时仅提供相对路径,CherryPy会抱怨。
然后我们指出路径段以/static开头的所有URL都将作为静态内容提供。 我们将该URL映射到公共目录,即根目录的直接子目录。 公共目录的整个子树将作为静态内容提供。 CherryPy会将URL映射到该目录中的路径。 这就是在public/css/style.css中找到/static/css/style.css的原因。

猜你喜欢

转载自blog.csdn.net/fudaxing/article/details/88642721
今日推荐