Python 如何构造视图以在Django中发送api get请求?
我正在视图中发送get请求,然后使用响应填充我的数据库,我需要确认以下内容: 我应该在视图内部进行api调用吗 这种看法应该是什么 如果我做错了,那么在Django中发送get请求的正确方式是什么Python 如何构造视图以在Django中发送api get请求?,python,django,api,Python,Django,Api,我正在视图中发送get请求,然后使用响应填充我的数据库,我需要确认以下内容: 我应该在视图内部进行api调用吗 这种看法应该是什么 如果我做错了,那么在Django中发送get请求的正确方式是什么 my_app/views.py class api(APIView): template_name = 'payment/api.html' def get(self, request): #I SEND THE GET REQUEST HERE config = conf
my_app/views.py
class api(APIView):
template_name = 'payment/api.html'
def get(self, request):
#I SEND THE GET REQUEST HERE
config = configparser.ConfigParser()
config.read('config.ini')
r = requests.get(config['DEFAULT']['api'])
response = r.json()
#HERE I FILTER THE RESPONSE AND PUT IN A DB
for item in response:
if 'Covered Recipient Physician' in item.values():
person, _ = models.Person.objects.get_or_create(
profile_id = int(item['physician_profile_id']),
first_name = item['physician_first_name'].lower(),
last_name = item['physician_last_name'].lower()
)
address, _ = models.Address.objects.get_or_create(
business_street =
item['recipient_primary_business_street_address_line1'].lower(),
city = item['recipient_city'].lower(),
state = item['recipient_state'].lower(),
country = item['recipient_country'].lower()
)
business, _ = models.Business.objects.get_or_create(
business = item['submitting_applicable_manufacturer_or_applicable_gpo_name'].lower(),
)
business_address_link = models.Business_address_link.objects.create(
business = business,
address = address
)
business_address_link.save()
payment = models.Payment.objects.create(
record_id = int(item['record_id']),
amount = float(item['total_amount_of_payment_usdollars']),
date = item['date_of_payment'],
number_of_payments = int(item['number_of_payments_included_in_total_amount']),
payment_form = item['form_of_payment_or_transfer_of_value'],
nature_of_payment = item['nature_of_payment_or_transfer_of_value']
)
payment.save()
person_payment_information = models.Person_payment_information.objects.create(
person = person,
business_address_link = business_address_link,
payment = payment
)
person_payment_information.save()
尝试将此函数用于GET请求-
@require_http_methods(['GET'])
def get_persons(request):
try:
data = list(Message.objects.all.values())
return render(request=request, template_name='template.html', context={"data": data})
except Exception as e:
return render(request=request, template_name='template.html', context={"error": e})
收到响应并将其发送到template.html后,可以按任何方式显示它
例如,如果要向数据库添加信息,最好使用POST请求-
@require_http_methods(['POST'])
def add_person(request):
try:
data = json.loads(request.body)
new_person = Person(**data)
new_person.save()
return render(request=request, template_name='template.html', context={"data": data})
except Exception as e:
return render(request=request, template_name='template.html', context={"error": e})
谢谢,但是我如何在get函数中发送get请求,然后在post函数中将响应发布到db?你说的“将响应发布到db”是什么意思?使用Django,一旦您使用POST请求创建模型的新实例,它就会自动将其添加到内置数据库中。