在Flask的特定路线上阻止查阅者 [英] Blocking referer on specific routes in Flask

查看:167
本文介绍了在Flask的特定路线上阻止查阅者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Flask中从站点外部的引用者阻止特定的路由(例如 / data )? =h2_lin>解决方案 request.referrer 包含请求的引用,所以你可以应用一些基于这个的逻辑。 p>

  from flask import Flask,request,redirect,url_for,render_template_string 
$ b app = Flask(__ name__)

@ app.route('/')
def home():
return render_template_string('''
< a href ={{url_for('data ')}}>正确引用< / a>
''')

@ app.route('/ data')
def data():
打印request.referrer $ b $如果request.referrer!='http://127.0.0.1:5000/':
return abort(403)#Forbidden
#或者也许:return redirect (url_for('home'))
return'Woo!'


if __name__ =='__main__':
app.run(debug = True)

我确定操作系统和设备中的不同浏览器有助于对引荐者做些微奇怪的事情,所以值得关注他们的特质。在访问主页/入口路由时设置会话值也许会更好,然后使用 before_request 检查会话值,就像自动登录。



所以如果你想保护你的所有页面,除了你的 home route - 如:

  @ app.before_request 
def check_session():
打印request.endpoint
如果不是session.get(合法)和request.endpoint不是'home':
返回重定向(url_for('home'))

然后在您的主线路上,只需添加 session [legit] = True 。现在,无论用户何时访问该网站,如果他们是新的,他们将被重定向回家,或者如果该会话仍处于活动状态,他们将能够看到所有内容。有点像酒店/咖啡厅的无线热点。

Is it possible to block a specific route (say /data) from referers external to the site itself in Flask ?

解决方案

request.referrer contains the referrer of the request, so you can just apply some logic based on that.

from flask import Flask, request, redirect, url_for, render_template_string

app = Flask(__name__)

@app.route('/')
def home():
    return render_template_string('''
        <a href="{{ url_for('data') }}">Correctly Referred</a>
    ''')

@app.route('/data')
def data():
    print request.referrer
    if request.referrer != 'http://127.0.0.1:5000/':
        return abort(403) # Forbidden
        # or maybe: return redirect(url_for('home'))
    return 'Woo!'


if __name__ == '__main__':
    app.run(debug=True)

I'm sure different browsers within OS's and devices helpfully do slightly odd things with the referrer, so it'd be worth having an look about for their idiosyncrasies. Perhaps it would be nicer just to set a session value on their visit to your homepage/entry-route, then check that session value is set using a before_request, almost like an automatic login.

So if you wanted to protect all your pages, except your home route-- you could so something like:

@app.before_request
def check_session():
    print request.endpoint
    if not session.get("legit") and request.endpoint is not 'home':
        return redirect(url_for('home'))

Then on your home route, just add a session["legit"] = True. Now whenever a user visits the site, they'll either get redirected right back to home if they're new, or if the session is still active, they'll be able to see everything. Kind of like a wireless hotspot in a hotel/cafe.

这篇关于在Flask的特定路线上阻止查阅者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆