Arsenal Fanatic
Arsenal Fanatic

Reputation: 3803

python urllib alternative to requests.put command?

I want to send image data via urllib python 3.6 library. i presently have an implementation of a python 2.7 with the help of requests library.

Id there a way to replace the requests lib with the urllib in this code.

import argparse
import io
import os
import sys
import base64
import requests


def read_file_bytestream(image_path):
    data = open(image_path, 'rb').read()
    return data


if __name__== "__main__":
    data=read_file_bytestream("testimg.png")
    requests.put("http.//0.0.0.0:8080", files={'image': data})

Upvotes: 0

Views: 2597

Answers (1)

mattjvincent
mattjvincent

Reputation: 888

Here is one way, pretty much taken from the docs:

import urllib.request

def read_file_bytestream(image_path):
    data = open(image_path, 'rb').read()
    return data

DATA = read_file_bytestream("file.jpg")
req = urllib.request.Request(url='http://httpbin.org/put', data=DATA, method='PUT')
with urllib.request.urlopen(req) as f:
    pass
print(f.status)
print(f.reason)

Upvotes: 3

Related Questions