所謂靜態資源,是指圖片、js、css等檔案。官方的說明在這裡。
以一個小項目來說明,下面是項目的目錄結構:
.├── static│ ├── css│ │ ├── base.css│ │ ├── bootstrap.min.css│ │ └── font-awesome.min.css│ ├── font│ │ ├── FontAwesome.otf│ │ ├── fontawesome-webfont.eot│ │ ├── fontawesome-webfont.svg│ │ ├── fontawesome-webfont.ttf│ │ └── fontawesome-webfont.woff│ └── index.html└── proxy_server.py
在proxy_server.py給2個靜態檔案目錄static/css和static/font添加路由:
app.router.add_static('/css/', path='static/css', name='css') app.router.add_static('/font/', path='static/font', name='font')
先來看看add_static方法的定義:
def add_static(self, prefix, path, *, name=None, expect_handler=None, chunk_size=256*1024, response_factory=StreamResponse, show_index=False, follow_symlinks=False): """Add static files view. prefix - url prefix path - folder with files """ # TODO: implement via PrefixedResource, not ResourceAdapter assert prefix.startswith('/') if prefix.endswith('/'): prefix = prefix[:-1] resource = StaticResource(prefix, path, name=name, expect_handler=expect_handler, chunk_size=chunk_size, response_factory=response_factory, show_index=show_index, follow_symlinks=follow_symlinks) self.register_resource(resource) return resource
必需的2個參數:
prefix:是靜態檔案的url的首碼,以/開始,在瀏覽器地址欄上顯示在網站host之後,也用於index.html靜態頁面進行引用
path:靜態檔案目錄的路徑,可以是相對路徑,上面代碼使用的static/css就是相對路徑——相對於proxy_server.py所在路徑。
下面是頁面的效果:
載入的是index.html,下面是它引用靜態資源的代碼:
<!-- Bootstrap CSS --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- Base CSS --><link href="css/base.css" rel="stylesheet"><!-- FA CSS --><link href="css/font-awesome.min.css" rel="stylesheet">
添加font的路徑是因為/font-awesome.min.css需要使用:
在瀏覽器中開啟css檔案:
可以看到是url的首碼是/css/。
如果修改首碼:
app.router.add_static('/css2017/', path='static/css', name='css')
頁面變成了:
css檔案也無法訪問了:
修改index.html中的css的引用路徑:
<!-- Bootstrap CSS --><link href="css2017/bootstrap.min.css" rel="stylesheet"><!-- Base CSS --><link href="css2017/base.css" rel="stylesheet"><!-- FA CSS --><link href="css2017/font-awesome.min.css" rel="stylesheet">
雖然目錄本身還是css,但通過add_static已經將它視為了css2017,頁面回複正常了:
css檔案也可以開啟了:
url首碼變成了/css2017/了。
此時直接開啟index.html檔案就會顯示為
因為static目錄下並沒有css2017這個檔案夾。
至此就瞭解了add_static的基本使用方法了,可以通過重新定義prefix參數還可以隱藏伺服器上真實的存放靜態資源的目錄,也可以將分散在各處的資源檔統一到同一個路徑首碼下。
此外,如果加上show_index=True,就可以顯示靜態資源的目錄索引了——預設是禁止訪問的:
app.router.add_static('/css2017/', path='static/css', name='css', show_index=True)