簡體   English   中英

用django提供沒有模板渲染的html文件?

[英]Serving an html file with django without template rendering?

我有一個html文件,我通過使用Bokeh庫創建可視化來生成。 我想將它包含在我的django站點中,但是,當我嘗試將其添加為視圖時,我得到了TemplateSyntaxError。 似乎頁面中的某些語法與Django的模板系統相沖突。

如何讓Django服務於頁面而不試圖將其解析為模板?

您可以在模板中使用verbatim標記 ,以便django的渲染系統不會解析頁面的該部分:

{% verbatim %}

<!--  Template tags ignored in here  -->

{% endverbatim %}

這樣,如果您將來想在該頁面上使用Django的模板標簽,則無需返回並更改視圖,然后再實施此解決方案。

基於基本模板文檔,您可以直接返回HttpResponse,而無需使用任何渲染函數:

https://docs.djangoproject.com/en/1.8/topics/http/views/

由於HttpResponse只為響應內容提取了一個字符串,因此您可以從存儲的任何位置讀取原始文件,並以這種方式返回。

當你使用render_to_responserender ,這只是加載模板,解析它,構造結果字符串,並返回它包裝在HttpResponse中,所以如果你不想做任何渲染,你可以完全跳過模板系統。

您可以使用Web服務器提供靜態html文件:

我個人使用(特殊情況下)這個使用nginx或cherokee來提供受保護的文件或圖片,這里有一個例子:

 @login_required(redirect_field_name=None)
     def serve_file(request,id):
     '''
     Where "id" is the argument that identifies
     the ressource to be protected
     '''
     #allowed = True
     # You can do your permission things here, and set allowed to True if applicable
     ##if allowed:
     response = HttpResponse()
     # construct the file's path
     url=os.path.join (settings.MEDIA_ROOT,'files','page_'+id+'.html')
     # test if path is ok and file exists
     if os.path.isfile(url):
       # let nginx determine the correct content type in this case
       response['Content-Type']=""
       response['X-Accel-Redirect'] = url
       #response['X-Sendfile'] = url
       # other webservers may accept X-Sendfile and not X-Accel-Redirect
       return response
return HttpResponseForbidden()

此解決方案可以使用任何文件類型,刪除@login_required刪除保護;)

在carlsl中確保通過urls.py中的regex對'id'變量進行類型檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM