程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python full stack 100 day learning notes] Introduction to day48 front and back end separation development

編輯:Python

Introduction to front and rear end separation development

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 :

  1. Improve development efficiency . After the front and rear ends are separated , It can realize the decoupling of front and back-end code , As long as the front and back end communicate and agree on the interface required by the application and interface parameters , You can start parallel development , You don't have to wait for the other party's development work to end . under these circumstances , Both front and rear end engineers can focus only on their own development work , Help build a better team . besides , In the development mode of front and back end separation , Even if the requirements change , As long as the interface and data format remain unchanged , Back end developers don't need to change the code , Just change the front end .
  2. Enhance code maintainability . After the front and rear ends are separated , The application code is no longer a mix of front and back ends , Invocation dependencies are only available at run time , In this way, the work of maintaining the code will be much easier and happier , No more pulling a hair and moving the whole body . When your code becomes concise and tidy , The readability and maintainability of the code will be qualitatively improved .
  3. Support multi terminal and service architecture . After the front and rear ends are separated , The same set of data interfaces can provide services for different terminals , More conducive to building multi terminal applications ; Besides , Because the interfaces provided by the back end can be connected through HTTP(S) To call , Help to build a service-oriented architecture ( Including microservices ).

Next, we will rewrite the previous voting application by separating the front end from the back end .

return JSON Formatted data

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 .

Use Vue.js Render the page

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved