python - 在 python 中使用 urllib3 模块而不是请求
问题描述
此代码在 python 2.X 版本中正常工作。我正在尝试在 python 版本 3 中使用类似的代码。问题是我不想使用 requests 模块。我需要使用“urllib3”使其工作。
import requests
import urllib
event = {'url':'http://google.com', 'email':'abc@gmail.com', 'title':'test'}
url = event['url']
if event['email']:
email=event['email']
if event['title']:
title=event['title']
url1 = urllib.parse.unquote(url)
myfile=urllib.request.urlopen(url1)
requests.post("https://api.mailgun.net/v3/xxx.mailgun.org/messages",
auth=("api", "key-xxx"),
files=[("attachment", myfile)
],
data={"from": "Excited User <excited-user@example.com>",
"to": email,
"subject": title,
"text": "Testing some awesomness with attachments!",
"html": myfile})
我在尝试运行此代码时收到 TypeError:
import urllib3
event = {'url':'http://oksoft.blogspot.com', 'email':'abc@gmail.com', 'title':'test'}
url = event['url']
if event['email']:
email=event['email']
if event['title']:
title=event['title']
url1 = urllib.parse.unquote(url)
myfile=urllib.request.urlopen(url1)
http = urllib3.PoolManager()
url = "https://api.mailgun.net/v3/xxx.mailgun.org/messages"
params={"from": "Excited User <excited-user@example.com>",
"to": email,
"subject": title,
"text": "Testing some awesomness with attachments!",
"html": myfile}
http.request(
"POST", url, headers={"Content-Type": "application/json", "api":"key-xxx"}, body= params
)
解决方案
此代码使用 urllib.reqeust 模块。与内联html 内容相比,实际创建文件附件比使用文件内容设置参数要复杂一些。html
import urllib.request
import urllib.error
import urllib.parse
import io
import mimetypes
import uuid
class MultiPartForm:
"""Accumulate the data to be used when posting a form."""
def __init__(self):
self.form_fields = []
self.files = []
# Use a large random byte string to separate
# parts of the MIME data.
self.boundary = uuid.uuid4().hex.encode('utf-8')
return
def get_content_type(self):
return 'multipart/form-data; boundary={}'.format(
self.boundary.decode('utf-8'))
def add_field(self, name, value):
"""Add a simple field to the form data."""
self.form_fields.append((name, value))
def add_file(self, fieldname, filename, fileHandle,
mimetype=None):
"""Add a file to be uploaded."""
body = fileHandle.read()
if mimetype is None:
mimetype = (
mimetypes.guess_type(filename)[0] or
'application/octet-stream'
)
self.files.append((fieldname, filename, mimetype, body))
return
@staticmethod
def _form_data(name):
return ('Content-Disposition: form-data; '
'name="{}"\r\n').format(name).encode('utf-8')
@staticmethod
def _attached_file(name, filename):
return ('Content-Disposition: file; '
'name="{}"; filename="{}"\r\n').format(
name, filename).encode('utf-8')
@staticmethod
def _content_type(ct):
return 'Content-Type: {}\r\n'.format(ct).encode('utf-8')
def __bytes__(self):
"""Return a byte-string representing the form data,
including attached files.
"""
buffer = io.BytesIO()
boundary = b'--' + self.boundary + b'\r\n'
# Add the form fields
for name, value in self.form_fields:
buffer.write(boundary)
buffer.write(self._form_data(name))
buffer.write(b'\r\n')
buffer.write(value.encode('utf-8'))
buffer.write(b'\r\n')
# Add the files to upload
for f_name, filename, f_content_type, body in self.files:
buffer.write(boundary)
buffer.write(self._attached_file(f_name, filename))
buffer.write(self._content_type(f_content_type))
buffer.write(b'\r\n')
buffer.write(body)
buffer.write(b'\r\n')
buffer.write(b'--' + self.boundary + b'--\r\n')
return buffer.getvalue()
event = {'url':'http://oksoft.blogspot.com', 'email':'abc@gmail.com', 'title':'test'}
url = event['url']
if event['email']:
email=event['email']
if event['title']:
title=event['title']
form = MultiPartForm()
form.add_field("from", "Excited User <excited-user@example.com>")
form.add_field("to", email)
form.add_field("subject", title)
form.add_field("text", "Testing some awesomness with attachments!")
with urllib.request.urlopen(url) as f:
form.add_file("attachment", "test.html", f, "text/html")
url = "https://api.mailgun.net/v3/xxx.mailgun.org/messages"
# create basic authorization opener
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='MG API',
uri=url,
user='api',
passwd='xxx-key')
opener = urllib.request.build_opener(auth_handler)
data = bytes(form)
req = urllib.request.Request(url, data=data)
req.add_header('Content-type', form.get_content_type())
req.add_header('Content-length', len(data))
with opener.open(req) as f:
print(f.read().decode('utf-8'))
推荐阅读
- c++ - 计算 Product 小于 K 的所有子序列
- java - 尝试在空对象引用上调用虚拟方法“Context.getSharedPreferences()”
- grep - Linux RegEx Grep 重复字符 n 到 m 次
- mobaxterm - 如何选择要包含在 MobaXterm 的 MultiExec 中的选项卡?
- javascript - 如何将图像尺寸从 javascript 发送到后端(快递)
- java - 两个 Quarkus 服务之间的非阻塞数据流(Vert.x with Mutiny in Java)
- java - 我可以在 JAVA 中使用多个 JButton 更改唯一的 MouseListener 方法吗?
- c# - Xamarin Android:自定义渲染器的自定义键盘出现问题 - 出现在控件下方、按键不可按下等
- postgresql - 将查询作为字符串变量执行并存储在表中
- react-native - 当我使用 useState 更新变量时,模态打开和关闭