0

I have some code that i have to convert from Javascript to Python.

In JS side, the code performs HTTP requests using fetch:

let resp = await fetch( url + 'get/token', { method: 'POST', mode: 'cors', body: fd });
let data = await resp.json();
return data.token;

How the fetch() command for javascript can be performed from Python? What is the equivalent command?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
user1584421
  • 3,499
  • 11
  • 46
  • 86

1 Answers1

1

You don't have to use Flask for this. So if you just want to perform a simple Post Request to a given URL just use the Pythons Request Library like so:

import requests

url = 'someurl'
myobj = {'somekey': 'somevalue'} # if you want to send JSON Data

x = requests.post(url, data = myobj)

print(x.text)

EDIT:

As @OneCricketeer mentioned in his comment you could do this also with the urllib Package which is included in the Python 3.

from urllib import request
from urllib.parse import urlencode


req = request.Request('your-url', method="POST")
req.add_header('Content-Type', 'application/json') # you could set any header you want with that method
data = urlencode({"key":"value"})
data = data.encode()

response = request.urlopen(req, data=data)
content = response.read()
Kevin
  • 785
  • 2
  • 10
  • 32