I would like to see the execution result of the API in HTML.
So, first I ran the API on localhost and checked if the result could be displayed in HTML in the browser.
As a result, I was told to study Django
, so I'll try it for the time being.
Django Let's take a quick look at Django.
--A full stack framework written in Python. ――You have everything you need. --The template doesn't bring that, and the DB access doesn't bring that. --There are modules to extend, but the basics are just Django.
--ORM --Object Relational Mapping The object relational mapping is excellent. --Low learning cost --Raw HTML, Javascript, and CSS are the basics, but it's a simple web framework to choose first.
Since this is my first development using Django
, I will create a book list as a sample application.
Development will proceed according to the following flow.
Django
and create a project.The execution environment is as follows
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.15.1
BuildVersion: 19B88
$ python --version
Python 3.7.4
Use venv
as a virtual development environment.
I want to use the stable version this time, so specify the version and install it.
$ pip install django==2.1.5
Then create a project. This time, create a project called mybook.
$ django-admin.py startproject mybook
A project is created with the following configuration.
mybook/
manage.py
mybook/
__init__.py
settings.py
urls.py
wsgi.py
Now move to the mybook
directory.
$ cd mybook
Database settings can be made in mybook / settings.py
.
This time, use the default setting SQlite3
.
settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
:
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
When you enter the command to migrate the database, a file called db.sqlite3
is created in the directory directly under the project.
$ python manage.py migrate
At the same time, create a super user.
$ python manage.py createsuperuser
Username (leave blank to use 'hoge'): admin
Email address: [email protected]
Password: hogefuga
Password (again): hogefuga
Superuser created successfully.
On the way, answer the following questions.
--Username: admin --Email address: [email protected] * Appropriate --Password: hogefuga --Password (re-enter): hogefuga
Start the development server with the command python manage.py runserver
and check if the project works.
$ python manage.py runserver
Go to http://127.0.0.1:8000/ with your browser.
Quit the development server with control + c
.
Create an application called cms
under the project.
Create with the following command.
$ python manage.py startapp cms
The following files are created under the directory of the mybook project.
mybook/
cms/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
manage.py
mybook/
:
:
Define the data model you want to define in the database in cms / models.py
.
models.py
from django.db import models
class Book(models.Model):
"""Books"""
name = models.CharField('Book title', max_length=255)
publisher = models.CharField('the publisher', max_length=255, blank=True)
page = models.IntegerField('number of pages', blank=True, default=0)
def __str__(self):
return self.name
Add cms
to the end of INSTALLED_APPS in mybook / settings.py
.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cms', #add to
]
Use the following command to pick up the changes in models.py
and create a migrate file.
$ python manage.py sqlmigrate cms 0001
Use the following command to reflect the migrate file that has not been reflected in the database to the database.
python manage.py migrate cms
At this point, the database is ready.
From here, we will create with Foron. This time, I'll use Bootstrap, a CSS framework. Download it from the following, including the jQuery required by Bootstrap.
Create a directory called mybook / cms / static / cms /
and place the downloaded file as follows.
mybook
└── cms
└── static
└── cms
├── css
│ ├── bootstrap.min.css
│ └── bootstrap.min.css.map
└── js
├── bootstrap.bundle.min.js
├── bootstrap.bundle.min.js.map
└── jquery-3.4.1.min.js
We need a list function, so create it in cms / views.py
.
views.py
from django.shortcuts import render
from django.http import HttpResponse
def book_list(request):
"""List of books"""
books = Book.objects.all().order_by('id')
return render(request,
'cms/book_list.html', #Template to use
{'books': books}) #Data to pass to the template
Then create a URL scheme.
The file cms / urls.py
does not exist, so create a new one.
In this, the URL and the function of the view are linked.
cms/urls.py
from django.urls import path
from cms import views
app_name = 'cms'
urlpatterns = [
#Books
path('book/', views.book_list, name='book_list'), #List
]
Then include cms / urls.py
in mybook / urls.py
for the entire project.
mybook/urls.py
from django.contrib import admin
from django.urls import path, include # ←,add include
urlpatterns = [
path('cms/', include('cms.urls')), #← Add here
path('admin/', admin.site.urls),
]
The final URL looks like this:
http://127.0.0.1:8000/cms/book/
Create a template called book_list.html
for use in the cms application of your mybook project.
First, create a template called base.html
that will be the inheritance source.
mybook/cms/templates/cms/base.html
The contents of base.html
are as follows.
base.html
{% load i18n static %}
<!DOCTYPE html>{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="{% static 'cms/css/bootstrap.min.css' %}">
{% block extra_css %}{% endblock %}
<title>{% block title %}My books{% endblock %}</title>
</head>
<body>
<div class="container">
{% block content %}
{{ content }}
{% endblock %}
</div>
<script src="{% static 'cms/js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'cms/js/bootstrap.bundle.min.js' %}"></script>
{% block extra_js %}{% endblock %}
</body>
</html>
Now, create mybook / cms / templates / cms / book_list.html
by inheriting this base_html
.
book_list.html
{% extends "cms/base.html" %}
{% block title %}List of books{% endblock title %}
{% block content %}
<h4 class="mt-4 border-bottom">List of books</h4>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Book title</th>
<th scope="col">the publisher</th>
<th scope="col">number of pages</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<th scope="row">{{ book.id }}</th>
<td>{{ book.name }}</td>
<td>{{ book.publisher }}</td>
<td>{{ book.page }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
Check it with your browser. Since there is no data, only the header.
http://127.0.0.1:8000/cms/book/
For the time being, I was able to display HTML.
After that, if you can call and execute the API from views.py
, you can achieve the purpose.
I'm new to the Python framework, and I've been able to get it to display without stumbling.
Recommended Posts