简体   繁体   English

aiohttp:提供单个静态文件

[英]aiohttp: Serve single static file

How to serve a single static file (instead of an entire directory) using aiohttp?如何使用 aiohttp 提供单个静态文件(而不是整个目录)?

Static file serving seems to be baked into the routing system with UrlDispatcher.add_static() , but this only serves entire directories.静态文件服务似乎通过UrlDispatcher.add_static()融入到路由系统中,但这仅服务于整个目录。

(I know that I eventually should use something like nginx to serve static files in a production environment.) (我知道我最终应该使用像 nginx 这样的东西在生产环境中提供静态文件。)

Currently, as of aiohttp version 2.0, the easiest way to return a single file as a response is to use the undocumented (?) FileResponse object, initialised with the path to the file, eg目前,从 aiohttp 2.0 版开始,返回单个文件作为响应的最简单方法是使用未记录的 (?) FileResponse对象,用文件的路径初始化,例如

from aiohttp import web

async def index(request):
    return web.FileResponse('./index.html')

Currently there is no built-in way of doing this;目前没有内置的方法来做到这一点; however, there are plans in motion to add this feature .但是,正在计划添加此功能

I wrote App, that handles uri on client (angular router).我写了应用程序,它在客户端(角度路由器)上处理 uri。

To serve webapp i used slightly different factory:为了服务 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM