zoukankan      html  css  js  c++  java
  • api安全认证

    三、auth自定义授权

    客户端代码:

    import requests
    import hashlib
    import time
    
    current_time = time.time()
    #自意义的字符串app_id,和服务端ck一致
    app_id ='8kasoimnasodn8687asdfkmasdf'
    app_id_time = "%s|%s" % (app_id,current_time,)
    
    m = hashlib.md5()
    m.update(bytes(app_id_time,encoding='utf-8'))
    authkey = m.hexdigest()
    
    authkey_time ="%s|%s" % (authkey,current_time,)
    print(authkey_time)
    
    host_data = {
        'status':True,
        'data':{
            'hostname':'c1.com',
            'disk':{'status':True,'data':'xxx'},
            'mem':{'status':True,'data':'xxx'},
            'nic':{'status':True,'data':'xxx'},
        },
    }
    
    
    response=requests.post(
        url='http://127.0.0.1:8000/api/asset/',
        json=host_data,
        headers={'authkey':authkey_time},
    )
    
    print(response.text)
    
    
    # requests.get(url='http://127.0.0.1:8000/api/asset/?k1=123')
    # requests.get(url='http://127.0.0.1:8000/api/asset/',params={'k1':'v1','k2':'v2'})
    # requests.post(
    #     url='http://127.0.0.1:8000/api/asset/',
    #     params={'k1':'v1','k2':'v2'}, # GET形式传值
    #     data={'username':'1123','pwd': '666'}, # POST形式传值
    #     headers={'a':'123'} # 请求头数据
    # )

    服务端代码:

    from django.shortcuts import render,HttpResponse
    from django.views.decorators.csrf import csrf_exempt,csrf_protect
    import hashlib
    import time
    
    #自定义的字符串
    ck='8kasoimnasodn8687asdfkmasdf'
    #5秒钟的授权列表
    auth_list = []
    
    @csrf_exempt
    def asset(request):
        auth_key_time = request.META.get('HTTP_AUTHKEY')
        auth_key_client,client_ctime = auth_key_time.split('|')
        server_current_time = time.time()
        if server_current_time - 5 > float(client_ctime):
            #太久远了
            return HttpResponse('时间太久远了')
        if auth_key_time in auth_list:
            #已经访问过了
            return HttpResponse('你来晚了')
        key_time = '%s|%s' %(ck,client_ctime)
        m = hashlib.md5()
        m.update(bytes(key_time,encoding='utf-8'))
        authkey = m.hexdigest()
    
        if authkey != auth_key_client:
            return HttpResponse('授权失败')
        auth_list.append(auth_key_time)
    
        if request.method == 'POST':
            import json
            print(authkey)
            host_info = json.loads(str(request.body,encoding='utf-8'))
            print(host_info)
        return HttpResponse('授权成功')
    
    
    
    
    
    def test(request):
        # print(request.POST,type(request.POST))
        # from django.http.request import QueryDict
        response = render(request,'index.html')
        response.set_signed_cookie('kkkk','vvvv',salt='asdf')
        return response

    线程池和进程池

    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    
    
    #######  编写方式一  ##########
    
    from concurrent.futures import ThreadPoolExecutor
    from concurrent.futures import ProcessPoolExecutor
    import requests
    import time
    
    
    def task(url):
        response = requests.get(url)
        print(url,response)
    
    
    pool = ThreadPoolExecutor(5)
    
    url_list = [
        'https://www.baidu.com',
        'http://www.sina.com.cn',
        'http://cn.bing.com',
        'https://home.cnblogs.com/u/liaoboshi/',
        'https://www.linkedin.com',
        'http://mil.news.baidu.com',
    ]
    
    for url in url_list:
        pool.submit(task,url)
    
    pool.shutdown(wait=True)
    
    
    
    
    
    
    #######  编写方式一  ################################
    
    from concurrent.futures import ThreadPoolExecutor
    import requests
    import time
    
    
    def task(url):
        '''
         下载页面
        :param url:
        :return:
        '''
        response = requests.get(url)
        return response
    
    
    def done(future,*args,**kwargs):
        response = future.result()
        print(response.status_code,response.content)
    
    
    pool = ThreadPoolExecutor(5)
    
    url_list = [
        'https://www.baidu.com',
        'http://www.sina.com.cn',
        'http://cn.bing.com',
        'https://home.cnblogs.com/u/liaoboshi/',
        'https://www.linkedin.com',
        'http://mil.news.baidu.com',
    ]
    
    for url in url_list:
        v = pool.submit(task,url)
        # 每一个线程函数走完,再走下面的另一个回调函数
        v.add_done_callback(done)
    
    pool.shutdown(wait=True)

    自定义异步IO框架

    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    
    # IO多路复用: 监听多个socket对象,感知变化,利用其特性可以并发出异步IO模块
    # 异步IO: 异步是非阻塞  非阻塞 + IO多路复用
                        # setblocking(False)
    
    
    import select
    import socket
    
    class HttpRequest:
        def __init__(self,sk,host,callback):
            self.socket = sk
            self.host = host
            self.callback = callback
    
        def fileno(self):
            return self.socket.fileno()
    
    class HttpResponse:
        def __init__(self,recv_data):
            self.recv_data = recv_data
            self.header_dict = {}
            self.body = None
    
            self.initialize()
    
        def initialize(self):
            headers, body = self.recv_data.split(b'
    
    ', 1)
            self.body = body
            header_list = headers.split(b'
    ')
            for h in header_list:
                h_str = str(h, encoding='utf-8')
                v = h_str.split(':', 1)
                if len(v) == 2:
                    self.header_dict[v[0]] = v[1]
    
    
    class AsyncRequest:
        def __init__(self):
            self.conn = []
            self.connection = []   # 用于检测是否已经连接成功
    
        def add_request(self,host,callback):
            try:
                sk = socket.socket()   # 创建 socket 对象
                sk.setblocking(False)  # 设置socket为非阻塞
                sk.connect((host,80,)) # 连接 主机
    
            except BlockingIOError as e:  # 设置socket为非阻塞后,会报错,要抓住异常
                pass
    
            request = HttpRequest(sk,host,callback)  # 创建一个socket对象 要返回self.socket.fileno()
            self.conn.append(request)     # 把对象加到列表里
            self.connection.append(request)  # 把对象加到列表里
    
        def run(self):
    
            while True:
                rlist,wlist,elist = select.select(self.conn,self.connection,self.conn,0.05)   # 创建select对象
                for w in wlist:
                    print(w.host,'连接成功...')
                    # 只要能循环到,表示socket和服务器端已经连接成功
                    tpl = 'GET / HTTP/1.0
    Host:%s
    
    ' % w.host
                    w.socket.send(bytes(tpl,encoding='utf8'))     # 给发服务器送消息
                    self.connection.remove(w)   # 发送完消息后,删除对象
                for r in rlist:
                    # r,是HttpRequest
                    recv_data = bytes()
                    while True:
                        try:
                            chunck = r.socket.recv(8096)  # 接收服务器返回消息
                            recv_data += chunck
                        except Exception as e:
                            break
    
                    response = HttpResponse(recv_data) # 返回的消息包装成字典(请求头和请求体)
                    r.callback(response)  # 执行回调函数
                    r.socket.close()  # 关闭连接
                    self.conn.remove(r)   #删除对象
                if len(self.conn) == 0:
                    break
    
    
    def f1(response):  # 回调函数拿到返回的请求头和请求体
        print('保存到文件', response.header_dict)
    
    
    def f2(response):
        print('保存到数据库', response.header_dict)
    
    
    url_list = [
        {'host': 'www.baidu.com', 'callback': f1},
        {'host': 'cn.bing.com', 'callback': f2},
        {'host': 'www.cnblogs.com', 'callback': f2},
    ]
    
    
    req = AsyncRequest() # 创建一个对象
    
    for item in url_list:
        req.add_request(item['host'],item['callback'])  # 运行类的add_request方法,把 主机名 和 回调函数 传进去
    
    req.run() # 运行类的run方法
    自定义异步IO框架
  • 相关阅读:
    xcode8.3 shell 自动打包脚本
    MarkDown常用语法记录
    正则表达式matcher.group()用法
    使用Jenkins进行持续集成
    Java8新特性:Stream的使用
    zookeeper windows 下配置和基础命令
    JAVA文件中获取路径及WEB应用程序获取路径方法
    共享锁(S锁)和排它锁(X锁)
    zookeeper 官方文档——综述
    zookeeper 入门指导
  • 原文地址:https://www.cnblogs.com/liaoboshi/p/6941378.html
Copyright © 2011-2022 走看看