(Star Python developers to improve Python skills)
Source: Liu Jiang
www.cnblogs.com/feixuelove1009/p/5823135.html
This article is aimed at: beginners who have a python foundation and are new to web frameworks.
Environment: windows7, python3.5.1, pycharm professional version, Django version 1.10, pip3
1. Introduction to Django
Baidu Encyclopedia: Open source web application framework, written in Python language...
Key point: A large and comprehensive framework, everything is considered for you.
1. Introduction to web framework
Before specifically introducing Django, we must first introduce concepts such as the WEB framework.
Web framework: A web site template that has been set by others, you learn its rules, and then "fill in the blanks" or "modify" to what you need.
The architecture of a general web framework is like this:
Other python-based web frameworks, such as tornado, flask, and webpy, are all added, deleted and cut within this range. For example, Tornado uses its own asynchronous non-blocking "wsgi", while Flask only provides the most streamlined and basic framework. Django uses WSGI directly and implements most of its functions.
2. Introduction to MVC/MTV
MVC Baidu Encyclopedia : The full name Model View Controller, which is an abbreviation of model-view-controller, is a model of software design, and organizes code in a way of separating business logic, data, and interface display , Gather business logic into one component, while improving and customizing the interface and user interaction, there is no need to rewrite business logic.
Popular explanation : a form of file organization and management! Don't be scared by the abbreviation, this is actually a way to put different types of files in different directories, and then take a tall name. Of course, there are many benefits it brings, such as separation of front and back ends, loose coupling, etc., which will not be explained in detail.
Model (model) : Define database-related content, generally placed in the models.py file.
View : Define HTML and other static web page files related, that is, front-end things such as html, css, js, etc.
Controller (controller) : Define business logic related, which is your main code.
MTV: Some web frameworks found the literal meaning of MVC very awkward, so they changed it. View is no longer HTML-related, but the main business logic, equivalent to a controller. HTML is placed in Templates, called templates, so MVC becomes MTV. This is actually a word game, which is essentially the same as MVC. It's just a different name and name. It doesn't change the medicine.
3. Django's MTV model organization
If the directories are separated, there must be a mechanism to couple them inside. In Django, urls, orm, static, settings, etc. play an important role. A typical business process is shown in the following figure:
So what do we learn from Django?
1. Directory structure specification
2. urls routing method
3. Settings configuration
4. ORM operation
5. Template rendering
6. Other
Two, Django project example
1. Program installation
Install python3.5, pip3 and pycharm professional edition by yourself.
(1) Install Django:
Only the simpler pip3 command installation method is introduced here.
Win+r, call up cmd, run the command: pip3 install django, automatically install the latest version provided by Pypi.
After the installation is complete, as shown below:
(2) Configure the system environment
After successfully installing Django, you can find the django-admin.exe file in the path shown in the figure below, and add it to the operating system environment variables. This will be more convenient for future calls.
Run: django-admin help, you can see the following content to indicate OK.
2. Create a django project
Under the command line interface such as linux, the command provided by django and vim can also be used for project development. However, it is recommended to use pycharm, the best python development IDE at present
, It has powerful functions and friendly interface. (All operations below are performed in pycharm.)
Click: file–>new project, the following dialog box appears.
Select the Django column and enter the name of the project. Here, the international convention mysite is used. Select the python interpreter version and click create to create it.
Django will automatically generate the following directory structure:
The directory with the same name as the project is the configuration file, and the templates directory is where the html file is stored, which is the T in MTV. manage.py is the django project management file.
3. Create APP
Each Django project can contain multiple APPs, which are equivalent to sub-systems, sub-modules, functional components, etc. in a large-scale project. They are relatively independent of each other, but they are also related.
All APPs share project resources.
Enter the command in the terminal terminal under pycharm:
python manage.py startapp cmdb
This creates an APP called cmdb, and django automatically generates the "cmdb" folder.
4. Write routing
The routing is in the urls file, which maps the url input by the browser to the corresponding business processing logic.
The simple way to write urls is as follows:
5. Write business processing logic
The business processing logic is in the views.py file.
Through the above two steps, we point the url of index to the index() function in views, which receives user requests and returns a "hello world" string.
6. Run the web service
Now we can run the web service.
The command line method is: python manage.py runserver 127.0.0.1:8000
But in pycharm, you can do this:
Find the icon shown below in the upper toolbar.
Click the drop down arrow
Click edit configurations
Fill in the host: 127.0.0.1 Fill in the port: 8000
After OK, click the green triangle, and the web service is up and running.
As shown in the figure, it will automatically jump to the browser program interface. The 404 page shown below is displayed:
Modify the url, add "/index", and everything is ok!
At this point, one of the simplest web services written by django has started successfully.
7. Return to HTML file
What did we return to the user's browser above? A string! In fact, this is definitely not working, usually we return the html file to the user.
Below, we write such an index.html file:
Modify the views file again:
In order to let django know where our html file is, we need to modify the corresponding content of the settings file. But by default, it just applies, you don't need to modify it.
Next, we can restart the web service. Refresh in the browser and you will see the styled "hello world".
Note: There is a small trick here. When the service is restarted frequently, it is easy to fail to start the service due to the port not being released. Modify the port and it will be OK.
8. Use static files
We can already return the html file to the user, but it is not enough. The three front-end blocks, html, css, js and various plug-ins, are complete.
Page. In Django, static files are generally placed in the static directory. Next, create a static directory in mysite.
Your CSS, JS and various plugins can be placed in this directory.
In order for django to find this directory, you still need to configure settings:
Similarly, in the index.html file, js files can be introduced:
Restart the web service, refresh the browser, and view the results.
9. Receive data sent by users
Above, we returned a complete html file to the user's browser. But this is not enough, because there is no dynamic interaction between the web server and the user.
Next, we design a form that allows the user to enter a user name and password, submit it to the url of index, and the server will receive the data.
Modify the index.html file first
Then modify the views.py file
At this point, when restarting the web service, an error will occur, because Django has a cross-site request protection mechanism, we turn it off in the settings file.
Enter the browser again and refresh the page:
Enter something, and then we can see the corresponding data in pycharm.
10. Return to the dynamic page
We have received the user's data, but what is returned to the user is still a static page. Usually we will process the user's data before returning it to the user.
At this time, django uses its own template language, similar to jinja2. According to the provided data, replace the corresponding part of the html, and then learn more after getting started with the detailed grammar.
First transform the views.py file:
Reconstruct the index.html file:
Restart the service and refresh the browser:
As you can see, we have obtained the data entered by the user in real time and displayed it on the user page in real time. This is a good interaction process.
11. Use the database
At this point in the process, django's MTV framework has basically surfaced, and only the final database part is left.
Although we interacted well with users above, we did not save any data. Once the page is closed or the server restarts, everything will return to its original state.
There is no doubt about using a database. Django operates the database through its own ORM framework and comes with a lightweight sqlite3 database. Let's take a look:
The first is to register the app:
Without registering it, your database will not know which app to create a table for.
Then we configure database-related parameters in settings. If you use the built-in sqlite, you don't need to modify it.
Then edit the models.py file, which is the M in MTV.
Here we have created 2 fields to store the user's name and password respectively.
The next step is to create a database table in the teminal of pycharm through commands. There are 2 commands, namely:
python manage.py makemigrations
Then enter the command: python manage.py migrate
Modify the business logic in views.py
After restarting the web service, refresh the browser page, and then the data of the user interaction can be saved in the database. You can read data from the database at any time and display it on the page.
At this point, a django project with complete elements and a clear display of the main frame is completed. It is actually very simple, isn't it?
Three, Django summary
As a must-web framework for python, Django has powerful functions and comprehensive content, but it also means a lot of restrictions, low flexibility, and poor modifiability. This is why you cannot have both. When we learn Django, we actually learn a piece of software. We need to understand its basic principles, grasp its overall framework, and keep in mind some basic rules. The rest is to go deep into the details, and then practice makes perfect and how much experience there is. There is no such thing as profoundness. Master the technology.
Suggestions on learning methods: learn anything, don't get into the details directly, you should first understand its peripheral knowledge, look at its overall structure, and then learn its basic content, and then learn more and polish your skills!
Recommended reading
(Click the title to jump to read)
Python devours the world! How the programmer's sideline became the hottest language in the world
Why does Python 3 change print to a function?
Think this article is helpful to you? Please share with more people
Pay attention to the "Python Developer" starred to improve Python skills
Good article, I am reading ❤️