[英]Sanic how to locate to static file
我想定位到靜態文件,因為 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、sanic-mako等方法也可以。
我不太清楚你到底想要做什么,所以我將提供幾個可能是你正在尋找的例子。 請讓我知道這是否解決了問題,我可以修改答案。
如果您有一個想要提供的靜態文件(這也適用於靜態文件目錄),那么您可以使用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 Extensions是一個官方支持的插件,它添加了模板:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.