Hướng dẫn request utf-8 python - yêu cầu trăn utf-8

Tôi đang cố gắng đăng một đoạn văn bản chứa các ký hiệu Unicode ưa thích lên dịch vụ web bằng thư viện yêu cầu. Tôi đang sử dụng Python 3.5.

text = "Två dagar kvar🎉🎉"
r = requests.post("http://json-tagger.herokuapp.com/tag", data=text)
print(r.json()

Tôi nhận được một UnicodeEncodeError, nhưng tôi không thể hiểu những gì tôi đang làm sai về phía mình, các tài liệu cho các yêu cầu chỉ nói về Unicode trong các yêu cầu nhận được từ những gì tôi thấy.

    UnicodeEncodeError                        Traceback (most recent call last)
 in ()
     19         print("cleaned : " + line)
     20 
---> 21         r = requests.post("http://json-tagger.herokuapp.com/tag", data=line)
     22         sentences = r.json()['sentences']
     23         for sentence in sentences:

//anaconda/lib/python3.4/site-packages/requests/api.py in post(url, data, json, **kwargs)
    105     """
    106 
--> 107     return request('post', url, data=data, json=json, **kwargs)
    108 
    109 

//anaconda/lib/python3.4/site-packages/requests/api.py in request(method, url, **kwargs)
     51     # cases, and look like a memory leak in others.
     52     with sessions.Session() as session:
---> 53         return session.request(method=method, url=url, **kwargs)
     54 
     55 

//anaconda/lib/python3.4/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth,     timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    466         }
    467         send_kwargs.update(settings)
--> 468         resp = self.send(prep, **send_kwargs)
    469 
    470         return resp

//anaconda/lib/python3.4/site-packages/requests/sessions.py in send(self, request, **kwargs)
    574 
    575         # Send the request
--> 576         r = adapter.send(request, **kwargs)
    577 
    578         # Total elapsed time of the request (approximately)

//anaconda/lib/python3.4/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    374                     decode_content=False,
    375                     retries=self.max_retries,
--> 376                     timeout=timeout
    377                 )
    378 

//anaconda/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries,     redirect, assert_same_host, timeout, pool_timeout, release_conn, **response_kw)
    557             httplib_response = self._make_request(conn, method, url,
    558                                                   timeout=timeout_obj,
--> 559                                                   body=body, headers=headers)
    560 
    561             # If we're going to release the connection in ``finally:``, then

//anaconda/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout,     **httplib_request_kw)
    351         # conn.request() calls httplib.*.request, not the method in
    352         # urllib3.request. It also calls makefile (recv) on the socket.
--> 353         conn.request(method, url, **httplib_request_kw)
    354 
    355         # Reset the timeout for the recv() on the socket

//anaconda/lib/python3.4/http/client.py in request(self, method, url, body, headers)
   1086     def request(self, method, url, body=None, headers={}):
   1087         """Send a complete request to the server."""
-> 1088         self._send_request(method, url, body, headers)
   1089 
   1090     def _set_content_length(self, body):

//anaconda/lib/python3.4/http/client.py in _send_request(self, method, url, body, headers)
   1123             # RFC 2616 Section 3.7.1 says that text default has a
   1124             # default charset of iso-8859-1.
-> 1125             body = body.encode('iso-8859-1')
   1126         self.endheaders(body)
   1127 

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 14-15: ordinal not in range(256)

Giải pháp thay thế: Tôi xóa tất cả các ký tự Unicode khỏi văn bản khỏi khối "biểu tượng cảm xúc", khối u+1f600 - u+1f64f và khối ký hiệu và chữ tượng hình " cần phải có biểu tượng cảm xúc và hình ảnh để phân tích: I remove all unicode characters from the text from the "emoticon" block, U+1F600 - U+1F64F and Symbols And Pictographs" block, U+1F300 - U+1F5FF according to this answer with the following code, since I don't need emoticons and pictures for the analysis:

text = re.sub(r'[^\u1F600-\u1F64F ]|[^\u1F300-\u1F5FF ]',"",text)

Cập nhật người tạo dịch vụ web đã sửa lỗi này ngay bây giờ và cập nhật tài liệu. Tất cả những gì bạn phải làm là gửi một chuỗi được mã hóa, trong Python 3: The creator of the web service has fixed this now and updated the documentation. All you have to do is to send an encoded string, in Python 3:

""Två dagar kvar🎉🎉".encode("utf-8")

Hi,

Tôi đang sử dụng các yêu cầu để gửi dữ liệu đến cơ sở dữ liệu Firebase. Dữ liệu có trong tệp JSON được mã hóa UTF-8. Tôi đang gửi dữ liệu đó như sau:

data_to_send = json.dumps(data).encode("utf-8")
request_object = self.requests.put(request_ref, headers=headers, data=data_to_send)

Nhưng điều này được gửi dưới dạng văn bản "Latin-1" bất kể điều gì, bởi vì thư viện máy khách HTTP cơ bản luôn gửi văn bản của cơ thể với mã hóa đó.

        if isinstance(body, str):
            # RFC 2616 Section 3.7.1 says that text default has a
            # default charset of iso-8859-1.
            body = _encode(body, 'body')

Kết quả này trên các ký tự kỳ lạ được hiển thị trên trang web của tôi.

Nếu thay vì: data_to_send = json.dumps(data).encode("utf-8") hoặc data_to_send = json.dumps(data, ensure_ascii=False).encode("utf-8") Tôi làm điều này: data_to_send = json.dumps(data, ensure_ascii=False)
data_to_send = json.dumps(data).encode("utf-8")
or
data_to_send = json.dumps(data, ensure_ascii=False).encode("utf-8")
I do this:
data_to_send = json.dumps(data, ensure_ascii=False)

Sau đó, thư viện máy khách HTTP ném lỗi này:

"client.py", line 1150, in _send_request
    body = _encode(body, 'body')
  File "C:\Users\mribeiro\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 161, in _encode
    (name.title(), data[err.start:err.end], name)) from None
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2030' in position 164: Body ('▒') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.

Vì vậy, làm thế nào tôi phải đăng dữ liệu được mã hóa UTF-8 bằng các yêu cầu?