本文介绍了使用Flask,如何将robots.txt和sitemap.xml作为静态文件提供?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在安静的地方读了一些提供静态文件的地方应该放在服务器上,例如在。但我使用OpenShift PaaS,并不知道如何修改.htaccess文件。



我遇到了这个,用于从一个网站模板。我在应用程序中为sitemap和robots.txt这样做了 - $ / $>

  

放置 robots.txt 和 sitemap.xml 到你的应用程序的 static 目录并定义这个视图:

  from flask import Flask,request,send_from_directory 

@ app.route('/ robots.txt')
@ app.route('/ sitemap.xml')
def static_from_root()
return send_from_directory(app.static_folder,request.path [1:])


I've read on quiet a few places that serving static files should be left to the server, for example in a couple of the answers on this SO question. But I use the OpenShift PaaS, and can't figure out how to modify the .htaccess file there.

I came across this piece of code that serves the sitemap from a template. I did that on my app for both the sitemap, and robots.txt, like so -

@app.route("/sitemap.xml")
def sitemap_xml():
    response= make_response(render_template("sitemap.xml"))
    response.headers['Content-Type'] = 'application/xml'
    return response

@app.route("/robots.txt")
def robots_txt():
    return render_template("robots.txt")

Is there any harm in this, or is my approach okay?

解决方案

Put robots.txt and sitemap.xml into your app's static directory and define this view:

from flask import Flask, request, send_from_directory

@app.route('/robots.txt')
@app.route('/sitemap.xml')
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])

这篇关于使用Flask,如何将robots.txt和sitemap.xml作为静态文件提供?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:35