我正在寻找从我的网络应用程序开发Django REST API
,我想尝试通过API创建对象。主要是如果我的流程得到很好的实施。
我正在使用python文件来制作它。
这是我的档案:
import requests
url = 'http://localhost:8000/Api/identification/create/'
data = {
"Etat": "Vivant",
"Civilite": "Monsieur",
"Nom": "creation",
"Prenom": "via-api",
"Sexe": "Masculin",
"Statut": "Célibataire",
"DateNaissance": "1991-11-23",
"VilleNaissance": "STRASBOURG",
"PaysNaissance": "FR",
"Nationalite1": "FRANCAISE",
"Nationalite2": "",
"Profession": "Journaliste",
"Adresse": "12, rue des fleurs",
"Ville": "STRASBOURG",
"Zip": 67000,
"Pays": "FR",
"Mail": "",
"Telephone": "",
"Image": "http://localhost:8000/media/pictures/HH_Hh_19212-00001-979812-2_ShUDIk8.jpg",
"CarteIdentite": "http://localhost:8000/media/Carte_Identite/carte_ID_lzpOI41_WOnC9WH.gif"
}
response = requests.post(url, data=data)
print (response.text)
如果我必须使用post
或put
,我会感到困惑,但无论如何,我没有克服创建我的对象。如果我直接通过API进行处理,它可以工作,但不能使用pythonic文件。
有什么想法吗?
编辑:
例如,它适用于这些文件:
#API_list.py
import requests
url = 'http://localhost:8000/Api/Identification/'
response = requests.get(url)
print (response.text)
和
#API_details.py
import requests
url = 'http://localhost:8000/Api/Identification/26/'
response = requests.get(url)
print (response.text)
和
#API_edit.py
import requests
url = 'http://localhost:8000/api/Identity/26/edit/'
data = {
"Ville": "STRASBOURG",
"Zip": 67000,
"Pays": "FR",
"Adresse": "12, rue de la mésange",
"Telephone": "0388603938",
"Mail": "ceciestuntest@datasystems.fr",
}
response = requests.put(url, data=data)
print (response.text)
答案 0 :(得分:1)
您可能必须使用post来创建新对象,因此您的代码看起来很好。
发布的数据可能有问题解释了问题。
我认为您应该print(response)
获取状态代码。这将有助于理解。另请查看您的服务器日志,这可能会告诉您哪里出了问题。
也许你的网址也有问题。如果您使用的是“Django-rest-framework”视图集,则创建的网址可能类似于http://localhost:8000/Api/identification/
答案 1 :(得分:0)
我找到了解决方案,感谢@luc回答:
import requests
url = 'http://localhost:8000/Api/Identification/create/'
filename1 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/pictures/photo.jpg'
filename2 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/Carte_Identite/carte_ID.gif'
files = {'Image' : open(filename1,'rb'), 'CarteIdentite': open(filename2,'rb')}
data = {
"Etat": "Vivant",
"Civilite": "Monsieur",
"Nom": "creation",
"Prenom": "via-api",
"Sexe": "Masculin",
"Statut": "Célibataire",
"DateNaissance": "1991-11-23",
"VilleNaissance": "STRASBOURG",
"PaysNaissance": "FR",
"Nationalite1": "FRANCAISE",
"Nationalite2": "",
"Profession": "JJJ",
"Adresse": "12, rue des fleurs",
"Ville": "STRASBOURG",
"Zip": 67000,
"Pays": "FR",
"Mail": "",
"Telephone": ""
}
response = requests.post(url, files=files, data=data)
print(response.text)