api安全認證

3、auth自定義受權html

客戶端代碼:python

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

 

 

線程池和進程池django

#!/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框架json

#!/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'\r\n\r\n', 1)
        self.body = body
        header_list = headers.split(b'\r\n')
        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\r\nHost:%s\r\n\r\n' % 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框架
相關文章
相關標籤/搜索