1,使用表单的形式传送数据:
使用多线程的方式,通过表单的格式将数据传送到后台:
def requests_send(url,files, i):
result = requests.post(url, data=files)
( 后台获取数据:data_ID = request.POST.get('data_id')
realtime_data = request.POST.get('data')).
texts = json.loads(result.text)
print('返回结果:' ,i ,texts['data_id'])
def mul_threads_hour(url):
data_list = os.listdir(path2) #这是获取某一个地址的所有的数据id
for s in range(1):
threads = []
for i in range(50*s,50*(s+1)):
request_data = readFile2(path2+ data_list[i]) #读取需要的数据
real_time_data = request_data.decode('utf-8') #字节准换为字符串
files = {'data_id': data_list[i].split('.')[0], 'data': real_time_data}
t1 = threading.Thread(target=requests_send,args=(url,files,i))
threads.append(t1)
start_time = time.time()
for t in threads:
t.setDaemon(True)
t.start()
for t in threads:
t.join()
del threads[:]
print('总共的时间==============', time.time() - start_time)
print('所有线程结束')
2,使用json字节流将数据传到后台:
import urllib
import json
headers = {}
headers['Content-Type'] = 'application/json; charset=utf-8'
def request_post_json(urls, j_data, i):
print('i--------',i)
req= urllib.request.Request(url=urls,headers=headers,data=bytes(j_data, encoding='utf-8'))
(这里的字符串要转换为字节数组)
page = urllib.request.urlopen(req)
res = page.read()
page.close()
# print('result==============',res)
多线程将数据发送到后台:
def jsonPost(url):
data_list = os.listdir(path2)
for s in range(1):
threads = []
for i in range(1 * s, 1 * (s + 1)):
request_data = readFile2(path2 + data_list[i])
values = {}
values['data_id'] = data_list[i].split('.')[0]
values['data'] = str(request_data, encoding='utf-8') (要将字节转换为字符串)
j_data = json.dumps(values)
t1 = threading.Thread(target=request_post_json, args=(url, j_data, i))
threads.append(t1)
start_time = time.time()
for t in threads:
t.setDaemon(True)
t.start()
for t in threads:
t.join()
del threads[:]
print('总共的时间==============', time.time() - start_time)
print('所有线程结束')
后台读取:
try:
request_data = str(request.body, encoding='utf-8') (将字节转换字符串)
req = json.loads(request_data)
except:
print(traceback.print_exc())
realtime_data = req['data']
data_ID = req['data_id']
2,前端和后台数据进行传输:
1)使用form表单:
向后台传输数据使用的方式:post和get;
后台获得数据,后可以进行重定向,使用HttpResponseRedirect的方式进行重定向
2)使用ajax的方式向后台输出数据,使用的方式:get,post
但是后台返回的return肯定返回ajax。这样,要想重定向,必须将重定向的地址返回给success,之后在前端进行重定向。