This article walks you through the steps of a beginner developing a coupon distribution service for the iPhone with a RESTful API and swift. It is a very detour implementation because it was implemented while examining the technical elements one by one.
Modify the code created in the previous Try using Django's template function so that it responds in JSON format. There is a convenient framework called Django Rest Framework, but first I will write it without using Django Rest Framework etc. for the purpose of understanding the mechanism.
Introduction to Python Django (6)
Mac OS 10.15 VSCode 1.39.2 pipenv 2018.11.26 Python 3.7.4 Django 2.2.6
Import the json module to convert the data to json format. Add ʻimport json` to your code.
Use json.dumps
to add a program that takes a structure as input and creates a json format string. The code that creates the structure uses the params = {}
part of the original code as it is.
Add code to create a json format string. We are passing the structure data params
as an argument.
json_str = json.dumps(params, ensure_ascii=False, indent=2)
The return value is simply a Json-formatted string with the HttpResponse
method.
return HttpResponse(json_str)
The modified views.py
is here.
views.py
from django.shortcuts import render
from django.http import HttpResponse
import json #Added
def coupon(request):
if 'coupon_code' in request.GET:
coupon_code = request.GET['coupon_code']
if coupon_code == '0001':
benefit = '1000 yen discount coupon!'
deadline = '2019/10/31'
message = ''
elif coupon_code == '0002':
benefit = '10%Discount coupon!'
deadline = '2019/11/30'
message = ''
else:
benefit = 'NA'
deadline = 'NA'
message = 'No coupons available'
params = {
'coupon_code':coupon_code,
'coupon_benefits':benefit,
'coupon_deadline':deadline,
'message':message,
}
#Generate json format string
json_str = json.dumps(params, ensure_ascii=False, indent=2)
return HttpResponse(json_str)
Save the code and start django's server.
If you access http://127.0.0.1:8000/coupon/?coupon_code=0001
with the curl command from the terminal, you can get the value with json.
Next, when I accessed http://127.0.0.1:8000/coupon/?coupon_code=0001
with a browser, the data in json format was displayed.
that's all.
Next time, Implementation on the application side that responds to coupon information (swift)
Recommended Posts