programing

python으로 요청을 포함한 "멀티파트/폼 데이터"를 전송하려면 어떻게 해야 합니까?

javaba 2022. 9. 30. 10:40
반응형

python으로 요청을 포함한 "멀티파트/폼 데이터"를 전송하려면 어떻게 해야 합니까?

『 』의 multipart/form-datarequests★★★★★★★★★ 송신 방법은 이해하지만, 이 으로 폼 데이터를 송신하는 방법은 이해할 수 파일 송신 방법은 이해하지만, 이 방법으로 폼 데이터를 송신하는 방법은 이해할 수 없습니다.

'아니다'를 하면,files으로 parameter(dictionary)를 지정합니다.requests multipart/form-data가 ★application/x-www-form-urlencodedPOST. 그러나 해당 사전의 실제 파일 사용에만 국한된 것은 아닙니다.

>>> import requests
>>> response = requests.post('http://httpbin.org/post', files=dict(foo='bar'))
>>> response.status_code
200

.org 에서 알 수 .org httpbin.org 、 httpbin.org and and 、 and and and and and 。response.json()하다

>>> from pprint import pprint
>>> pprint(response.json()['headers'])
{'Accept': '*/*',
 'Accept-Encoding': 'gzip, deflate',
 'Connection': 'close',
 'Content-Length': '141',
 'Content-Type': 'multipart/form-data; '
                 'boundary=c7cbfdd911b4e720f1dd8f479c50bc7f',
 'Host': 'httpbin.org',
 'User-Agent': 'python-requests/2.21.0'}

또한 단일 문자열 또는 바이트 개체 대신 태플을 사용하여 각 부분의 파일 이름, 컨텐츠 유형 및 추가 헤더를 더욱 제어할 수 있습니다.태플에는 파일명, 콘텐츠, 콘텐츠유형(옵션) 및 추가 헤더의 옵션 딕셔너리 등 2 ~4개의 요소가 포함됩니다.

태플 폼을 사용해서None「 」가 .filename="..."다음 부품에 대한 요청에서 파라미터가 삭제됩니다.

>>> files = {'foo': 'bar'}
>>> print(requests.Request('POST', 'http://httpbin.org/post', files=files).prepare().body.decode('utf8'))
--bb3f05a247b43eede27a124ef8b968c5
Content-Disposition: form-data; name="foo"; filename="foo"

bar
--bb3f05a247b43eede27a124ef8b968c5--
>>> files = {'foo': (None, 'bar')}
>>> print(requests.Request('POST', 'http://httpbin.org/post', files=files).prepare().body.decode('utf8'))
--d5ca8c90a869c5ae31f70fa3ddb23c76
Content-Disposition: form-data; name="foo"

bar
--d5ca8c90a869c5ae31f70fa3ddb23c76--

files순서 지정 및/또는 같은 이름의 여러 필드가 필요한 경우 에는 2개의 값 튜플 목록이 될 수도 있습니다.

requests.post(
    'http://requestb.in/xucj9exu',
    files=(
        ('foo', (None, 'bar')),
        ('foo', (None, 'baz')),
        ('spam', (None, 'eggs')),
    )
)

files ★★★★★★★★★★★★★★★★★」data에 따라 달라집니다.dataPOST ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★의 경우data 않으면 둘 다 사용됩니다.그것만 사용됩니다.렇지않data ★★★★★★★★★★★★★★★★★」files are are are are are are are are are are are are 。data첫 번째 목록입니다.

또, 뛰어난 제품도 있습니다.requests-toolbelt이 프로젝트에는 고급 멀티파트 지원이 포함됩니다.필드 정의와 같은 형식을 취합니다.files「」와 달리, 「」를 참조해 주세요.requests디폴트로는 파일명 파라미터를 설정하지 않습니다.오픈 를 스트리밍 할 수 .여기서, 「」는 「」의 「파일 오브젝트」를 참조해 주세요.requests는 먼저 내에 합니다.메모리에는 요구 본문이 포함되어 있습니다.

from requests_toolbelt.multipart.encoder import MultipartEncoder

mp_encoder = MultipartEncoder(
    fields={
        'foo': 'bar',
        # plain file object, no filename or mime type produces a
        # Content-Disposition header with just the part name
        'spam': ('spam.txt', open('spam.txt', 'rb'), 'text/plain'),
    }
)
r = requests.post(
    'http://httpbin.org/post',
    data=mp_encoder,  # The MultipartEncoder is posted as data, don't use files=...!
    # The MultipartEncoder provides the content-type header with the boundary:
    headers={'Content-Type': mp_encoder.content_type}
)

필드는 동일한 규칙을 따릅니다.2 ~ 4개의 요소가 포함된 태플을 사용하여 파일 이름, 부분 MIME 유형 또는 추가 헤더를 추가합니다.「 」와 files 「Default」 「Default」 「Default」 「Default」 「Default」 「Default」는 검출되지 .filename튜플을 사용하지 않을 경우 값을 매길 수 있습니다.

이전 답변 중 일부가 작성된 이후 요청이 변경되었습니다.상세한 것에 대하여는, Github 의 호를 참조해 주세요.또, 를 들면 이 코멘트를 참조해 주세요.

요면,,는files파라미터는 Requests quickstart의 "POST a Multipart-Encoded File" 섹션에서 설명한 바와 같이 키가 폼필드의 이름이고 값이 문자열 또는 2, 3, 또는4 길이의 태플인 사전을 사용합니다.

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

위에서 태플은 다음과 같이 구성되어 있다.

(filename, data, content_type, headers)

값이 문자열일 경우 파일명은 다음과 같이 키와 동일합니다.

>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}

Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

첫가 " "일 "None파일 이름 속성은 포함되지 않습니다.

>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}

Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream

72c2b6f406cdabd578c5fd7598557c52

하다를 요.files파일을 업로드할 필요가 없는 경우에도 POST 요청을 멀티파트 형식으로 전송하기 위한 파라미터입니다.

원래 요청 소스:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    ...
    :param files: (optional) Dictionary of ``'name': file-like-objects``
        (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,
        3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,
        where ``'content-type'`` is a string
        defining the content type of the given file
        and ``custom_headers`` a dict-like object 
        containing additional headers to add for the file.

관련 부품은 다음과 같습니다. can be a:

  • 2-tuple (오류, fileobj)
  • 3-tuple (fileobj, content_type)
  • 4-tuple (fileobj, content_type, custom_type).

☝ 파일을 다룰 때는 실제 파일 개체이거나 일반 텍스트 필드를 다룰 때는 문자열일 수 있습니다.

위의 내용에 따르면 업로드할 파일과 폼필드를 모두 포함하는 가장 간단한 멀티파트 폼 요구는 다음과 같습니다.

import requests

multipart_form_data = {
    'upload': ('custom_file_name.zip', open('myfile.zip', 'rb')),
    'action': (None, 'store'),
    'path': (None, '/path1')
}

response = requests.post('https://httpbin.org/post', files=multipart_form_data)

print(response.content)

플레인 텍스트 필드용 튜플의 첫 번째 인수로 참고 - 파일 업로드에만 사용되는 파일 이름 필드의 자리 표시자이지만 데이터를 제출하려면 첫 번째 매개 변수로 전달해야 합니다.

이름이 같은 여러 필드

같은 이름의 필드를 여러 개 게시해야 하는 경우 사전 대신 페이로드를 튜플 목록(또는 튜플)으로 정의할 수 있습니다.

multipart_form_data = (
    ('file2', ('custom_file_name.zip', open('myfile.zip', 'rb'))),
    ('action', (None, 'store')),
    ('path', (None, '/path1')),
    ('path', (None, '/path2')),
    ('path', (None, '/path3')),
)

스트리밍 요청 API

위의 API가 사용자에게 충분하지 않은 경우 요청 도구 벨트를 사용하는 을 고려하십시오.pip install requests_toolbelt)는 파일 업로드 스트리밍을 지원하는 코어 요청 모듈의 확장입니다.또한 Multipart Encoder를 대신 사용할 수 있습니다.files를 사전,

MultipartEncoder는 실제 업로드 필드가 있는 경우와 없는 경우의 멀티파트 요구에 모두 사용할 수 있습니다. '아까운 친구'에게.data파라미터를 지정합니다.

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

multipart_data = MultipartEncoder(
    fields={
            # a file upload field
            'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')
            # plain text fields
            'field0': 'value0', 
            'field1': 'value1',
           }
    )

response = requests.post('http://httpbin.org/post', data=multipart_data,
                  headers={'Content-Type': multipart_data.content_type})

동일한 이름으로 여러 필드를 전송해야 하거나 양식 필드의 순서가 중요한 경우 사전 대신 튜플 또는 목록을 사용할 수 있습니다.

multipart_data = MultipartEncoder(
    fields=(
            ('action', 'ingest'), 
            ('item', 'spam'),
            ('item', 'sausage'),
            ('item', 'eggs'),
           )
    )

다음은 요청을 사용하여 추가 매개 변수가 포함된 단일 파일을 업로드하는 간단한 코드 조각입니다.

url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'

files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}

response = requests.put(url, files=files, data=payload, verify=False)

콘텐츠 유형을 명시적으로 지정할 필요는 없습니다.

메모: 위의 답변 중 하나에 대해 코멘트를 하고 싶었지만 평판이 좋지 않아 여기에 새로운 답변이 작성되었습니다.

하다를 요.name「HTML」입니다.§:

autocomplete="off" name="image">

?name="image">파일을 업로드하기 위한 사이트의 HTML에서 찾을 수 있습니다. 할 때 .Multipart/form-data

스크립트:

import requests

site = 'https://prnt.sc/upload.php' # the site where you upload the file
filename = 'image.jpg'  # name example

여기서 이미지 대신 HTML로 업로드 파일 이름을 추가합니다.

up = {'image':(filename, open(filename, 'rb'), "multipart/form-data")}

업로드에서 업로드 버튼을 클릭해야 하는 경우 다음과 같이 사용할 수 있습니다.

data = {
     "Button" : "Submit",
}

그런 다음 요청을 시작합니다.

request = requests.post(site, files=up, data=data)

완료, 파일 업로드 성공

「」를 .filesPOST 「」, 「」, 「」,Content-Type요청은 자동으로 로 설정됩니다.multipart/form-data(멀티 파트 payload의 각 신체 부위를 분리하기 위해 사용되는 문자열에 의해 지정됨), 전송만 가능할지 여부files , 「」form 및 "" " " " 。files동시에 설정하려고 하면됩니다. Content-Type ( 경우는 수동으로).반면, 만약 그렇다면form되었습니다.Content-Type으로 동 would would would would would 로 설정됩니다.application/x-www-form-urlencoded.

요.Content-Type하여 위의 이 예에서는 ( (''의 파일.key (예:)'files'이하에 나타내는 경우)와 옵션에서 사용할 수 있습니다.form 데이터,data=form_data)의 POST과 멀티플의 ""files여기와 여기 각각 있습니다.대용량 파일을 메모리에 읽지 않고 업로드해야 하는 경우 스트리밍 업로드를 참조하십시오.서버측에서는, 필요한 경우는, 이하의 코드 스니펫을 취득해, Fast 를 사용하고 있는 회답을 봐 주세요.API 웹 프레임워크

import requests

url = 'http://127.0.0.1:8000/submit'
files = [('files', open('test_files/a.txt', 'rb')), ('files', open('test_files/b.txt', 'rb'))]
#file = {'file': open('test_files/a.txt','rb')} # for sending a single file
form_data ={"name": "foo", "point": 0.13, "is_accepted": False}
resp = requests.post(url=url, data=form_data, files=files) 
print(resp.json())
print(resp.request.headers['content-type'])
import requests
# assume sending two files
url = "put ur url here"
f1 = open("file 1 path", 'rb')
f2 = open("file 2 path", 'rb')
response = requests.post(url,files={"file1 name": f1, "file2 name":f2})
print(response)

위의 예를 명확히 하기 위해

"파일을 업로드할 필요가 없는 경우에도 여러 형식의 POST 요청을 전송하려면 files 파라미터를 사용해야 합니다."

파일={}

불행히도 효과가 없어요.

예를 들어, 몇 가지 더미 값을 입력해야 합니다.

files={"foo": "bar"}

Bitbucket의 REST API에 파일을 업로드하려고 할 때 이 사실을 알게 되었고, "Unsupported Media Type" 오류를 피하기 위해 다음과 같은 혐오사항을 작성해야 했습니다.

url = "https://my-bitbucket.com/rest/api/latest/projects/FOO/repos/bar/browse/foobar.txt"
payload = {'branch': 'master', 
           'content': 'text that will appear in my file',
           'message': 'uploading directly from python'}
files = {"foo": "bar"}
response = requests.put(url, data=payload, files=files)

:O=

멀티파트/폼 데이터 키 및 값 전송

curl 명령:

curl -X PUT http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F taskStatus=1

python requests - 더 복잡한 POST 요청:

    updateTaskUrl = "http://127.0.0.1:8080/api/xxx"
    updateInfoDict = {
        "taskStatus": 1,
    }
    resp = requests.put(updateTaskUrl, data=updateInfoDict)

멀티파트/폼 데이터 파일 전송

curl 명령:

curl -X POST http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F file=@/Users/xxx.txt

python 요청 - 멀티파트 인코딩 파일 POST:

    filePath = "/Users/xxx.txt"
    fileFp = open(filePath, 'rb')
    fileInfoDict = {
        "file": fileFp,
    }
    resp = requests.post(uploadResultUrl, files=fileInfoDict)

그게 다야

여기 하나의 큰 파일을 멀티파트 폼 데이터로 업로드하기 위해 필요한 파이썬 스니펫이 있습니다.서버 측에서 NodeJs Multer 미들웨어가 실행되고 있는 경우.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

서버측에서는, 다음의 URL 에 있는 멀티 메뉴얼을 확인해 주세요.https://github.com/expressjs/multer 에서는, 1 개의 파일을 받아들이기 위해서 필드 single( 「fieldName」)이 사용됩니다.

var upload = multer().single('fieldName');

이것은 멀티파트 요청으로 파일을 보내는 한 가지 방법입니다.

import requests
headers = {"Authorization": "Bearer <token>"}
myfile = 'file.txt'
myfile2 = {'file': (myfile, open(myfile, 'rb'),'application/octet-stream')}
url = 'https://example.com/path'
r = requests.post(url, files=myfile2, headers=headers,verify=False)
print(r.content)

기타 접근법

import requests

url = "https://example.com/path"

payload={}
files=[
  ('file',('file',open('/path/to/file','rb'),'application/octet-stream'))
]
headers = {
  'Authorization': 'Bearer <token>'
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

둘 다 테스트해 봤는데 둘 다 정상이에요.

import json
import os
import requests
from requests_toolbelt import MultipartEncoder

AUTH_API_ENDPOINT = "http://localhost:3095/api/auth/login"

def file_upload(path_img, token ):
    url = 'http://localhost:3095/api/shopping/product/image'
    name_img = os.path.basename(path_img)

    mp_encoder = MultipartEncoder(
        fields={
            'email': 'mcm9@gmail.com',
            'source': 'tmall',
            'productId': 'product_0001',
            'image': (name_img, open(path_img, 'rb'), 'multipart/form-data')
        #'spam': ('spam.txt', open('spam.txt', 'rb'), 'text/plain'),
        }
    )

    head = {'Authorization': 'Bearer  {}'.format(token),
            'Content-Type': mp_encoder.content_type}

    with requests.Session() as s:
        result = s.post(url, data=mp_encoder, headers=head)

    return result

def do_auth(username, password, url=AUTH_API_ENDPOINT):
    data = {
        "email": username,
        "password": password
    }

    # sending post request and saving response as response object
    r = requests.post(url=url, data=data)

    # extracting response text
    response_text = r.text

    d = json.loads(response_text)
    # print(d)

    return d


if __name__ == '__main__':
    result = do_auth('mcm4@gmail.com','123456')
    token = result.get('data').get('payload').get('token')
    print(token)
    result = file_upload('/home/mcm/Pictures/1234.png',token)
    print(result.json())

python 3의 request module과 함께 URL_server로 request를 보내려고 합니다.이것으로 충분합니다.

# -*- coding: utf-8 *-*
import json, requests

URL_SERVER_TO_POST_DATA = "URL_to_send_POST_request"
HEADERS = {"Content-Type" : "multipart/form-data;"}

def getPointsCC_Function():
  file_data = {
      'var1': (None, "valueOfYourVariable_1"),
      'var2': (None, "valueOfYourVariable_2")
  }

  try:
    resElastic = requests.post(URL_GET_BALANCE, files=file_data)
    res = resElastic.json()
  except Exception as e:
    print(e)

  print (json.dumps(res, indent=4, sort_keys=True))

getPointsCC_Function()

장소:

  • URL_SERVER_TO_POST_DATA = 데이터를 전송할 서버
  • HEADERs = 헤더를 보냈습니다.
  • file_data = 전송된 파라미터

우편 배달원이 추가 양식 필드와 함께 파일 업로드용 코드를 생성했습니다.

import http.client
import mimetypes
from codecs import encode

conn = http.client.HTTPSConnection("data.XXXX.com")
dataList = []
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name=batchSize;'))

dataList.append(encode('Content-Type: {}'.format('text/plain')))
dataList.append(encode(''))

dataList.append(encode("1"))
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name=file; filename={0}'.format('FileName-1.json')))

fileType = mimetypes.guess_type('FileName-1.json')[0] or 'application/octet-stream'
dataList.append(encode('Content-Type: {}'.format(fileType)))
dataList.append(encode(''))

with open('FileName-1.json', 'rb') as f:
  dataList.append(f.read())
dataList.append(encode('--'+boundary+'--'))
dataList.append(encode(''))
body = b'\r\n'.join(dataList)
payload = body
headers = {
  'Cookie': 'XXXXXXXXXXX',
  'Content-type': 'multipart/form-data; boundary={}'.format(boundary)
}
conn.request("POST", "/fileupload/uri/XXXX", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

언급URL : https://stackoverflow.com/questions/12385179/how-to-send-a-multipart-form-data-with-requests-in-python

반응형