我怎样才能限制在Flask的访问 [英] how can I limit the access in Flask

查看:2045
本文介绍了我怎样才能限制在Flask的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个项目来模拟登录我公司的网站,并把它放在我的服务器上让别人来使用。

但是公司网站有单ip只能打开2个会话。

因此当2个以上的同事登录我的项目时,第三个不能登录。

是否有限制访问的方法,所以当有2个用户正在使用时,第三个用户无法登录。



我应该使用全局变量来存储一些当前用户吗?

解决方案

您可以保存ip地址,用户id或者登录和上次登录到您的应用程序到数据库中,并检查它在一些用户登录时。



如果用户登录,您存储他/她的IP地址,id /登录到应用程序的时间表。如果尝试从同一个IP地址第三次登录,则拒绝登录。

当用户注销时,您从数据库中删除记录。

当用户会话自动到期但记录在数据库中时,您需要小心。为了避免您可以将永久会话设置为真(即使浏览器关闭,会话也不会被销毁),并将其持续时间设置为固定的时间 - 比方说48小时。然后,您可以创建一个程序,它将在您的数据库中定期运行,并检查上次登录时间和会话持续时间。如果差异超过48小时,则从数据库中删除记录。

您还应该考虑您的IP地址是静态的还是动态的。使用静态IP地址,应该更容易。动态的 - 这取决于他们改变的频率,但肯定会变得更加复杂。



在用户登录之前,您可以通过以下方式获取他/她的IP地址:

  from flask import request 

@ app.route('/ login',methods = [' GET','POST']):
def login():
ip_address = request.remote_addr
#检查ip_address以及绑定的会话数量


I create a project to simulate login my company's website.And put it in my server to let others to use.

But the company website has a limit with single ip can only open 2 sessions.

So when more than 2 my colleagues login my project ,the third one can't login.

Is there a way to limit the access , So when there's 2 users are using ,the third one can't login.

Should I use a global variable to store a number of current users?

解决方案

You can save the ip address, user id or login and last time of logging in to your app into database and check against it when some user logs in.

If user logs in, you store his/her ip address, id/login and last time of logging in to the app into table. If an attempt is made to login third time from the same ip address you reject it.

When user logs out you remove the record from the database.

You need to be careful with situations when user session expires automatically but the record is in the database.

In order to avoid that you can set permanent session to True (session will not be destroyed even if the browser gets closed) and set its duration to a fixed amount of time - let's say 48 hours. Then you can create a procedure which will run periodically in your db and check the last time of logging in and the duration of the session. If the difference is more than 48 hours, it deletes the record from the database.

You should also take into account whether your ip addresses are static or dynamic. With static ip addresses it should be much easier. With dynamic - it depends on how often they change, but definitely it will be more complicated.

Before a user logs in you can get his/her ip address this way:

from flask import request

@app.route('/login', methods=['GET', 'POST']):
def login():
    ip_address = request.remote_addr
    # Check the ip_address and how many sessions are bound to it

这篇关于我怎样才能限制在Flask的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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