Search code examples
pythonjsonflaskpython-requestsflask-admin

How to allow Flask-Admin to accept JSON for record creation


I would like to know if it is possible to use Flask-Admin with the python requests library to create new records in the database from a script. An example would be as such:

import requests

new_userdata = {'username': 'testuser', 'confirmed_at': None, 'login_count': 0, 'last_login_at': None, 'active': False, 'password': 'password', 'current_login_ip': None, 'last_login_ip': None, 'current_login_at': None, 'email': 'test@test.com'}

url = "http://localhost:5000/admin/user/new/"

r = requests.post(url, data=new_userdata, headers={"content-type":"application/json")

I tried this already, and it does successfully create a new user record in the database, but all the fields in the record are null. Is there a configuration setting that needs to be changed to allow this sort of behavior? I wasn't able to find in the Flask-Admin documentation that discussed this kind of usage.


Solution

  • You're sending form data, but you're also saying that the content type is JSON. If you were actually sending JSON data, you would either need to call json.dumps, or you would pass json= instead of data=. Just remove the header and send form data, as it's obviously sufficient to handle the data you're sending and Flask-Admin recognizes it.