[英]How to insert data into django app database using a web API
On a server, I have a Django app with a database. 在服务器上,我有一个带数据库的Django应用。 At the client, I am writing a Python script to send data through https to the server and have the server insert that data into the database.
在客户端,我正在编写一个Python脚本,以通过https将数据发送到服务器,并让服务器将这些数据插入数据库中。
How should I approach this problem? 我应该如何解决这个问题? I am in control of both the server and the client.
我可以控制服务器和客户端。 The reason for wanting to do this is to have an API to insert data into the database.
想要这样做的原因是拥有一个将数据插入数据库的API。
You can send data from the Python Script to the backend. 您可以将数据从Python脚本发送到后端。 You will need to have in place an API defined in Django, of course.
当然,您将需要在Django中定义一个API。 But assuming you already have it you can simply use the awesome requests library to send the data from the Script:
但是,假设您已经拥有了它,则可以简单地使用很棒的请求库来从脚本发送数据:
>>> r = requests.get('http://localhost:8000/v1/api/resource?param1=12¶m2=blabla')
Or using POST: 或使用POST:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post('http://localhost:8000/v1/api/resource', data=payload)
And the Backend will receive it (If you are using Django you will need to process it in the View, and most probably use the ORM to store the value). 后端将接收它(如果您使用的是Django,则需要在View中对其进行处理,并且很可能使用ORM来存储值)。 If by any chance you don't receive the value in the View, it means that the APIs defined in the
urls.py
file are probably not configured correctly. 如果您没有在View中收到该值,则意味着
urls.py
文件中定义的API可能未正确配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.