简体   繁体   English

如何使用 python 打开照片以用于 API 发布请求

[英]How to open a photo with python for use in an API post request

I am trying to open a test photo in python to upload the photo using the imgur API.我正在尝试在 python 中打开一张测试照片,以使用 imgur API 上传照片。 I have found guides online with how to do this using javascript but am trying to learn python so help in that language would be appreciated.我在网上找到了有关如何使用 javascript 执行此操作的指南,但我正在尝试学习 python,因此将不胜感激。

The error i'm getting is我得到的错误是

FileNotFoundError: [Errno 2] No such file or directory: '..\\media\\test.jpg'

I suspect that the cause of the error is with my pathing to the test.jpg file but I can't seem to figure out the right way to get to that file.我怀疑错误的原因是我指向test.jpg文件的路径,但我似乎无法找出获取该文件的正确方法。 I have uploaded my sample code below and it is also in the github post linked HERE .我已经在下面上传了我的示例代码,它也在 github 帖子中链接这里

Different attempts i have made to call the file include the below:我为调用该文件所做的不同尝试包括以下内容:

  • 'image': b64encode(open(r'..\media\test.jpg', 'rb').read())
  • 'image': open(r'..\media\test.jpg', 'rb').read()
  • 'image': open('..\media\test.jpg', 'rb').read()
  • 'image': open('..\\media\\test.jpg', 'rb').read()
  • 'image': open(r'..\\media\\test.jpg', 'rb').read()
  • 'image': open('../\media/\test.jpg', 'rb').read()

I have also tried to put the test.jpg photo into the same folder as the python script but unfortunately that did not work either.我还尝试将test.jpg照片放入与 python 脚本相同的文件夹中,但不幸的是这也不起作用。

Code I am using:我正在使用的代码:

from base64 import b64encode
import json
import requests
import config



client_id = config.IMGUR_CLIENT_ID
# headers = ['Authorization'] = f'Client-ID {client_id}'
headers = {"Authorization": f'Client-ID {client_id}'}
api_key = config.IMGUR_CLIENT_SECRET
url = "https://api.imgur.com/3/upload.json"


# print(r'..\media\test.jpg')

j1 = requests.post(
    url, 
    headers = headers,
    data = {
        'key': api_key, 
        #'image': b64encode(open(r'..\media\test.jpg', 'rb').read()),
        'image': open(r'..\media\test.jpg', 'rb').read(),
        'type': 'base64',
        'name': 'test.jpg',
        'title': 'Picture no. 1'
    }
)


Picture of the file structure:文件结构图:

文件结构

Couldn't figure this out so i ended up using the below code to save to a folder in my C drive, i don't need to store the variable anywhere since the file can be overwritten every time the code runs.无法弄清楚这一点,所以我最终使用下面的代码保存到我的 C 驱动器中的文件夹中,我不需要将变量存储在任何地方,因为每次代码运行时都可以覆盖文件。

file_location = urllib.request.urlretrieve(url, r'C:\temp\test.jpg')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM