我想定位到静态文件,因为html中有许多相对路径,例如:
<a href="1.html"> page1 </a>
<a href="2.html"> page2 </a>
....我可以用app.send_static_file()在烧瓶做它。
from flask import Flask
app = Flask(__name__, static_url_path='')
@app.route('/')
def index():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run(host="0.0.0.0",debug=True,port=8888)但是对于Sanic,我没有找到相关的方法。
from sanic import Sanic
app = Sanic(__name__)
app.static('/static', './static')
@app.route('/')
async def index(request):
#return "static/index.html" file with static state.
if __name__=='__main__':
app.run(host='0.0.0.0',port=8888,debug=True, auto_reload=True)有办法做到这一点吗?或者sanic-jinja2 2,sanic-mako等方法也不错。
发布于 2022-05-12 06:10:48
我有点不清楚你到底想做什么,所以我会提供几个例子,这可能是你想要的。请让我知道这样做是否解决了问题,我可以修改答案。
静态文件
如果您有一个要服务的静态文件(这也适用于一个静态文件目录),则使用app.static。
app.static("/static", "/path/to/directory")
# So, now a file like `/path/to/directory/foo.jpg`
# is available at http://example.com/static/foo.jpg这也适用于/path/to/directory中的深度嵌套文件。
您还可以选择在单个文件上使用此模式,这通常有助于index.html (例如:
app.static("/", "/path/to/index.html")检索(或查找)静态文件的URL
如果你所说的“定位”文件是你想要访问它的网址,那么你可以使用app.url_for
app.static(
"/user/uploads",
"/path/to/uploads",
name="uploads",
)
app.url_for(
"static", # Note, for any file registered with app.static, this value is "static"
name="uploads",
filename="image.png",
)从路由处理程序中提供文件
另一方面,如果您有一个常规的路由处理程序,并且希望使用一个文件进行响应(这意味着您所做的不仅仅是为一个静态文件服务),那么您可以使用sanic.response.file。
让我们设想一个场景,您需要查找用户并获取他们的概要文件映像:
@app.get("/current-user/avatar")
async def serve_user_avatar(request: Request):
user = await fetch_user_from_request(request)
return await file(user.avatar)模板
由于您提到了jinja和mako,所以Sanic扩展是一个官方支持的插件,它添加了模板:
pip install "sanic[ext]"@app.get("/")
@app.ext.template("foo.html")
async def handler(request: Request):
return {"seq": ["one", "two"]}回顾你的例子..。
您的示例显示如下:
app.static('/static', './static')
@app.route('/')
async def index(request):
#return "static/index.html" file with static state.在我看来,您似乎在./static/index.html中有一个文件,您希望只提供该文件。在这种情况下,@app.route定义是不必要的,因为它将是服务器,因为有了app.static定义。如果您有这样的文件夹结构:
./root
├── static
│ └── index.html
└── server.py那么你所需要的就是:
app.static("/static", "./static")现在,您将得到:http://example.com/static/index.html
https://stackoverflow.com/questions/72197393
复制相似问题