当前位置:首页 > 行业动态 > 正文

Flask 限制IP

在Flask中,你可以通过多种方式限制IP地址的访问,以下是一些常见的方法:

Flask 限制IP  第1张

1、使用FlaskLimiter扩展

2、使用FlaskLogin和session限制

3、使用自定义装饰器

4、使用nginx反向代理

1. 使用FlaskLimiter扩展

FlaskLimiter是一个用于限制请求速率的扩展,你可以设置每个IP地址的最大请求数,超过这个数量的请求将被拒绝。

安装FlaskLimiter:

pip install FlaskLimiter

示例代码:

from flask import Flask, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
app = Flask(__name__)
limiter = Limiter(app, key_func=get_remote_address)
@app.route("/")
@limiter.limit("10/minute")  # 每分钟最多10个请求
def index():
    return "Hello, World!"

2. 使用FlaskLogin和session限制

FlaskLogin可以帮助你管理用户会话,你可以设置每个IP地址的最大会话数,超过这个数量的会话将被删除。

安装FlaskLogin:

pip install FlaskLogin

示例代码:

from flask import Flask, session, request, redirect, url_for, render_template, flash, login_user, logout_user, current_user
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user, login_required, logout_required, user_loader
from werkzeug.security import generate_password_hash, check_password_hash
import os
from datetime import timedelta
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from models import db, User, Role, Followers, Likes, Posts, Comments, Visits
from forms import RegistrationForm, LoginForm, UpdateAccountForm, RequestResetForm, ResetPasswordForm, ChangePasswordForm, SearchForm, PostForm, CommentForm, LikeForm, FollowForm, UnfollowForm
from functools import wraps
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer as Serializer
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
from flask
0