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.
This time [try running python in Django environment made with pipenv] In the environment created by (https://qiita.com/Ajyarimochi/items/0964d314c8bd968fcc80), create a simple web API using Django's functions.
Mac OS 10.15 VSCode 1.39.2 pipenv 2018.11.26 Python 3.7.4 Django 2.2.6
When a coupon code is requested, the content of the coupon associated with the coupon code is responded by HTTP.
Enter the pipenv virtual environment with the pipenv shell command and change to the directory where manage.py is located.
Create a django app named coupon.
If you open the folder with VS Code, you will have a coupon app.
As shown below, I created a function called coupon and hard-coded the contents of the coupon. Depending on the code of the coupon sent by the request variable (coupon_code), the coupon will be sorted by the if statement. The response is returned in Http using Django's HttpResponse
method.
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def coupon(request):
if 'coupon_code' in request.GET:
coupon_code = request.GET['coupon_code']
if coupon_code == '0001':
result = '1000 yen discount coupon!'
elif coupon_code == '0002':
result = '10%Discount coupon!'
else:
result = 'Error:Not found coupon code!'
return HttpResponse(result)
Next, set the path. First, create a new ʻurls.py` under the coupon app.
coupon/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.coupon, name='coupon'),
]
Next, edit urls.py under the project. Added path ('coupon /', include ('coupon.urls'))
to ʻurl patterns`.
ami_coupon_api/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include('hello.urls')),
path('coupon/', include('coupon.urls'))
]
Save your changes and start django's web server.
$ python manage.py runserver
Access the following URL with a browser.
http://127.0.0.1:8000/coupon/?coupon_code=0001
Confirm that the correct response changes.
Check the pattern for entering other parameters
Request a coupon with coupon code 0002
http://127.0.0.1:8000/coupon/?coupon_code=0002
If you specify a coupon code that does not exist
http://127.0.0.1:8000/coupon/?coupon_code=0003
With the above, we have implemented a super-simple web API. From here, we will modify it as follows to make it a web API that can withstand practical use.
Next time, I'll try using Django's template feature for learning [https://qiita.com/Ajyarimochi/items/9d64b13321f0779fc986)
Recommended Posts