简体   繁体   中英

AioHttp: How can I create a data form for an aiohttp post

This is what the data looks like when I'm using requests and it works fine.

data ={
      "srt": srt,
      "firstname" : firstname,
      "lastname" : lastname,
      "Email" : email,
      "password" : password,
      "promotion" : "true",
      "action" : {"name":"EMAIL_REG_FORM_SUBMIT"},
      "ri" : "NORU",
      "ets" : ets
          }

I'm trying to convert it so that it works with aiohttp and this is what I have. I think I'm getting an error because of line: "action": {"name":"EMAIL_REG_FORM_SUBMIT"},

data = aiohttp.FormData()
data.add_field("srt", srt)
data.add_field("firstname", firstname)
data.add_field("lastname", lastname)
data.add_field("Email", email)
data.add_field("password", password)
data.add_field("promotion", 'true')
data.add_field("action", {"name":"EMAIL_REG_FORM_SUBMIT"})
data.add_field("ri", 'NORU')
data.add_field("ets", ets)

If anyone has any ideas on how to make this work pls leave a comment. Essentially I need an async requests with a session, if you know how to do that pls let me know.

I was able to get a submission of a full dictionary in a field by simply converting it to a JSON string:

data.add_field("action", json.dumps({"name":"EMAIL_REG_FORM_SUBMIT"}))

Depending on the data in the dictionary, you might need to add a serialization class to json.dumps to handle "special" data types that json.dumps default serialization class can't handle or for which you need to serialize to JSON following some special format (for example converting a DateTime with time zone to some special text format the server is expecting)

You can also add files with additional calls to add_field, specifying the name of the file you have in the form field(s) as the name field of your data.add_field() call.

Under the hood, FormData tries to transform all your fields and files in a properly formatted multipart/form-data payload.

(I found out most of this after fighting a whole day with both the aiohttp client docs and the server I was submitting data to that was doing "unsmart" things)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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