访问上传​​文件的 url

Accessing an uploaded file's url

我的发送和接收数据的应用程序 from/to 我的 phone - 基本上是通过 pushbullet API 的双向通信。

我正在尝试从我的 phone 中获取一个文件,并在上传后对其进行处理(例如,如果它是音频文件,则播放它)。

但是当我在 phone 上上传文件然后在我的计算机上列出推送并获得准确的推送时,文件 URL 受到限制。

我收到以下 XML 错误响应,显示“拒绝访问”消息:

403: Forbidden

我该如何处理?

这是应用程序的代码:


def play_sound(url):
    #open the url and then write the contents into a local file
    open("play.mp3", 'wb').write(urlopen(url))
 
    #playsound through the playsound library
    playsound("play.mp3", False)


pb = pushbullet.Pushbullet(API_KEY, ENCRYPTION_PASSWORD)

pushes = pb.get_pushes()
past_pushes = len(pushes)
while True:
    time.sleep(3)

    # checks for new pushes on the phone and then scans them for commands
    pushes = pb.get_pushes()
    number_pushes = len(pushes) - past_pushes

    if number_pushes != 0:
        past_pushes = (len(pushes) - number_pushes)

        try:
            for i in range(number_pushes):
                push = pushes[i]

                push_body = push.get("body")

                if push_body is not None:
                    play = False

                    if push_body == "play":
                        play = True
                elif play:
                    #only runs if the user has asked to play something 
                    #beforehand

                    play = False
                    url = push.get('file_url')

                    #play sound from url
                    #this is where I get my 403: forbidden error
                    if url is not None and ".mp3" in url:
                        play_sound(url)

        except Exception as e:
            print(e)

来自 docs...

To authenticate for the API, use your access token in a header like Access-Token: <your_access_token_here>.

您使用的 urlopen(url) 没有任何 header 信息,因此请求被拒绝。

所以,试试下面的方法

from urllib.request import Request, urlopen

req = Request('https://dl.pushbulletusercontent.com/...')
req.add_header('Access-Token', '<your token here>')
content = urlopen(req).read()

with open('sound.mp3', 'wb') as f:
  f.write(content)

参考:How do I set headers using python's urllib?