[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"article-2":3},{"id":4,"title":5,"title_en":6,"abstract":7,"abstract_en":8,"content":9,"content_en":10,"category":11,"banner_id":12,"banner_path":13,"tags":14,"is_recommend":17,"prev_article":18,"next_article":22,"created_at":26},2,"Django指定IP访问（限制IP访问）","Django specifies IP access (restricts IP access)","# Django指定IP访问（限制IP访问）\n###### 最近服务器总能被国外ip的恶意扫描和尝试性的攻击，我就把国外IP地址给屏蔽了\n###### 我这边是通过中间件来实现的\n\n[geoip数据库","# Django specifies IP access (restrict IP access)\n###### Recently, the server can always be maliciously scanned and attempted attacked by foreign IPs, so I blocked the foreign IP address\n###### I do it with middleware\n","# Django指定IP访问（限制IP访问）\n###### 最近服务器总能被国外ip的恶意扫描和尝试性的攻击，我就把国外IP地址给屏蔽了\n###### 我这边是通过中间件来实现的\n\n[geoip数据库下载](https:\u002F\u002Fgithub.com\u002Fmangoclover\u002FGeoIP2-CN \"geoip数据库\")\n\n下载好之后，放在你项目的根目录\n\n### settings.py 配置\n```python\n# settings.py\n# GeoLite路径 \nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nGEOIP_PATH = os.path.join(BASE_DIR, 'geoip')\n```\n```python\n# settings.py配置\nOPEN_FORBIDDEN = True  # 是否启用屏蔽功能\nMIN_FORBIDDEN_TIME = 60  # 最小屏蔽时长\nMAX_FORBIDDEN_TIME = 600  # 最大屏蔽时长\nFORBIDDEN_IP_SECONDS = 60  # 记录同一IP下用户被屏蔽次数的KEY的过期时间\nFORBIDDEN_USER_SECONDS = 1  # 记录同一用户指定时间步长内访问次数的KEY的过期时间\nFORBIDDEN_IP_COUNT = 3  # 同一IP的用户被屏蔽次数超过该值将屏蔽该IP\nFORBIDDEN_USER_COUNT = 8  # 同一用户指定时间步长内访问次数超过该值将屏蔽该用户\n```\n\n```python\n# settings.py 中间件 放在第一个\nMIDDLEWARE = [\n    'page.CountryMiddleware.ForbiddenMiddleware',  # 反爬虫\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n\t..........\n]\n```\n\n#### 在你的项目中创建一个CountryMiddleware.py的文件，名字你们自己起\n```python\nfrom random import choice\nfrom django.conf import settings\nfrom django.core.cache import caches\nfrom django.contrib.gis.geoip2 import GeoIP2\nfrom django.http import HttpResponseForbidden\nfrom django.utils.deprecation import MiddlewareMixin\n\ncache = caches['default']  # from django.core.cache import cache没有incr功能\ngeoip = GeoIP2(settings.GEOIP_PATH)  # 加载IP地理位置数据库\nforbidden = '\u003Cdiv style=\"font-size:30px;\">403 forbidden\u003C\u002Fdiv>\u003Cdiv>%s\u003C\u002Fdiv>'\n\n\nclass ForbiddenMiddleware(MiddlewareMixin):\n    def process_request(self, request):\n        if not settings.OPEN_FORBIDDEN:  # 配置文件里的功能开关\n            return\n        ip = request.META.get('HTTP_REMOTE_ADDR', request.META['REMOTE_ADDR'])  # 获取访问者IP地址\n        try:\n            country = geoip.country(ip)['country_code']  # 解析访问者国别编码\n            if country != 'CN':  # 屏蔽国外IP的访问\n                return HttpResponseForbidden(forbidden % 'Temporarily')\n        except:\n            pass\n\n    def process_response(self, request, response):\n        if request.user.is_authenticated and request.user.is_superuser:\n            return response  # 如果是超级管理员，则直接返回响应\n        if not settings.OPEN_FORBIDDEN:  # 配置文件里的功能开关\n            return response\n        ip_address = request.META.get('HTTP_REMOTE_ADDR', request.META['REMOTE_ADDR'])  # 获取访问者IP地址\n        try:\n            user_tag = request.COOKIES.get(settings.CSRF_COOKIE_NAME)  # 从请求中获取cookie\n            if not user_tag:\n                user_tag = response.cookies[settings.CSRF_COOKIE_NAME].value  # 登陆时从响应中获取cookie\n        except KeyError:\n            user_tag = ip_address  # 没有cookie，即用户没有登陆，使用IP地址作为用户标记\n\n        forbidden_ip_key = 'forbidden:ip:%s' % ip_address\n        forbidden_user_key = 'forbidden:user:%s' % user_tag\n        for cache_key in [forbidden_ip_key, forbidden_user_key]:  # 同时检查IP地址屏蔽和用户标记屏蔽\n            forbidden_time = cache.get(cache_key)\n            if forbidden_time:  # 如果被屏蔽了还继续请求\n                cache.set(cache_key, forbidden_time, forbidden_time)  # 重置过期时间为初始值，延长屏蔽时间\n                return HttpResponseForbidden(forbidden % '访问过于频繁，请稍候再试！')\n\n        ip_count_key = 'count:ip:%s' % ip_address  # 同一IP地址的用户被屏蔽的次数\n        user_count_key = 'count:user:%s:%s' % (user_tag, request.path)  # 同一用户在指定时间步长内的访问次数\n        forbidden_user_count = settings.FORBIDDEN_USER_COUNT\n        if 'HTTP_FILE_UPLOAD_NAME' in request.META:  # 文件传输的交互频率较高，频率限制调高5倍\n            forbidden_user_count *= 5\n\n        if cache.get(user_count_key, 0) &gt; forbidden_user_count:  # 同一用户在指定时间步长内访问太多次\n            forbidden_time = choice(range(settings.MIN_FORBIDDEN_TIME, settings.MAX_FORBIDDEN_TIME))  # 生成随机的屏蔽时间长度\n            cache.set(forbidden_user_key, forbidden_time, forbidden_time)  # 设置屏蔽该用户\n            try:\n                cache.incr(ip_count_key)  # 该用户使用的IP被屏蔽的次数增加一次\n            except ValueError:\n                cache.set(ip_count_key, 1, settings.FORBIDDEN_IP_SECONDS)  # 还没有这个key的话设置为1\n            return HttpResponseForbidden(forbidden % '访问过于频繁，请稍候再试！')\n        elif cache.get(ip_count_key, 0) &gt; settings.FORBIDDEN_IP_COUNT:  # 同一IP地址的用户被屏蔽三次后屏蔽该IP地址的访问\n            forbidden_time = choice(range(settings.MIN_FORBIDDEN_TIME, settings.MAX_FORBIDDEN_TIME))  # 生成随机的屏蔽时间长度\n            cache.set(forbidden_ip_key, forbidden_time, forbidden_time)  # 设置屏蔽该IP地址\n            return HttpResponseForbidden(forbidden % '访问过于频繁，请稍候再试！')\n        else:\n            try:\n                cache.incr(user_count_key)  # 该用户的访问次数增加一次\n            except ValueError:\n                cache.set(user_count_key, 1, settings.FORBIDDEN_USER_SECONDS)  # 还没有这个key的话设置为1\n            return response\n```\n#### 这样就好了","# Django Specify IP access (restrict IP access)\n######Recently, the server has always been maliciously scanned and attempted attacks by foreign IPs, so I blocked the foreign IP address\n#######I do it through middleware\n\n[Geoip Database Download](github.com\u002Fmangoclover\u002FGeoIP2-CN \"Geoip Database\")\n\nAfter downloading, place it in the root directory of your project\n\n###settings.py Configuration\n```python\n# settings.py\n# GeoLite Path \nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nGEOIP_PATH = os.path.join(BASE_DIR, 'geoip')\n```\n```python\n# settings.py Configuration\nOPEN_FORBIDDEN = True #Whether to enable blocking\nMIN_FORBIDDEN_TIME = 60 #Minimum masking duration\nMAX_FORBIDDEN_TIME = 600 #maximum masking duration\nFORBIDDEN_IP_SECONDS = 60 #Expiration time of a KEY that records the number of times a user is blocked under the same IP\nFORBIDDEN_USER_SECONDS = 1 #The expiration time of a KEY that records the number of accesses within the time step specified by the same user\nFORBIDDEN_IP_COUNT = 3 #Users with the same IP will be blocked more than this value will block the IP\nFORBIDDEN_USER_COUNT = 8 #If the number of accesses within the specified time step of the same user exceeds this value, the user will be blocked\n```\n\n```python\n#settings.py Middleware put first\nMIDDLEWARE = [\n    'page.CountryMiddleware.ForbiddenMiddleware', #Anticrawler\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n\t..........\n]\n```\n\n####Create a CountryMiddleware.py file in your project, name it yourself\n```python\nfrom random import choice\nfrom django.conf import settings\nfrom django.core.cache import caches\nfrom django.contrib.gis.geoip2 import GeoIP2\nfrom django.http import HttpResponseForbidden\nfrom django.utils.deprecation import MiddlewareMixin\n\ncache = caches['default']# from django.core.cache import cache has no incr feature\ngeoip = GeoIP2(settings.GEOIP_PATH) #Load IP geo-location database\nforbidden = '\u003Cdiv style=\"font-size:30px;\">403 forbidden\u003C\u002Fdiv>\u003Cdiv>%s\u003C\u002Fdiv>'\n\n\nclass ForbiddenMiddleware(MiddlewareMixin):\n    def process_request(self, request):\n        if not settings.OPEN_FORBIDDEN: #Function switches in configuration file\n            return\n        ip = request.META.get ('HTTP_REMOTE_ADDR', request.META['REMOTE_ADDR']) #Get the visitor IP address\n        try:\n            country = geoip.country (ip)['country_code']#parse visitor country code\n            if country != 'CN':#Block access to foreign IP\n                return HttpResponseForbidden(forbidden % 'Temporarily')\n        except:\n            pass\n\n    def process_response(self, request, response):\n        if request.user.is_authenticated and request.user.is_superuser:\n            return response #If you are a super administrator, return the response directly\n        if not settings.OPEN_FORBIDDEN: #Function switches in configuration file\n            return response\n        ip_address = request.META.get ('HTTP_REMOTE_ADDR', request.META['REMOTE_ADDR']) #Get the visitor IP address\n        try:\n            user_tag = request.COOKIES.get(settings.CSRF_COOKIE_NAME) #Get cookies from the request\n            if not user_tag:\n                user_tag = response.cookies[settings.CSRF_COOKIE_NAME].value #Get cookies from the response when logging in\n        except KeyError:\n            user_tag = ip_address #There is no cookie, that is, the user has not logged in, and the IP address is used as the user token\n\n        forbidden_ip_key = 'forbidden:ip:%s' % ip_address\n        forbidden_user_key = 'forbidden:user:%s' % user_tag\n        for cache_key in [forbidden_ip_key, forbidden_user_key]: #Check IP address masking and user token masking at the same time\n            forbidden_time = cache.get(cache_key)\n            if forbidden_time: #Continue requesting if blocked\n                cache.set(cache_key, forbidden_time, forbidden_time) #Resets the expiration time to the initial value and extends the masking time\n                return HttpResponseForbidden(Forbidden % 'is visited too frequently. Please try again later! ')\n\n        ip_count_key = 'count:ip:% s'% ip_address #The number of times users with the same IP address have been blocked\n        user_count_key = 'count:user:%s:% s'%(user_tag, request.path) #The number of visits by the same user in the specified time step\n        forbidden_user_count = settings.FORBIDDEN_USER_COUNT\n        if 'HTTP_FILE_UPLOAD_NAME' in request.META: #File transfers have a higher interactive frequency, and the frequency limit is increased by 5 times\n            forbidden_user_count *= 5\n\n        if cache.get(user_count_key, 0) Forbidden_user_count: #The same user accesses too many times in a specified time step\n            forbidden_time = choice(range(settings.MIN_FORBIDDEN_TIME, settings.MAX_FORBIDDEN_TIME)) #Generate a random mask length\n            cache.set(forbidden_user_key, forbidden_time, forbidden_time) #Set to block this user\n            try:\n                cache.incr(ip_count_key) #The number of times the IP used by this user is blocked is increased once\n            except ValueError:\n                cache.set(ip_count_key, 1, settings.FORBIDDEN_IP_SECONDS) #Set to 1 if you don't have this key yet\n            return HttpResponseForbidden(Forbidden % 'is visited too frequently. Please try again later! ')\n        elif cache.get(ip_count_key, 0) settings.FORBIDDEN_IP_COUNT: #Users with the same IP address are blocked three times and then access to that IP address is blocked\n            forbidden_time = choice(range(settings.MIN_FORBIDDEN_TIME, settings.MAX_FORBIDDEN_TIME)) #Generate a random mask length\n            cache.set(forbidden_ip_key, forbidden_time, forbidden_time) #Set to block this IP address\n            return HttpResponseForbidden(Forbidden % 'is visited too frequently. Please try again later! ')\n        else:\n            try:\n                cache.incr(user_count_key) #The number of visits this user has increased once\n            except ValueError:\n                cache.set(user_count_key, 1, settings.FORBIDDEN_USER_SECONDS) #Set to 1 if you don't have this key yet\n            return response\n```\n####That's fine","python",0,"https:\u002F\u002Fblog4-1316398321.cos.ap-nanjing.myqcloud.com\u002Fblog5\u002F20250712002259__freecompress-【哲风壁纸】傍晚风光-富士山.png",[15,16],"Python","Django",false,{"id":19,"title":20,"title_en":21},1,"uwsgi.ini 常用配置参数详解","uwsgi.ini Detailed explanation of common configuration parameters",{"id":23,"title":24,"title_en":25},3,"根据ip获取城市","Get the city according to IP","2025-07-21T05:00:48+08:00"]