珠海网站制作哪家便宜久久建筑网 百度网盘

news/2025/10/6 1:03:37/文章来源:
珠海网站制作哪家便宜,久久建筑网 百度网盘,怎样上传网站到空间,沙坪坝网站建设认证与权限频率组件 身份验证是将传入请求与一组标识凭据#xff08;例如请求来自的用户或其签名的令牌#xff09;相关联的机制。然后 权限 和 限制 组件决定是否拒绝这个请求。 简单来说就是#xff1a; 认证确定了你是谁权限确定你能不能访问某个接口限制确定你访问某…认证与权限频率组件 身份验证是将传入请求与一组标识凭据例如请求来自的用户或其签名的令牌相关联的机制。然后 权限 和 限制 组件决定是否拒绝这个请求。 简单来说就是 认证确定了你是谁权限确定你能不能访问某个接口限制确定你访问某个接口的频率 一、认证组件 REST framework 提供了一些开箱即用的身份验证方案并且还允许你实现自定义方案。 自定义Token认证 定义一个用户表和一个保存用户Token的表 class UserInfo(models.Model):username models.CharField(max_length16)password models.CharField(max_length32)type models.SmallIntegerField(choices((1, 普通用户), (2, VIP用户)),default1)class Token(models.Model):user models.OneToOneField(toUserInfo)token_code models.CharField(max_length128) 定义一个登录视图 def get_random_token(username):根据用户名和时间戳生成随机token:param username::return:import hashlib, timetimestamp str(time.time())m hashlib.md5(bytes(username, encodingutf8))m.update(bytes(timestamp, encodingutf8))return m.hexdigest()class LoginView(APIView):校验用户名密码是否正确从而生成token的视图def post(self, request):res {code: 0}print(request.data)username request.data.get(username)password request.data.get(password)user models.UserInfo.objects.filter(usernameusername, passwordpassword).first()if user:# 如果用户名密码正确token get_random_token(username)models.Token.objects.update_or_create(defaults{token_code: token}, useruser)res[token] tokenelse:res[code] 1res[error] 用户名或密码错误return Response(res) 定义一个认证类 from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailedclass MyAuth(BaseAuthentication):def authenticate(self, request): # 必须实现authenticate方法返回认证之后的用户认证的objif request.method in [POST, PUT, DELETE]:request_token request.data.get(token, None)if not request_token:raise AuthenticationFailed(缺少token)token_obj models.Token.objects.filter(token_coderequest_token).first()if not token_obj:raise AuthenticationFailed(无效的token)return token_obj.user.username, Noneelse:return None, None 视图级别认证 class CommentViewSet(ModelViewSet):queryset models.Comment.objects.all()serializer_class app01_serializers.CommentSerializerauthentication_classes [MyAuth, ] 全局级别认证 # 在settings.py中配置 REST_FRAMEWORK {DEFAULT_AUTHENTICATION_CLASSES: [app01.utils.MyAuth, ] } 二、权限组件 只有VIP用户才能看的内容。 自定义一个权限类 # 自定义权限 class MyPermission(BasePermission):message VIP用户才能访问def has_permission(self, request, view):必须实现has_permission有权限返回True无权限返回False# 因为在进行权限判断之前已经做了认证判断所以这里可以直接拿到request.userif request.user and request.user.type 2: # 如果是VIP用户return Trueelse:return False 视图级别配置 class CommentViewSet(ModelViewSet):queryset models.Comment.objects.all()serializer_class app01_serializers.CommentSerializerauthentication_classes [MyAuth, ]permission_classes [MyPermission, ] 全局级别设置 # 在settings.py中设置rest framework相关配置项 REST_FRAMEWORK {DEFAULT_AUTHENTICATION_CLASSES: [app01.utils.MyAuth, ],DEFAULT_PERMISSION_CLASSES: [app01.utils.MyPermission, ] } 三、频率限制组件 DRF内置了基本的限制类首先我们自己动手写一个限制类熟悉下限制组件的执行过程。 自定义限制类 VISIT_RECORD {} # 自定义限制 class MyThrottle(object):def __init__(self):self.history Nonedef allow_request(self, request, view): 必须实现allow_request允许访问返回True否则返回False自定义频率限制60秒内只能访问三次# 获取用户IPip request.META.get(REMOTE_ADDR)timestamp time.time()if ip not in VISIT_RECORD:VISIT_RECORD[ip] [timestamp, ]return Truehistory VISIT_RECORD[ip]self.history historyhistory.insert(0, timestamp)while history and history[-1] timestamp - 60:history.pop()if len(history) 3:return Falseelse:return Truedef wait(self):限制时间还剩多少timestamp time.time()return 60 - (timestamp - self.history[-1]) 视图使用 class CommentViewSet(ModelViewSet):queryset models.Comment.objects.all()serializer_class app01_serializers.CommentSerializerthrottle_classes [MyThrottle, ] 全局使用 # 在settings.py中设置rest framework相关配置项 REST_FRAMEWORK {DEFAULT_AUTHENTICATION_CLASSES: [app01.utils.MyAuth, ],DEFAULT_PERMISSION_CLASSES: [app01.utils.MyPermission, ],DEFAULT_THROTTLE_CLASSES: [app01.utils.MyThrottle, ] } 使用内置限制类 from rest_framework.throttling import SimpleRateThrottleclass VisitThrottle(SimpleRateThrottle):scope xxxdef get_cache_key(self, request, view):return self.get_ident(request) 全局配置 # 在settings.py中设置rest framework相关配置项 REST_FRAMEWORK {DEFAULT_AUTHENTICATION_CLASSES: [app01.utils.MyAuth, ],# DEFAULT_PERMISSION_CLASSES: [app01.utils.MyPermission, ]DEFAULT_THROTTLE_CLASSES: [app01.utils.VisitThrottle, ],DEFAULT_THROTTLE_RATES: {xxx: 5/m,} } 认证类源码 ############################ authentication.py #################################### from __future__ import unicode_literalsimport base64 import binasciifrom django.contrib.auth import authenticate, get_user_model from django.middleware.csrf import CsrfViewMiddleware from django.utils.six import text_type from django.utils.translation import ugettext_lazy as _from rest_framework import HTTP_HEADER_ENCODING, exceptionsdef get_authorization_header(request):Return requests Authorization: header, as a bytestring.Hide some test client ickyness where the header can be unicode.auth request.META.get(HTTP_AUTHORIZATION, b)if isinstance(auth, text_type):# Work around django test client oddnessauth auth.encode(HTTP_HEADER_ENCODING)return authclass CSRFCheck(CsrfViewMiddleware):def _reject(self, request, reason):# Return the failure reason instead of an HttpResponsereturn reasonclass BaseAuthentication(object):All authentication classes should extend BaseAuthentication.def authenticate(self, request):Authenticate the request and return a two-tuple of (user, token).raise NotImplementedError(.authenticate() must be overridden.)def authenticate_header(self, request):Return a string to be used as the value of the WWW-Authenticateheader in a 401 Unauthenticated response, or None if theauthentication scheme should return 403 Permission Denied responses.passclass BasicAuthentication(BaseAuthentication):HTTP Basic authentication against username/password.www_authenticate_realm apidef authenticate(self, request):Returns a User if a correct username and password have been suppliedusing HTTP Basic authentication. Otherwise returns None.auth get_authorization_header(request).split()if not auth or auth[0].lower() ! bbasic:return Noneif len(auth) 1:msg _(Invalid basic header. No credentials provided.)raise exceptions.AuthenticationFailed(msg)elif len(auth) 2:msg _(Invalid basic header. Credentials string should not contain spaces.)raise exceptions.AuthenticationFailed(msg)try:auth_parts base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(:)except (TypeError, UnicodeDecodeError, binascii.Error):msg _(Invalid basic header. Credentials not correctly base64 encoded.)raise exceptions.AuthenticationFailed(msg)userid, password auth_parts[0], auth_parts[2]return self.authenticate_credentials(userid, password, request)def authenticate_credentials(self, userid, password, requestNone):Authenticate the userid and password against username and passwordwith optional request for context.credentials {get_user_model().USERNAME_FIELD: userid,password: password}user authenticate(requestrequest, **credentials)if user is None:raise exceptions.AuthenticationFailed(_(Invalid username/password.))if not user.is_active:raise exceptions.AuthenticationFailed(_(User inactive or deleted.))return (user, None)def authenticate_header(self, request):return Basic realm%s % self.www_authenticate_realmclass SessionAuthentication(BaseAuthentication):Use Djangos session framework for authentication.def authenticate(self, request):Returns a User if the request session currently has a logged in user.Otherwise returns None.# Get the session-based user from the underlying HttpRequest objectuser getattr(request._request, user, None)# Unauthenticated, CSRF validation not requiredif not user or not user.is_active:return Noneself.enforce_csrf(request)# CSRF passed with authenticated userreturn (user, None)def enforce_csrf(self, request):Enforce CSRF validation for session based authentication.check CSRFCheck()# populates request.META[CSRF_COOKIE], which is used in process_view()check.process_request(request)reason check.process_view(request, None, (), {})if reason:# CSRF failed, bail with explicit error messageraise exceptions.PermissionDenied(CSRF Failed: %s % reason)class TokenAuthentication(BaseAuthentication):Simple token based authentication.Clients should authenticate by passing the token key in the AuthorizationHTTP header, prepended with the string Token . For example:Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6akeyword Tokenmodel Nonedef get_model(self):if self.model is not None:return self.modelfrom rest_framework.authtoken.models import Tokenreturn TokenA custom token model may be used, but must have the following properties.* key -- The string identifying the token* user -- The user to which the token belongsdef authenticate(self, request):auth get_authorization_header(request).split()if not auth or auth[0].lower() ! self.keyword.lower().encode():return Noneif len(auth) 1:msg _(Invalid token header. No credentials provided.)raise exceptions.AuthenticationFailed(msg)elif len(auth) 2:msg _(Invalid token header. Token string should not contain spaces.)raise exceptions.AuthenticationFailed(msg)try:token auth[1].decode()except UnicodeError:msg _(Invalid token header. Token string should not contain invalid characters.)raise exceptions.AuthenticationFailed(msg)return self.authenticate_credentials(token)def authenticate_credentials(self, key):model self.get_model()try:token model.objects.select_related(user).get(keykey)except model.DoesNotExist:raise exceptions.AuthenticationFailed(_(Invalid token.))if not token.user.is_active:raise exceptions.AuthenticationFailed(_(User inactive or deleted.))return (token.user, token)def authenticate_header(self, request):return self.keywordclass RemoteUserAuthentication(BaseAuthentication):REMOTE_USER authentication.To use this, set up your web server to perform authentication, which willset the REMOTE_USER environment variable. You will need to havedjango.contrib.auth.backends.RemoteUserBackend in yourAUTHENTICATION_BACKENDS setting# Name of request header to grab username from. This will be the key as# used in the request.META dictionary, i.e. the normalization of headers to# all uppercase and the addition of HTTP_ prefix apply.header REMOTE_USERdef authenticate(self, request):user authenticate(remote_userrequest.META.get(self.header))if user and user.is_active:return (user, None)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/928890.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

成都网站建设制作设计内蒙古最新消息今天

Python是一种高级编程语言,广泛用于数据科学、人工智能、网络编程等领域。 Python提供了许多内置函数和标准库,可以完成各种任务: 1、print()函数:将文本输出到控制台。可以将字符串、数字和变量等输出到控制台。 2、input()函…

创建自己的网站怎么弄宁乡市住房和城乡建设局网站

原理概述 当一台BGP路由器中存在多条去往同一目标网络的BGP路由时,BGP协议会对这些BGP路由的属性进行比较,以确定去往该目标网络的最优BGP路由,然后将该最优BGP路由与去往同一目标网络的其他协议路由进行比较,从而决定是否将该最优…

重庆商家网站农村自建房设计师哪里找

目录 Python基础(八)--迭代,生成器,装饰器与元类 1 迭代 1.1 可迭代对象与迭代器 1.2 自定义迭代类型 1.3 迭代合体 2 生成器 2.1 什么是生成器 2.2 生成器表达式 2.3 生成器函数 3 装饰器 3.1 闭包 3.2 什么是装饰器 …

如何向百度举报网站国外网站怎么上

2019独角兽企业重金招聘Python工程师标准>>> 安装。。。后查看 import django django.VERSION #输出版本号,目前自己是py2.7.9和django1.8 1,新建一个django-project django-admin.py startproject project-name 一个project一般为一个项目 …

网站制作费用申请移动互联网开发记事本项目告别

这一篇讲解消费者 文章目录一、依赖配置1. 引入依赖2. 配置文件3. 主配置二、代码Conding2.1. 消费者代码一、依赖配置 1. 引入依赖 <!--springboot整合RabbitMQ依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>sp…

济南seo外贸网站建设小型公司网站建设

AV1 屏幕内容编码 为了提高屏幕捕获内容的压缩性能&#xff0c;AV1采用了几种编码工具&#xff0c;例如用于处理屏幕画面中重复模式的内帧内块复制&#xff08;IntraBC&#xff09;&#xff0c;以及用于处理颜色数量有限的屏幕块的调色板模式。 帧内块拷贝 AV1 编码中的 Intra …

锦州做网站哪家好cloudfare wordpress

文章目录 Spring Boot 约定大于配置&#xff1a;实现自定义配置引言1. Spring Boot 的约定大于配置2. 自定义配置的需求3. 实现自定义配置的步骤4. 示例&#xff1a;自定义 Spring MVC 配置4.1 创建自定义配置类4.2 创建自定义拦截器4.3 测试自定义配置 5. 其他自定义配置场景5…

CF2152G Query Jungle(线段树,重链剖分,*)

CF2152G Query Jungle 子树翻转,求没有黑色子孙的黑色点个数。套上 mincnt 标签和双生 rev 标签即可。不明白提交记录里的人都在写什么鬼。 Code const int inf = 1 << 30;struct Node {int m1 = inf, mc1 = 0,…

代码随想录算法训练营第九天 | leetcode 151 卡特55

反转字符串中的单词 整体思路:先将整体翻转,再进行翻转其中的单词,以空格划分进行单词操作,使用快慢指针思想,快指针获取符合题目要求的字母,慢指针是获取到字母后更新到哪里 代码如下:class Solution { public…

[题解] 分竹子

传送门 题目描述 将 bamboo_len 的竹子砍为若干整数段, 求每段竹子长度的最大乘积. 2 <= bamboo_len <= 58 分析 设将长度为 \(s\) 的竹子分为 \(n\) 段, 每段分别为 \(a_1, a_2, \cdots, a_n\) , 问题转化为求 …

可画在线设计网站网站建设策划书事物选题

如果還不知道什麼是 Pagination 或者還不了解如何使用&#xff0c;請參考&#xff1a; CakePHP Pagination (分頁功能) 。通常在管理後台實作時&#xff0c;常設定許多查詢條件來查詢資料&#xff0c;比如&#xff1a;起始、結束時間。通常這些參數都是用GET的方式在傳遞。以下…

万网网站多少直播营销策划方案范文

transport传输 一、Tansport 转发到Producer二、RtpStreamRecv 处理收到的包三、数据传输到Router&#xff0c;再分发到Consumertips 一、Tansport 转发到Producer Transport收到数据packet后&#xff0c;会解析出packet中所带的ssrc字段&#xff0c;然后基于ssrc找到该数据的…

烟台房地产网站建设flash网站与html5

1 标准误 1.1 定义 标准误&#xff08;Standard Error&#xff09;是用来衡量统计样本估计量&#xff08;如均值、回归系数等&#xff09;与总体参数之间的差异的一种统计量。标准误衡量了样本估计量的变异程度&#xff0c;提供了对总体参数的估计的不确定性的度量。标准误越…

免费做网站怎么做网站3.15网站建设

文章目录1. 题目信息2. 解题2.1 递归查找2.2 改循环1. 题目信息 给定一个非空特殊的二叉树&#xff0c;每个节点都是正数&#xff0c;并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话&#xff0c;那么这个节点的值不大于它的子节点的值。 给出这样的一…

实力强劲的机器视觉公司有哪些:2025年TOP5精选榜单

实力强劲的机器视觉公司有哪些:2025年TOP5精选榜单科技的飞速迭代正重塑工业生产模式,机器视觉公司作为工业自动化的“技术引擎”,凭借图像采集、算法分析等核心能力,为3C电子、汽车制造、半导体等领域提供精准检测…

常见的电子商务网站有南宁网站推广优化

本章节的目的是 【明确目标用户群】 &#xff0c;以更好的服务现有用户。 【知识点】 1.作图 显示中文plt.rcParams[font.sans-serif] [SimHei] # 步骤一&#xff08;替换sans-serif字体&#xff09; plt.rcParams[axes.unicode_minus] False # 步骤二&#xff08;解决坐标轴…

保健品网站建设流程网站模板下载免费

文章目录 前言 1 配置 2 使用 3 MAVLink协议说明 前言 ArduPilot 和任务计划器能够通过使用加密密钥添加数据包签名&#xff0c;为空中 MAVLink 传输增加安全性。这并不加密数据&#xff0c;只是控制自动驾驶仪是否响应 MAVLink 命令。 当自动驾驶仪处于激活状态时&#x…

优质机器视觉教育装备有哪些:2025年TOP5推荐清单

优质机器视觉教育装备有哪些:2025年TOP5推荐清单科技浪潮推动教育领域向智能化转型,机器视觉教育装备作为培养工业自动化、人工智能领域专业人才的核心工具,已广泛应用于高校智能制造专业、职业院校工业机器人课程及…

2025年机器视觉软件平台哪个好:全行业品牌TOP5推荐榜单

2025年机器视觉软件平台哪个好:全行业品牌TOP5推荐榜单科技的飞速发展正深刻改变生产生活方式,机器视觉软件平台作为工业自动化的"智慧之眼",已广泛应用于3C电子、半导体、汽车零部件等众多领域,为品质检…

专业彩票网站建设轻极免费版wordpress主题

前言 1024 程序员节是中国程序员的节日&#xff0c;于每年的 10 月 24 日庆祝。这个节日旨在纪念和表彰程序员对科技和社会发展所做的贡献。 1024 程序员节最早由中国互联网公司 CSDN&#xff08;中国软件开发者网&#xff09;发起&#xff0c;自然而然地成为了中国程序员社区…