In traditional Web Application development , Most programmers use the browser as the dividing line between the front end and the back end . The part of the browser that presents the page to the user is called the front end , And will run on the server , All the code that provides the business logic and data preparation for the front end is collectively referred to as the back end . The so-called development of front and rear end separation , That is, the front and rear end engineers agree on the data interaction interface , Develop and test in parallel , The backend only provides data , Not responsible for rendering data to the page , Front end by HTTP Request to get the data and be responsible for rendering the data to the page , This job is left to the browser JavaScript Code to complete .
There are many benefits of using front and back-end separate development , Let's briefly talk about these benefits :
Next, we will rewrite the previous voting application by separating the front end from the back end .
Just said , In the development mode of front and back end separation , The back end needs to provide data interface for the front end , These interfaces usually return JSON Formatted data . stay Django In the project , We can first process the object into a dictionary , Then we can use Django Packaged JsonResponse
Back to browser JSON Formatted data , The specific methods are as follows .
def show_subjects(request):
queryset = Subject.objects.all()
subjects = []
for subject in queryset:
subjects.append({
'no': subject.no,
'name': subject.name,
'intro': subject.intro,
'isHot': subject.is_hot
})
return JsonResponse(subjects, safe=False)
In the above code , We loop through the query discipline to get QuerySet
object , Process the data of each subject into a dictionary , Save the dictionary in a file named subjects
In the list container of , The use of JsonResponse
Complete the serialization of the list , Back to browser JSON Formatted data . because JsonResponse
Serialize a list instead of a dictionary , So you need to specify safe
The value of the parameter is False
To complete the right subjects
Serialization , Otherwise, it will occur TypeError
abnormal .
Maybe you have found out , It's troublesome to write your own code to turn an object into a dictionary , If the object has many attributes and some attributes are associated with a more complex object , Things will get worse . To do this, we can use a named bpmappers To simplify the operation of converting objects into dictionaries , The third-party library itself also provides access to Django Framework support .
Install tripartite Library bpmappers.
pip install bpmappers
Write mapper ( Implement object to dictionary conversion ).
from bpmappers.djangomodel import ModelMapper
from poll2.models import Subject
class SubjectMapper(ModelMapper):
class Meta:
model = Subject
Modify view functions .
def show_subjects(request):
queryset = Subject.objects.all()
subjects = []
for subject in queryset:
subjects.append(SubjectMapper(subject).as_dict())
return JsonResponse(subjects, safe=False)
To configure URL mapping , Then access the interface , You can get the following JSON Format data .
[
{
"no": 101,
"name": "Python The whole stack + Artificial intelligence ",
"intro": "Python Is a computer programming language . Is an object-oriented dynamic type language , Originally designed to write automated scripts (shell), With the continuous update of the version and the addition of new language features , More and more are used for independent 、 Development of large projects .",
"create_date": "2017-08-01",
"is_hot": true
},
// The following is omitted here
]
If you don't want to be in JSON The data shows the establishment time of the discipline , We can exclude... From the mapper create_date
attribute ; If you want to name the key corresponding to whether it is a popular subject as isHot
( The default name is is_hot
), You can also do this by modifying the mapper . The specific methods are as follows :
from bpmappers import RawField
from bpmappers.djangomodel import ModelMapper
from poll2.models import Subject
class SubjectMapper(ModelMapper):
isHot = RawField('is_hot')
class Meta:
model = Subject
exclude = ('create_date', 'is_hot')
View the information returned by the discipline interface again JSON data .
[
{
"no": 101,
"name": "Python The whole stack + Artificial intelligence ",
"intro": "Python Is a computer programming language . Is an object-oriented dynamic type language , Originally designed to write automated scripts (shell), With the continuous update of the version and the addition of new language features , More and more are used for independent 、 Development of large projects .",
"isHot": true
},
// The following is omitted here
]
About bpmappers Detailed use guide , Please refer to its Official documents , This official document is written in Japanese , You can use the translation function of the browser to translate it into a language you are familiar with .
About Vue.js Knowledge , We are the first 21 To the first day 30 It has been introduced in the content of days , We won't go into details here . If you want to fully understand and learn Vue.js, It is recommended to read its The official tutorial Or in YouTube On the search Vue.js New to (Crash Course) To study .
Rewrite subjects.html page , Use Vue.js To render a page .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Discipline </title>
</head>
<body>
<h1> All subjects </h1>
<hr>
<div id="app">
<div v-for="subject in subjects">
<h3>
<a :href="getTeachersHref(subject.no)">{
{ subject.name }}</a>
<img v-if="subject.isHot" src="/static/images/hot.png" width="32">
</h3>
<p>{
{ subject.intro }}</p>
</div>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script> const app = new Vue({
el: '#app', data: {
subjects: [] }, created() {
fetch('/subjects/') .then(resp => resp.json()) .then(json => this.subjects = json) }, methods: {
getTeachersHref(sno) {
return `/static/teachers.html/?sno=${
sno}` } } }) </script>
</body>
</html>
The development of front-end and back-end separation needs to deploy the front-end page as a static resource , When the project is actually launched , We will treat the whole Web Application for dynamic and static separation , Static resources are generated through Nginx or Apache Server deployment , Generating dynamic content Python Program deployment at uWSGI perhaps Gunicorn Server , Requests for dynamic content are made by Nginx or Apache Route to uWSGI or Gunicorn Server .
In the development stage , We usually use them Django Built in test server , If you want to try to separate the front and rear ends , You can first put the static page in the directory you created earlier to put the static resources , We can refer to Project complete code .