首先,我正在为 WordPress REST API 编写一个异步包装器。我有一个托管在 Bluehost 上的 Wordpress 网站。我正在使用端点进行媒体(图像)上传。我已经成功上传了一张图片,但我想做两处更改。第二个更改是我真正想要的,但出于好奇,我也想知道如何实现更改 1。我将首先提供代码,然后提供一些细节。
工作代码
async def upload_local_pic2(self, local_url, date, title):
url = f'{self.base_url}/wp-json/wp/v2/media'
with aiohttp.MultipartWriter() as mpwriter:
json = {'title': title, 'status':'publish'}
mpwriter.append_json(json)
with open(local_url, 'rb') as f:
print(f)
payload = mpwriter.append(f)
async with self.session.post(url, data=payload) as response:
x = await response.read()
print(x)
变化 1
第一个更改是使用 aiofiles.open() 上传,而不是只使用 open(),因为我希望处理大量文件。以下代码不起作用。
async def upload_local_pic(self, local_url, date, title):
url = f'{self.base_url}/wp-json/wp/v2/media'
with aiohttp.MultipartWriter() as mpwriter:
json = {'title': title, 'status':'publish'}
mpwriter.append_json(json)
async with aiofiles.open(local_url, 'rb') as f:
print(f)
payload = mpwriter.append(f)
async with self.session.post(url, data=payload) as response:
x = await response.read()
print(x)
变化 2
我的另一个变化是我想要另一个功能,可以直接将文件上传到 WordPress 服务器,而无需在本地下载它们。因此,我不想获取本地图片,而是想在线传递图片的 url。以下代码也不起作用。
async def upload_pic(self, image_url, date, title):
url = f'{self.base_url}/wp-json/wp/v2/media'
with aiohttp.MultipartWriter() as mpwriter:
json = {'title':title, 'status':'publish'}
mpwriter.append_json(json)
async with self.session.get(image_url) as image_response:
image_content = image_response.content
print(image_content)
payload = mpwriter.append(image_content)
async with self.session.post(url, data = payload) as response:
x = await response.read()
print(x)
详细信息/调试
我试图弄清楚为什么每个都行不通。我认为关键是调用print(image_content)
并print(f)
显示我输入的确切内容mpwriter.append
在我只使用标准 Pythonopen()
函数的示例中,我显然是在传递<_io.BufferedReader name='/redactedfilepath/index.jpeg'>
在使用 aiofile 的更改 1 示例中,我传入<aiofiles.threadpool.binary.AsyncBufferedReader object at 0x7fb803122250>
Wordpress 将返回此 html:
b'<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>'
最后,在更改 2 中,我尝试将 get 请求传递给 url 给我的内容
<StreamReader 292 bytes>
。WordPress 返回的响应与上面的 Mod Security 相同。
知道如何使这些示例起作用吗?似乎它们都是某种类型的 io 阅读器,但我猜底层 aiohttp 代码对它们的处理方式不同。
这也无关紧要,但这是我传递给更改 2 示例的 url。