python模拟浏览器文件上传,csrf放行

服务器端视图函数

from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt

# Create your views here.
@csrf_exempt#这个可以对csrf进行放行
def up(request,):
    file_list = request.FILES.getlist('save_data')
    for i in file_list:
        for x in i :
            print(x)
    return HttpResponse('ok')

 客户端

import time
import datetime
import hashlib
import os
import random
import sys
import requests
import json

from requests_toolbelt.multipart.encoder import MultipartEncoder
url = 'http://127.0.0.1:8000/up/'#文件上传的url


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0',
    'Referer': url
}

multipart_encoder = MultipartEncoder(
    fields = {
        'save_name': '论坛.txt',#文件名
        'save_data': ('论坛.txt', open('论坛.txt', 'rb'), 'application/octet-stream')
    },
    boundary = '-----------------------------' + str(random.randint(1e28, 1e29 - 1))
)

headers['Content-Type'] = multipart_encoder.content_type
#请求头必须包含一个特殊的头信息,类似于Content-Type: multipart/form-data; boundary=${bound}

responseStr = requests.post(url, data=multipart_encoder, headers=headers)
print(responseStr.text)#服务器的响应

 

posted @ 2019-07-11 11:18  充电宝宝  阅读(456)  评论(0编辑  收藏  举报