Preface
This project is designed with three-stage separation
Reception
The foreground page built by materialize framework and the interface written by django used by the backend
Backstage
Use the interface built by Amazon UI template to manage the content of each part
Project environment
python3.7.2 django2.2.9 vue axios jQuery materialize mysql
Abstract
This design adopts the design mode of front-end and back-end separation. The front-end uses the axios of vue to send ajax requests to call the back-end interface to display the page. The back-end uses the django framework in Python to access the database and return json data. django is a complete open source web open source framework, which can be used to quickly build the website you want. In this design, the background management template is implemented in the style of amazeUI page. The open-source mysql database is used in the database part. Because django is very convenient to operate the database, we only need to care about the design of the models class in the framework, only need to care about the view logic, and the background management system can realize the basic function of adding, deleting, and querying.
Keywords: Python;Vue;Django;ajax;Mysql;
1. Introduction to basic environment
1.1 Python introduction.
Python is a cross platform computer programming language. It is an object-oriented dynamic type language, which was originally designed to write automatic scripts (shells). With the continuous update of versions and the addition of new language functions, it is increasingly used in the development of independent and large-scale projects. Python's design philosophy is "elegant", "clear", "simple". As a result, the idea that "there are always many ways to do the same thing" in Perl is often intolerable to Python developers. The philosophy of Python developers is "to do one thing in one way, preferably only one.". When designing Python language, if faced with multiple choices, python developers will generally refuse fancy syntax, and choose clear syntax with little or no ambiguity. Because of this difference in design concept, python source code is generally considered to have better readability than Perl, and can support large-scale software development. These guidelines are called Python maxims. Run import this in the Python interpreter to get a complete list. Python is a completely object-oriented language. Functions, modules, numbers, strings are objects. And fully support inheritance, overload, derivation, multi inheritance, which is beneficial to enhance the reusability of source code.
1.2 Python features
1. Easy to learn
Python has relatively few keywords, simple structure and easier to learn.
2. Easy to read
Python code is more clearly defined.
3. Easy to maintain
Python's success is that its source code is fairly easy to maintain.
4. An extensive standard library
One of the biggest advantages of Python is its rich libraries, cross platform and good compatibility.
5. Interactive mode
You can input the execution code from the terminal and get the result of the language, interactive testing and debugging code snippets.
6. portable
Based on its open source nature, Python has been ported (that is, made to work) to many platforms.
7. extensible
If you need a fast running key code, or you want to write some algorithms that do not want to be open, you can use C or C++ to complete that part of the program and then call it from your Python program.
8. database
Python provides interfaces to all major commercial databases.
9.GUI programming
Python support GUI can be created and ported to many system calls.
10. embeddable
You can embed Python into C/C + + programs to give users of your programs the ability to "script.".
1.3 introduction to Django
Django is an advanced Python Network Framework, which can quickly develop secure and maintainable websites. Built by experienced developers, Django handles the hassle of web development, so you can focus on writing applications without redevelopment. It's free and open source, with a thriving community, rich documentation, and many free and paid solutions.
1.3.1 completeness
Django adheres to the concept of "complete function", providing almost all functions that developers may want to "use out of the box". Because everything you need is part of a product, they all come together seamlessly, follow consistent design principles, and have extensive and up-to-date documentation
1.3.2 generality
Django can (and has) been used to build almost any type of website - from content management systems and wikis to social networks and news sites. It can work with any client framework and can provide content in almost any format (including HTML,Rss source, JSON,XML, etc.). The website you are reading is based on Django.
Internally, although it provides a choice for almost all the functions that may be required (such as several popular databases, template engines, etc.), it can also be extended to use other components if necessary.
1.3.3 safety
Django helps developers avoid many common security errors by providing a framework designed to "do the right thing" to automatically protect websites. For example, Django provides a secure way to manage user accounts and passwords, avoiding common errors, such as the vulnerable practice of putting session in a cookie (instead, the cookie contains only one key, and the actual data is stored in the database) or directly storing passwords instead of password hashes.
1.3.4 expandable
Django uses a component-based "no share" Architecture (each part of the architecture is independent of other architectures, so it can be replaced or changed as needed). A clear separation between the parts means that it can extend services by adding hardware at any level: cache server, database server or application server. Some of the busiest sites have successfully scaled Django to meet their needs (for example, Instagram and Disqus, to name just two, can be added on their own).
1.3.5 maintainability
Django code is written in accordance with design principles and patterns, encouraging the creation of maintainable and reusable code. In particular, it uses the don't repeat yourself (DRY) principle, so there is no unnecessary repetition, reducing the number of code. Django also groups related functions into reusable "applications" and groups related code or modules (model view controller (MVC) patterns) at a lower level
1.3.6 flexibility
Django is written in Python and runs on many platforms. This means that you are not limited to task specific server platforms and can run applications on many kinds of Linux,Windows, and Mac OsX. In addition, Django is well received by many web hosting providers, who often provide specific infrastructure and documentation to host Django websites.
1.4 MySQL introduction
MySQL is a relational database management system, which is developed by MySQL AB company in Sweden and currently belongs to Oracle company. The SQL language used by MySQL is the most commonly used standardized language for accessing databases. Because of its small size, fast speed, low total cost of ownership and open source code, MySQL is widely used in the development of small and medium-sized websites. Because of the excellent performance of its community version, it can form a good development environment with PHP and Apache server.
2. Demand analysis
The construction of the station consists of two major systems: the foreground function system and the background management system, which are implemented by personnel with different abilities. The foreground function system belongs to the UI design class, and the background management system belongs to the program class. Therefore, the background management system design is selected in this design. Because this design is the background management system, the main function is to add, delete, modify and check the front display page. The main function of this website is to display and publicize information. It is divided into four pages: homepage, course page, teaching characteristic page and student style page. The main functions are as follows:
Figure 2.1 demand analysis of XDH official website
2.1 home page
The homepage is mainly divided into the following parts: (1) Rotation chart (2) Introduction to the brotherhood (3) Difference between fraternity and traditional employment class (4) Faculty (5) Good news for employment (6) Subject introduction
2.2 Course Introduction
(1) Training course, specific subject introduction (2) Introduction to specific disciplines and levels of fraternity (3) What problems did the brotherhood solve (4) Focus on the differences between fraternity curriculum system and traditional training system (5) The bitterness of learning VS the bitterness of life
2.3 teaching characteristics
(1) School running philosophy - programmers with real delivery ability (2) Project driven learning - there are exercises in every stage (3) Guidance of Enterprise Project Manager (4) Real enterprise level business project full development (5) Learning experience sharing (6) Corporate culture training (training healthy programmers)
2.4 student style
(1) Student interview video (2) Student's speech (3) Personal blog (4) League building activities (5) Our work
3. Design of Django model class
Model design is the core part of the whole project, which directly determines the subsequent feasibility of the project. Here we are divided into two app s for design, namely api and bgapi, one as the front-end interface and the other as the back-end management interface.
3.1 import required modules
from django.db import models from django.utils import timezone
3.2 all rotation charts
class Banner(models.Model): img = models.TextField() page = models.CharField(max_length=20) link = models.CharField(max_length=100) is_del = models.IntegerField(default=0) join_date = models.DateTimeField(default=timezone.now)
3.3 work information sheet
class JobInfo(models.Model): major = models.CharField(max_length=50,default="") # Major major major, major (University) school = models.CharField(max_length=50) name = models.CharField(max_length=20) title = models.CharField(max_length=50) img = models.CharField(max_length=200) salary = models.CharField(max_length=20) date = models.DateField() is_del = models.IntegerField(default=0) join_date = models.DateTimeField(default=timezone.now)
3.4 student's speech
class StudentSay(models.Model): img = models.CharField(max_length=50) # Avatar means Avatar name = models.CharField(max_length=20) title = models.CharField(max_length=255) content = models.TextField() is_del = models.IntegerField(default=0) join_date = models.DateTimeField(default=timezone.now)
3.5 contents of technical community
class Community(models.Model): subject = models.CharField(max_length=50) type = models.CharField(max_length=50) content = models.TextField() link = models.TextField() is_del = models.IntegerField(default=0)
3.6 school running characteristics
class Feature(models.Model): img = models.CharField(max_length=250) title = models.CharField(max_length=250) type = models.CharField(max_length=250) content = models.TextField() is_del = models.IntegerField(default=0) join_date = models.DateTimeField(default=timezone.now)
3.7 course content
class Source(models.Model): text = models.CharField(max_length=150) link = models.CharField(max_length=250) is_del = models.IntegerField(default=0) join_date = models.DateTimeField(default=timezone.now)
3.8 personal blog
class Blog(models.Model): name = models.CharField(max_length=20) link = models.CharField(max_length=100) img = models.CharField(max_length=255) title = models.CharField(max_length=255) description = models.TextField() is_del = models.IntegerField(default=0) join_date = models.DateTimeField(default=timezone.now)
3.9 for logging in token table
class Token(models.Model): token_data = models.CharField(max_length=250) token_key = models.CharField(max_length=250) change_time = models.DateTimeField('Last modified date',auto_now=True)
4. View view function
The view function is the core of this project, which is mainly responsible for receiving the request from the front-end ajax, carrying out the preliminary processing, then going to the database for the operation of adding, deleting, modifying and querying, and returning the JSON format data to the requester. Refer to Appendix II for specific codes
5. Interface documents
After the front and back platforms are separated, the communication between their two ends is realized by calling the background interface from the front platform, so a clear interface document will increase the efficiency of project development. The interface document of this project is shown in the appendix, which includes the interface name, interface url, request method and request parameters.
6. Deploy Online
6.1 domain name
Before the project goes online, a domain name needs to be purchased and resolved. Before domain name resolution, the website needs to be filed first. Only after filing can the domain name be bound to the corresponding server
6.2 server
Alibaba cloud server is used in the background of the project, which uses pagoda tools to connect remote servers and manage servers and databases. Pagoda Linux panel is a server management software to improve operation and maintenance efficiency, supporting more than 100 server management functions such as one click LAMP/LNMP / cluster / monitoring / website / FTP / database / JAVA. There are 20 professional teams for R & D and maintenance. After more than 200 versions of iterations, it has full functions, few errors and enough security, and has been approved by millions of users around the world for installation.
6.3 database
mysql 5.7 is used as the database of this project. Because mysql is open-source and free, plus the control of pagoda tool, it is very convenient to deploy the database.
7. Project summary
The project is designed in a way of front-end and back-end separation, which can separate and reduce the coupling between various project parts. On the one hand, it is conducive to assign different parts of the project to developers who are good at different fields for development, on the other hand, it can increase the maintainability of later projects. The whole project takes a week. Although there are many loopholes in it, it still gains a lot after the completion of the project, which can add some experience and project experience for future study and work. Reference [1] Django project case study (2nd Edition) by Antonio Miller, Tsinghua University Press [2] Python web development Author: Dong Weiming press: Electronic Industry Press [3] MySQL 5.7 from introduction to mastery (video teaching edition) (2nd Edition) Zhang factory Tsinghua University Press [4] Python Django web typical module development practice Author: Kou Xuesong press: Mechanical Industry Press
appendix
Appendix I interface documents
Background interface name interface url request method request parameter Login for administrator login / bgapi/login / post request username Get verification code / bgapi/verification/ Blog list / bgapi/blog/list / get request Blog Community resource add / bgapi/blog/add / post request name=file Modify / bgapi/blog/edit / post request name=file Delete / bgapi/blog/del / get request? id=1 List / bgapi/community/list / get request community resources Add / bgapi/community/add / post request subject, Modify / bgapi/community/edit / post request id,subject, Delete / bgapi/community/delete / get request id List / bgapi/banner/list / get requests use nothing Rotation chart Student video add / bgapi/banner/add / post request name=file Modify / bgapi/banner/edit / post request name=file Delete / bgapi/banner/del / get request id List / bgapi/assessvideo/list / get request Student video School running features add / bgapi/assessvideo/add / post request video,img Modify / bgapi/assessvideo/edit / post request video,img Delete / bgapi/assessvideo/delete / get request id List / bgapi/feature/list / get request School running characteristics Homepage information add / bgapi/feature/add / post request name=file Modify / bgapi/feature/edit / post request name=file Delete / bgapi/feature/delete / get request id List / bgapi/mainpuretext/list / get request Home page information Homepage subject add / bgapi/mainpuretext/add / post request title,content Modify / bgapi/mainpuretext/edit / post request id,title,content Delete / bgapi/mainpuretext/delete / get request id List / bgapi/mainsubject/list / get request Home discipline Phase management add / bgapi/mainsubject/add / post request name=file Modify / bgapi/mainsubject/edit / post request name=file Delete / bgapi/mainsubject/delete / get request id List / bgapi/stage/list / get request Stage management Student's speech add / bgapi/stage/add / post request name=file Modify / bgapi/stage/edit / post request name=file Delete / bgapi/stage/delete / get request id List / bgapi/studentsay/list / get request Student sentiment Student work add / bgapi/studentsay/add / post request name=file Modify / bgapi/studentsay/edit / post request name=file Delete / bgapi/studentsay/delete / get request id List / bgapi/studentworks/list / get request Student works Work information add / bgapi/studentworks/add / post request name=file Modify / bgapi/studentworks/edit / post request name=file Delete / bgapi/studentworks/delete / get request id List / bgapi/jobinfo/list / get request Work information Teacher information add / bgapi/jobinfo/add / post request name=file Modify / bgapi/jobinfo/edit / post request name=file Delete / bgapi/jobinfo/delete / get request id List / bgapi/teacher/list / get request Teacher information Course details add / bgapi/teacher/add / post request name=file Modify / bgapi/teacher/edit / post request name=file Delete / bgapi/teacher/delete / get request id List / bgapi/coursedetail/list / get request Course Details Activity management add / bgapi/coursedetail/add / post request name=file Modify / bgapi/coursedetail/edit / post request name=file Delete / bgapi/coursedetail/delete / get request id List / bgapi/activity/list / get request Activity management add / bgapi/activity/add / post request name=file Modify / bgapi/activity/edit / post request name=file Delete / bgapi/activity/delete / get request id
Appendix II: View function program code
Course management view function
from django.forms import model_to_dict from django.shortcuts import render from django.http import JsonResponse,HttpResponse from api.models import CourseDetail,Token from django.conf import settings from .utils import add_data,edit_data,delete_data,list_data,check_token,check_md5 def list(request): if check_token(request): pass else: u_dict = { "status": "509", "info": "Please login first.!", } return JsonResponse(u_dict) ''' //List view function :param request:Request parameters :return:Return json Format data ''' # # Verify login # if check_token(request): # # If it becomes # pass # else: # u_dict = { # "status": "509", # "info": "please log in first!", # } # return JsonResponse(u_dict) # Verification is over. u_dict = list_data(CourseDetail) response = JsonResponse(u_dict) return response def add(request): # Verify login if check_md5(request): # If it becomes pass else: u_dict = { "status": "509", "info": "Please login first.!", } return JsonResponse(u_dict) # Verification is over. ''' //Add view function :param request:Request parameters :return:Return json Format data ''' u_dict = add_data(request,CourseDetail) return JsonResponse(u_dict) def edit(request): # Verify login if check_md5(request): # If it becomes pass else: u_dict = { "status": "509", "info": "Please login first.!", } return JsonResponse(u_dict) # Verification is over. ''' //Edit view function :param request:Request parameters :return:Return json Format data ''' u_dict = edit_data(request,CourseDetail) return JsonResponse(u_dict) def delete(request): # Verify login if check_token(request): # If it becomes pass else: u_dict = { "status": "509", "info": "Please login first.!", } return JsonResponse(u_dict) # Verification is over. ''' //Delete view function :param request:Request parameters :return:Return json Format data ''' u_dict = delete_data(request,CourseDetail) return JsonResponse(u_dict) //Encapsulation tool class //Save file def save_file(file): ''' //Used to save the file and return the path to save the file :param file: :return: ''' if file: # Uploaded a picture import hashlib # Information to be encrypted (random number) ran_str = str(random.randint(0, 9999999)) # Create md5 object hl = hashlib.md5() to_md5_str = str(time()) + ran_str # Tips # encode must be declared here # If the writing method is hl.update(str), the error is: Unicode objects must be encoded before hashing hl.update(to_md5_str.encode(encoding='utf-8')) # Encrypted md5 string md5_str = hl.hexdigest() # File extension file_extend_name = file.name.split('.').pop() # Splicing file name filename = md5_str + '.' + file_extend_name with open(f'./media/' + filename, 'wb+') as f: f.write(file.read()) # with open(f'./media/uploads/' + filename, 'wb+') as fp: # fp.write(file.read()) return filename else: return "" //Delete files def del_file(path): ''' //Used to delete a file. It returns whether it was deleted successfully :param path: :return: ''' import os my_file = settings.BASE_DIR + settings.MEDIA_URL + path print(my_file) if os.path.exists(my_file): # There are two ways to delete a file. os.remove(my_file) return True else: return False //Data returned successfully def success_response(u_dict): ''' //Return data filter correctly :param u_dict: Returned data body content :return: Nested data ''' u_dict = { "status": "200", "info": "Information returned successfully!", "data": u_dict } return u_dict //Return error message def error_response(u_dict, err_info): ''' //Error json returned :param u_dict: json Main contents returned :param err_info: Error message :return: ''' u_dict = { "status": "500", "info": err_info, "data": u_dict } return u_dict //Query data def list_data(a_model_object): ''' //Used to list all database data :param a_model_object: A model object :return: Return json Dictionary of data format dict Type data ''' print("--------------------------Start list view function---------------------------") u_dict = {} try: u_dict = all_data(a_model_object) # Nested u_dict = success_response(u_dict) except: u_dict = error_response(u_dict, "Server error,Query exception!") return u_dict //Add data def add_data(request, a_model_object): ''' //How to add encapsulation :param request: http Request request parameter :param a_model_object: A model object :return: Return json Previous dictionary type data ''' print("--------------------------Start adding view functions---------------------------") # Define return data u_dict = { } # Judge request mode if (request.method == 'POST'): # try: # Start processing pictures # 1. Get the form content data = request.POST.dict() print(data) # If there is a link, then judge whether it is a real link if "link" in data.keys(): curr_link = data["link"] if check_link(curr_link): # If you link, do nothing pass else: # If you can't, just kick it back u_dict = { "info": "Incorrect link type,Please check the format!", "status": "506" } return u_dict # Delete token first data.pop("token") # 2. Get the file in the form file = request.FILES.get('file', None) print("file", file) # 3. Execute save file and return to file path # Save file - > custom function path = save_file(file) # TODO here judge the file type try: kind = filetype.guess(settings.BASE_DIR+settings.MEDIA_URL+path) print("The type of guess is:",kind) print("Guess the type extension yes:",kind.extension) print("Guess the type mime yes:",kind.mime) # TODO: write code..... # # Determine the true file type if kind.extension == "png" or kind.extension == "jpg": # If it's the right type, do nothing pass else: # If it wasn't for these two types # I'll go straight back. Error message u_dict = { "info": "Incorrect picture type,Please upload png perhaps jpg format!", "status": "505" } return u_dict except: u_dict = { "info": "Incorrect picture type,Please upload png perhaps jpg format!", "status": "505" } return u_dict if not path: data.pop("file") # Building img field data data["img"] = path # data.pop("file") # Save data a_model_object(**data).save() # Return data content u_dict = { "info": "ok", "status": "200" } # except: # u_dict = { # "info": "error", # "status": "500" # } if (request.method == 'GET'): u_dict = { "info": "Lack of eyes,Access with browser!", "status": "666" } return u_dict //Modifying data def edit_data(request, a_model_object): ''' //Encapsulation functions for editing :param request: A requested parameter :param a_model_object: A model class object :return: Return to the json Format dictionary dict ''' print("--------------------------Start editing view functions---------------------------") u_dict = { } print("request.POST:", request.POST) print("request.FILES:", request.FILES) if (request.method == 'POST'): # Get modified id data = request.POST.dict() print(data) # Delete token first data.pop("token") # If there is a link, then judge whether it is a real link if "link" in data.keys(): curr_link = data["link"] if check_link(curr_link): # If you link, do nothing pass else: # If not, just kick it back u_dict = { "info": "Incorrect link type,Please check the format!", "status": "506" } return u_dict # print(data.__dict__) id = data["id"] # Get original object obj = a_model_object.objects.get(id=id) dict = model_to_dict(obj) old_path = dict['img'] # 2. Get the file in the form new_file = request.FILES.get('file', None) # Judge whether there are new documents print("new_file:", new_file) # If there's a new document if new_file: # print(new_file) # print(type(new_file)) # print("there are documents left") # Delete old files del_file(old_path) # Save new file path = save_file(new_file) print("new_path:", path) # Building img field data data["img"] = path else: # print("no file left") # print(new_file) # print(type(new_file)) # No new files data["img"] = old_path data.pop("file") obj = a_model_object.objects.filter(id=id) obj.update(**data) # else: # u_dict = { # "info": "failed to delete file!", # "status": "501" # } # return JsonResponse(u_dict) # Success status code u_dict = { "info": "ok", "status": "200" } if (request.method == 'GET'): # Request mode incorrect status code u_dict = { "info": "no", "status": "666" } return u_dict //Delete data def delete_data(request, a_model_object): ''' //Method for removing encapsulation :param request: A request parameter :param a_model_object: A model object :return: Return json Dictionary data of type ''' u_dict = { "info": "default", "status": "888" } print("--------------------------Start deleting view functions---------------------------") try: # Try to delete id = request.GET.get("id") obj = a_model_object.objects.get(id=id) # Delete source file # Get file path dict = model_to_dict(obj) # Delete Library obj.delete() # original path old_path = dict['img'] print("old_path:", old_path) # Execution deletion del_file(old_path) u_dict = { "info": "ok", "status": "200" } except: u_dict = { "info": "error", "status": "500" } return u_dict