[英]aiohttp: Serve single static file
如何使用 aiohttp 提供單個靜態文件(而不是整個目錄)?
靜態文件服務似乎通過UrlDispatcher.add_static()融入到路由系統中,但這僅服務於整個目錄。
(我知道我最終應該使用像 nginx 這樣的東西在生產環境中提供靜態文件。)
目前,從 aiohttp 2.0 版開始,返回單個文件作為響應的最簡單方法是使用未記錄的 (?) FileResponse
對象,用文件的路徑初始化,例如
from aiohttp import web
async def index(request):
return web.FileResponse('./index.html')
目前沒有內置的方法來做到這一點; 但是,正在計划添加此功能。
我寫了應用程序,它在客戶端(角度路由器)上處理 uri。
為了服務 webapp,我使用了稍微不同的工廠:
def index_factory(path,filename):
async def static_view(request):
# prefix not needed
route = web.StaticRoute(None, '/', path)
request.match_info['filename'] = filename
return await route.handle(request)
return static_view
# json-api
app.router.add_route({'POST','GET'}, '/api/{collection}', api_handler)
# other static
app.router.add_static('/static/', path='../static/', name='static')
# index, loaded for all application uls.
app.router.add_get('/{path:.*}', index_factory("../static/ht_docs/","index.html"))
# include handler path
app['static_root_url'] = '/static'
# path dir of static file
STATIC_PATH = os.path.join(os.path.dirname(__file__), "static")
app.router.add_static('/static/', STATIC_PATH, name='static')
# include in template
<link href="{{static('/main.css')}}" rel="stylesheet">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.