基于Django实现

  在使用RestFramework之前我们先用Django自己实现以下API。

  API完全可以有我们基于Django自己开发,原理是给出一个接口(URL),前端向URL发送请求以获取数据。这样能实现前后端分离的效果。但Django实现的API许多功能都需要我们自己写。

URL

  1. from django.contrib import admin
  2. from django.conf.urls import url, include
  3. from app01 import views
  4. from app02 import views
  5.  
  6. urlpatterns = [
  7. url('admin/', admin.site.urls),
  8. url('app02/', include('app02.urls'))#路由分发
  9. ]

全局路由

  1. from app02 import views
  2. from django.conf.urls import url
  3. urlpatterns = [
  4. url('^users/', views.users),
  5. url('^user/(\d+)', views.user),
  6. #######FBV与CBV的分界线########
  7. url('^users/', views.UsersView.as_view()),
  8. url('^user/', views.UserView.as_view()),
  9. ]

app02/urls.py

views.py

  FBV

  1. from django.shortcuts import render,HttpResponse
  2.  
  3. import json
  4.  
  5. def users(request):
  6. response = {'code':1000,'data':None} #code用来表示状态,比如1000代表成功,1001代表
  7. response['data'] = [
  8. {'name':'Damon','age':22},
  9. {'name':'Stefan','age':10},
  10. {'name':'Elena','age':11},
  11. ]
  12. return HttpResponse(json.dumps(response)) #返回就送字符串,前端解析
  13.  
  14. def user(request,pk):
  15. if request.method =='GET':
  16. return HttpResponse(json.dumps({'name':'Stefan','age':11})) #返回一条数据
  17. elif request.method =='POST':
  18. return HttpResponse(json.dumps({'code':1111})) #返回一条数据
  19. elif request.method =='PUT':
  20. pass
  21. elif request.method =='DELETE':
  22. pass

FBV

  CBV

  1. from django.views import View
  2. class UsersView(View):
  3. def get(self,request):
  4. response = {'code':1000,'data':None}
  5. response['data'] = [
  6. {'name': 'Damon', 'age': 22},
  7. {'name': 'Stefan', 'age': 10},
  8. {'name': 'Elena', 'age': 11},
  9. ]
  10. return HttpResponse(json.dumps(response),stutas=200)
  11.  
  12. class UserView(View):
  13. def get(self,request,pk):
  14. return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据
  15. def post(self,request,pk):
  16. return HttpResponse(json.dumps({'code':1111})) #返回一条数据
  17. def put(self,request,pk):
  18. pass
  19. def delete(self,request,pk):
  20. pass

CBV

注:通常我们在前后端分离进行编程时会推崇使用CBV的形式,CBV的代码可读性较高。

基于RestFramework实现

安装:

  1. pip3 install djangorestframework -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com

  RestFramework可以直接在Django中使用,安装完RestFramework后在Django中可以当做模块一般导入即可使用。(记得在settings.py中进行注册,如app)

URL与基于Django实现相同,这里选用CBV的形式

  1. from app02 import views
  2. from django.conf.urls import url
  3. urlpatterns = [
  4. url('^users/', views.UsersView.as_view()),#CBV必须要有as_view()
  5. url('^user/', views.UserView.as_view()),
  6. ]

views.py

  CBV

  1. #导入rest_framework,自定义视图的类需继承APIView
  2. from rest_framework.views import APIView
  3. from rest_framework.response import Response
  4.  
  5. class TestView(APIView):
  6. def dispatch(self, request, *args, **kwargs):
  7. """
  8. 请求到来之后,在url中执行as_view()就会执行dispatch方法,dispatch方法是APIView类中内置的,根据请求方式不同触发 get/post/put等方法。可自定制~
  9.  
  10. 注意:APIView中的dispatch方法有好多好多的功能
  11. """
  12. return super().dispatch(request, *args, **kwargs)
  13.  
  14. def get(self, request, *args, **kwargs):
  15. return Response('GET请求,响应内容')
  16.  
  17. def post(self, request, *args, **kwargs):
  18. return Response('POST请求,响应内容')
  19.  
  20. def put(self, request, *args, **kwargs):
  21. return Response('PUT请求,响应内容')

注:重要的功都在APIView的dispatch中触发。要掌握RestFramework,必须弄懂dispatch方法做了些什么,这样我们才可以根据自己的需求进行自定制。

dispatch基本源码剖析

  我们在继承了APIView之后就可以重写里面的方法进行自定制。此时我们需要先弄懂APIView里到底封装了哪些方法。在APIView中,最重要的就是dispatch方法。

请求在url中执行as_view()时就会触发dispatch,进入源码我们可以看到dispatch主要做了四件事:

  1. #在APIView类中:
  2. def dispatch(self, request, *args, **kwargs):
  3. """
  4. `.dispatch()` is pretty much the same as Django's regular dispatch,
  5. but with extra hooks for startup, finalize, and exception handling.
  6. """
  7. self.args = args
  8. self.kwargs = kwargs
  9. # 1.封装Django原始的request,使得用了framework以后的request都具有更多功能
  10. """
  11. 增加的功能
  12. parsers=self.get_parsers(),
  13. authenticators=self.get_authenticators(),#获取认证相关的所有类并实例化,传入request对象
  14. negotiator=self.get_content_negotiator(),
  15. parser_context=parser_context
  16. """
  17. request = self.initialize_request(request, *args, **kwargs)
  18. self.request = request#将封装后的request赋值给原始request
  19. self.headers = self.default_response_headers # deprecate?
  20.  
  21. try:
  22. """
  23. 2.版本处理、用户认证、权限、访问频率限制
  24. """
  25. self.initial(request, *args, **kwargs)
  26.  
  27. # Get the appropriate handler method
  28. if request.method.lower() in self.http_method_names:
  29. handler = getattr(self, request.method.lower(),
  30. self.http_method_not_allowed)
  31. else:
  32. handler = self.http_method_not_allowed
  33. #3.执行函数get/post/put/delete
  34. response = handler(request, *args, **kwargs)
  35.  
  36. except Exception as exc:
  37. response = self.handle_exception(exc)
  38. #4.对返回结果进行再次加工
  39. self.response = self.finalize_response(request, response, *args, **kwargs)
  40. return self.response

接下来我们对每一步进行具体的分析

第一步:封装request

  1. request = self.initialize_request(request, *args, **kwargs)
  2. #查看initialize_request做了什么
  3. def initialize_request(self, request, *args, **kwargs):
  4. """
  5. Returns the initial request object.
  6. """
  7. parser_context = self.get_parser_context(request)
  8.  
  9. return Request(
  10. request,
  11. parsers=self.get_parsers(),
  12. authenticators=self.get_authenticators(),#获取认证相关的所有类并实例化,传入request对象。优先找自己的,没有就找父类的
  13. negotiator=self.get_content_negotiator(),
  14. parser_context=parser_context
  15. )

1.1、我们看到request封装了一个认证的功能——获取认证相关的所有的类并实例化,看看get_authenticators()做了什么

  1. def get_authenticators(self):
  2. """
  3. Instantiates and returns the list of authenticators that this view can use.
  4. """
  5. #返回的是对象列表[SessionAuthentication,BaseAuthentication]
  6. return [auth() for auth in self.authentication_classes]
  7.  
  8. #self.authentication_classes是封装有认证功能的类的列表
  9. authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES #默认的,如果自己有会优先执行直接的

1.2、去settings.py查看默认的配置是什么

  1. DEFAULTS = {
  2. # Base API policies
  3. 'DEFAULT_AUTHENTICATION_CLASSES': (
  4. 'rest_framework.authentication.SessionAuthentication', #这时候就找到了他默认认证的类了,可以导入看看
  5. 'rest_framework.authentication.BasicAuthentication'
  6. ),

1.3、导入SessionAutenticationBasicAuthentication查看这两个雷兜风装了什么功能

  1. from rest_framework.authentication import SessionAuthentication
  2. from rest_framework.authentication import BaseAuthentication
  1. class BaseAuthentication(object):
  2. """
  3. All authentication classes should extend BaseAuthentication.
  4. """
  5.  
  6. def authenticate(self, request):
  7. """
  8. Authenticate the request and return a two-tuple of (user, token).
  9. """
  10. raise NotImplementedError(".authenticate() must be overridden.")
  11.  
  12. def authenticate_header(self, request):
  13. """
  14. Return a string to be used as the value of the `WWW-Authenticate`
  15. header in a `401 Unauthenticated` response, or `None` if the
  16. authentication scheme should return `403 Permission Denied` responses.
  17. """
  18. pass

BaseAuthentication

  1. class BasicAuthentication(BaseAuthentication):
  2. """
  3. HTTP Basic authentication against username/password.
  4. """
  5. www_authenticate_realm = 'api'
  6.  
  7. def authenticate(self, request):
  8. """
  9. Returns a `User` if a correct username and password have been supplied
  10. using HTTP Basic authentication. Otherwise returns `None`.
  11. """
  12. auth = get_authorization_header(request).split()
  13.  
  14. if not auth or auth[0].lower() != b'basic':
  15. return None #返回none不处理。让下一个处理
  16.  
  17. if len(auth) == 1:
  18. msg = _('Invalid basic header. No credentials provided.')
  19. raise exceptions.AuthenticationFailed(msg)
  20. elif len(auth) > 2:
  21. msg = _('Invalid basic header. Credentials string should not contain spaces.')
  22. raise exceptions.AuthenticationFailed(msg)
  23.  
  24. try:
  25. auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') #用partition切割冒号也包括
  26. except (TypeError, UnicodeDecodeError, binascii.Error):
  27. msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
  28. raise exceptions.AuthenticationFailed(msg)
  29.  
  30. userid, password = auth_parts[0], auth_parts[2] # 返回用户和密码
  31. return self.authenticate_credentials(userid, password, request)
  32.  
  33. def authenticate_credentials(self, userid, password, request=None):
  34. """
  35. Authenticate the userid and password against username and password
  36. with optional request for context.
  37. """
  38. credentials = {
  39. get_user_model().USERNAME_FIELD: userid,
  40. 'password': password
  41. }
  42. user = authenticate(request=request, **credentials)
  43.  
  44. if user is None:
  45. raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
  46.  
  47. if not user.is_active:
  48. raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
  49.  
  50. return (user, None)
  51.  
  52. def authenticate_header(self, request):
  53. return 'Basic realm="%s"' % self.www_authenticate_realm

BasicAuthentication

1.4、简单自定制认证的类

  我们可以看到源码中最重要的就是BasicAuthenticationauthenticate方法,所以要自定制认证的类只需重写该方法即可

  1. class MyAuthentication(BaseAuthentication):
  2. def authenticate(self, request):
  3. token = request.query_params.get('token')#登录用户有tocken字段
  4. obj = models.UserInfo.objects.filter(token=token).first()
  5. if obj:
  6. return (obj.username,obj)
  7. return None
  8.  
  9. def authenticate_header(self, request):
  10. pass

第二步、版本处理、认证、权限、访问频率限制

  1. self.initial(request, *args, **kwargs)
  2.  
  3. #查看initial方法做了什么
  4. def initial(self, request, *args, **kwargs):
  5. """
  6. Runs anything that needs to occur prior to calling the method handler.
  7. """
  8. self.format_kwarg = self.get_format_suffix(**kwargs)
  9.  
  10. # Perform content negotiation and store the accepted info on the request
  11. neg = self.perform_content_negotiation(request)
  12. request.accepted_renderer, request.accepted_media_type = neg
  13.  
  14. # Determine the API version, if versioning is in use.
  15. #2.1 处理版本信息,获取版本必须用version
  16. version, scheme = self.determine_version(request, *args, **kwargs)
  17. request.version, request.versioning_scheme = version, scheme
  18.  
  19. # Ensure that the incoming request is permitted
  20. #2.2认证,将user封装到request对象中
  21. self.perform_authentication(request)
  22. #2.3 权限
  23. self.check_permissions(request)
  24. #2.4 对请求用户进行访问频率的限制
  25. self.check_throttles(request)

2.2.1、认证:查看perform_authentication方法,发现只是将user封装到了request中

  1. def perform_authentication(self, request):
  2.  
  3. request.user

2.2.2、查看request.user中都封装了什么

  1. class Request(object):
  2. @property
  3. def user(self):
  4. """
  5. Returns the user associated with the current request, as authenticated
  6. by the authentication classes provided to the request.
  7. """
  8. if not hasattr(self, '_user'):
  9. self._authenticate()#执行用户认证
  10. return self._user

2.2.3、执行self._authenticate() 开始用户认证,如果验证成功后返回元组: (用户,用户Token)

  1. def _authenticate(self):
  2. """
  3. Attempt to authenticate the request using each authentication instance
  4. in turn.
  5. """
  6. #循环对象列表
  7. for authenticator in self.authenticators:
  8. try:
  9. # 执行每一个对象的authenticate 方法
  10. user_auth_tuple = authenticator.authenticate(self)
  11. except exceptions.APIException:
  12. self._not_authenticated()
  13. raise
  14.  
  15. if user_auth_tuple is not None:
  16. self._authenticator = authenticator
  17. self.user, self.auth = user_auth_tuple#返回一个元组,赋给了self,就可以request.user,request.auth了
  18. return
  19.  
  20. self._not_authenticated()

2.2.4、在user_auth_tuple = authenticator.authenticate(self) 进行验证,如果验证成功,执行类里的authenticatie方法。如果用户没有认证成功:self._not_authenticated()

  1. def _not_authenticated(self):
  2. """
  3. Set authenticator, user & authtoken representing an unauthenticated request.
  4.  
  5. Defaults are None, AnonymousUser & None.
  6. """
  7. # 如果跳过了所有认证,默认用户和Token和使用配置文件进行设置
  8. self._authenticator = None
  9.  
  10. if api_settings.UNAUTHENTICATED_USER:
  11. self.user = api_settings.UNAUTHENTICATED_USER()# 默认值为:匿名用户AnonymousUser
  12. else:
  13. self.user = None# None 表示跳过该认证
  14.  
  15. if api_settings.UNAUTHENTICATED_TOKEN:
  16. self.auth = api_settings.UNAUTHENTICATED_TOKEN()# 默认值为:None
  17. else:
  18. self.auth = None
  19.  
  20. #默认值都可以在settings.py中进行自定制配置
  21. REST_FRAMEWORK = {
  22. 'UNAUTHENTICATED_USER': None,
  23. 'UNAUTHENTICATED_TOKEN': None,
  24.  
  25. }

2.3.、权限控制

  1. ######check_permissions方法#######
  2. def check_permissions(self, request):
  3. """
  4. Check if the request should be permitted.
  5. Raises an appropriate exception if the request is not permitted.
  6. """
  7. for permission in self.get_permissions():#寻找类中的get_permissions()方法
  8. if not permission.has_permission(request, self):#无权限则抛出异常
  9. self.permission_denied(
  10. request, message=getattr(permission, 'message', None)
  11. )
  12.  
  13. ######get_permissions方法#######
  14. def get_permissions(self):
  15. """
  16. Instantiates and returns the list of permissions that this view requires.
  17. """
  18. return [permission() for permission in self.permission_classes]#去settings.py中查是否有权限配置

2.4、对访问频率进行限制(以下简称限流)

  限流的主要目的还是为了防爬。一个网站的最终目的是为了让人去访问的,但是有时候会有一些人工智能做一些对网站有伤害的事,这时候我们就需要进行相应的限制了。权限的分配是一种对网站的保护的限制,但有些功能(比如看新闻、看动态等)是不需要任何权限只需要进入网站就可以查看的,这时我们就需要进行相应的限流操作,区分出非人类的用户访问予以限制。

  1. def check_throttles(self, request):
  2. """
  3. Check if request should be throttled.
  4. Raises an appropriate exception if the request is throttled.
  5. """
  6. """
  7. 循环每一个throttle对象,执行allow_request方法
  8. allow_request:
  9. 返回False,说明限制访问频率
  10. 返回True,说明不限制,通行
  11. 可自定制
  12. """
  13. for throttle in self.get_throttles():
  14. if not throttle.allow_request(request, self):
  15. self.throttled(request, throttle.wait())#throttle.wait()表示多少秒后可再次访问
  1. from __future__ import unicode_literals
  2.  
  3. import time
  4.  
  5. from django.core.cache import cache as default_cache
  6. from django.core.exceptions import ImproperlyConfigured
  7.  
  8. from rest_framework.settings import api_settings
  9.  
  10. class BaseThrottle(object):
  11. """
  12. Rate throttling of requests.
  13. """
  14.  
  15. def allow_request(self, request, view):
  16. """
  17. Return `True` if the request should be allowed, `False` otherwise.
  18. """
  19. raise NotImplementedError('.allow_request() must be overridden')
  20.  
  21. def get_ident(self, request):#唯一标识
  22. """
  23. Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR
  24. if present and number of proxies is > 0. If not use all of
  25. HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR.
  26. """
  27. xff = request.META.get('HTTP_X_FORWARDED_FOR')
  28. remote_addr = request.META.get('REMOTE_ADDR')#获取IP
  29. num_proxies = api_settings.NUM_PROXIES#获取代理信息
  30.  
  31. if num_proxies is not None:
  32. if num_proxies == 0 or xff is None:
  33. return remote_addr
  34. addrs = xff.split(',')
  35. client_addr = addrs[-min(num_proxies, len(addrs))]
  36. return client_addr.strip()
  37.  
  38. return ''.join(xff.split()) if xff else remote_addr
  39.  
  40. def wait(self):
  41. """
  42. Optionally, return a recommended number of seconds to wait before
  43. the next request.
  44. """
  45. return None#等待时长,可重写

BaseThrottle

  1. class SimpleRateThrottle(BaseThrottle):
  2. """
  3. 一个简单的缓存实现,只需要` get_cache_key() `。被覆盖。
  4. 速率(请求/秒)是由视图上的“速率”属性设置的。类。该属性是一个字符串的形式number_of_requests /期。
  5. 周期应该是:(的),“秒”,“M”,“min”,“h”,“小时”,“D”,“一天”。
  6. 以前用于节流的请求信息存储在高速缓存中。
  7. A simple cache implementation, that only requires `.get_cache_key()`
  8. to be overridden.
  9.  
  10. The rate (requests / seconds) is set by a `throttle` attribute on the View
  11. class. The attribute is a string of the form 'number_of_requests/period'.
  12.  
  13. Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
  14.  
  15. Previous request information used for throttling is stored in the cache.
  16. """
  17. cache = default_cache
  18. timer = time.time
  19. cache_format = 'throttle_%(scope)s_%(ident)s'
  20. scope = None
  21. THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
  22.  
  23. def __init__(self):
  24. if not getattr(self, 'rate', None):
  25. self.rate = self.get_rate()#点进去看到需要些一个scope 2/m
  26. self.num_requests, self.duration = self.parse_rate(self.rate)
  27.  
  28. def get_cache_key(self, request, view):#这个相当于是一个半成品,我们可以来补充它
  29. """
  30. Should return a unique cache-key which can be used for throttling.
  31. Must be overridden.
  32.  
  33. May return `None` if the request should not be throttled.
  34. """
  35. raise NotImplementedError('.get_cache_key() must be overridden')
  36.  
  37. def get_rate(self):
  38. """
  39. Determine the string representation of the allowed request rate.
  40. """
  41. if not getattr(self, 'scope', None):#检测必须有scope,没有就报错了
  42. msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
  43. self.__class__.__name__)
  44. raise ImproperlyConfigured(msg)
  45.  
  46. try:
  47. return self.THROTTLE_RATES[self.scope]
  48. except KeyError:
  49. msg = "No default throttle rate set for '%s' scope" % self.scope
  50. raise ImproperlyConfigured(msg)
  51.  
  52. def parse_rate(self, rate):
  53. """
  54. Given the request rate string, return a two tuple of:
  55. <allowed number of requests>, <period of time in seconds>
  56. """
  57. if rate is None:
  58. return (None, None)
  59. num, period = rate.split('/')
  60. num_requests = int(num)
  61. duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
  62. return (num_requests, duration)
  63.  
  64. # 1、一进来首先执行,
  65. def allow_request(self, request, view):
  66. """
  67. Implement the check to see if the request should be throttled.
  68.  
  69. On success calls `throttle_success`.
  70. On failure calls `throttle_failure`.
  71. """
  72. if self.rate is None:
  73. return True
  74.  
  75. self.key = self.get_cache_key(request, view)#2、执行get_cache_key
  76. if self.key is None:
  77. return True#不限制
  78.  
  79. self.history = self.cache.get(self.key, [])#3、得到的key,默认是一个列表,赋值给了self.history
  80. # self.history可以理解为每一个ip对应的访问记录
  81. self.now = self.timer()
  82.  
  83. # Drop any requests from the history which have now passed the
  84. # throttle duration
  85. while self.history and self.history[-1] <= self.now - self.duration:
  86. self.history.pop()
  87. if len(self.history) >= self.num_requests:
  88. return self.throttle_failure()
  89. return self.throttle_success()
  90.  
  91. def throttle_success(self):
  92. """
  93. Inserts the current request's timestamp along with the key
  94. into the cache.
  95. """
  96. self.history.insert(0, self.now)
  97. self.cache.set(self.key, self.history, self.duration)
  98. return True
  99.  
  100. def throttle_failure(self):
  101. """
  102. Called when a request to the API has failed due to throttling.
  103. """
  104. return False
  105.  
  106. def wait(self):
  107. """
  108. Returns the recommended next request time in seconds.
  109. """
  110. if self.history:
  111. remaining_duration = self.duration - (self.now - self.history[-1])
  112. else:
  113. remaining_duration = self.duration
  114.  
  115. available_requests = self.num_requests - len(self.history) + 1
  116. if available_requests <= 0:
  117. return None
  118.  
  119. return remaining_duration / float(available_requests)

SimpleRateThrottle

第三步、执行函数get/post/put/delete

  1. if request.method.lower() in self.http_method_names:#http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  2.   handler = getattr(self, request.method.lower(),self.http_method_not_allowed)#反射
  3. else:
  4.   handler = self.http_method_not_allowed#抛出异常

第四步、对返回结果进行再次加工

RestFramework——API基本实现及dispatch基本源码剖析的更多相关文章

  1. Django Rest Framework源码剖析(四)-----API版本

    一.简介 在我们给外部提供的API中,可会存在多个版本,不同的版本可能对应的功能不同,所以这时候版本使用就显得尤为重要,django rest framework也为我们提供了多种版本使用方法. 二. ...

  2. 第二十四课:jQuery.event.remove,dispatch的源码解读

    本课还是来讲解一下jQuery是如何实现它的事件系统的.这一课我们先来讲一下jQuery.event.remove的源码解读. remove方法的目的是,根据用户传参,找到事件队列,从里面把匹配的ha ...

  3. 老李推荐:第3章3节《MonkeyRunner源码剖析》脚本编写示例: MonkeyImage API使用示例 1

    老李推荐:第3章3节<MonkeyRunner源码剖析>脚本编写示例: MonkeyImage API使用示例   在上一节的第一个“增加日记”的示例中,我们并没有看到日记是否真的增加成功 ...

  4. 老李推荐: 第3章1节《MonkeyRunner源码剖析》脚本编写示例: MonkeyRunner API使用示例

    老李推荐: 第3章1节<MonkeyRunner源码剖析>脚本编写示例: MonkeyRunner API使用示例   MonkeyRunner这个类可以说是编写monkeyrunner脚 ...

  5. Web API 源码剖析之默认配置(HttpConfiguration)

    Web API 源码剖析之默认配置(HttpConfiguration) 我们在上一节讲述了全局配置和初始化.本节我们将就全局配置的Configuration只读属性进行展开,她是一个类型为HttpC ...

  6. Web API 源码剖析之默认消息处理程序链之路由分发器(HttpRoutingDispatcher)

    Web API 源码剖析之默认消息处理程序链-->路由分发器(HttpRoutingDispatcher) 我们在上一节讲述了默认的DefaultServer(是一个类型为HttpServer的 ...

  7. Web API源码剖析之HttpServer

    Web API源码剖析之HttpServer 上一节我们讲述全局配置.本节将讲述全局配置的DefaultServer,它是一个HttpServer类型. 主要作用就是接受每一次请求,然后分发给消息处理 ...

  8. Web API 源码剖析之全局配置

    Web API 源码剖析之全局配置 Web API  均指Asp.net Web API .本节讲述的是基于Web API 系统在寄宿于IIS. 本节主要讲述Web API全局配置.它是如何优雅的实现 ...

  9. Web API 源码剖析之默认消息处理程序链--》路由分发器(HttpRoutingDispatcher)

    我们在上一节讲述了默认的DefaultServer(是一个类型为HttpServer的只读属性,详情请参考 Web API 源码剖析之全局配置).本节将讲述DefaultHandler(是一个Http ...

随机推荐

  1. java程序员必须要学会的linux命令总结

    1.查找文件find / -name filename.txt 根据名称查找/目录下的filename.txt文件.find . -name “*.xml” 递归查找所有的xml文件2.查看一个程序是 ...

  2. WPF之Menu绑定XML

    一.XML文件 <?xml version="1.0" encoding="utf-8" ?> <MenuData xmlns="& ...

  3. 父页面操作嵌套iframe子页面的HTML标签元素

    一个页面A.html使用iframe嵌套一个页面B.html,在A页面写js操作B页面HTML元素,首先要获取到B页面document对象,才能对嵌套页面进行操作 请看一个实例,在A页面写js操作B页 ...

  4. TensorFlow Jupyter Notebook 和matplotlib安装配置

    Jupyter Notebook 和matplotlib Jupyter Notebook安装 Python 3 : python3 -m pip install --upgrade pip pyth ...

  5. C语言迷题:有符号数与无符号数的问题(转)

    https://my.oschina.net/kelvinfang/blog/134725

  6. Saltstack之通过grains在配置文件中赋值

    案例,使用salt给客户端安装zabbix agent时需要在配置文件中自动生成主机名信息 zabbix agent安装sls zabbix-agent-install: file.managed: ...

  7. bootstrap-switch 使用

    网址:http://www.bootcss.com/p/bootstrap-switch/ 界面设置不调用方法没成功,事件也不起作用不知道是jquery版本原因还是什么原因!,下面亲测试可以使用 $( ...

  8. [No0000C2]WPF 数据绑定的调试

    )DataBinding的表达式无效时,跟踪Debug的输出信息来查找原因(2)DataBinding的表达式有效,但是数据和期望值不同,此时可以在Converter中断点调试 :在VS输出窗口跟踪信 ...

  9. arcgisengine实现矩形转面

    面文件都有几何类型. arcengine在绘图时,不规则的多边形的几何类型是esriGeometryPolygon,矩形的几何类型是esriGeometryEnvelope,圆的几何类型是esriGe ...

  10. day5_集合

    集合也是一种数据类型,一个类似列表东西,它的特点是无序的,不重复的,也就是说集合中是没有重复的数据 集合的作用: 1.它可以把一个列表中重复的数据去掉,而不需要你再写判断---天生去重 2.可以做关系 ...