In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Today, I will talk to you about how to connect the front and back end technology of Python from scratch. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Overview of operation and maintenance development process
It is an entrance for us to participate in it, and we need to understand some aspects of operation and maintenance development, as well as some technical basis of operation and maintenance development. We use an example to demonstrate that the basic requirement is to retrieve the data from the database and show it through the front-end page.
(1) Business requirements
Display personnel information and departments
Use the Django framework to flow data
Data is stored in MySQL
You can view the data on the front-end page
Rapid iterative development
(2) Environmental construction
1) create a project
Django-admin startproject emp_test
2) start Python built-in web service
Where 192.168.56.102 is the host IP, which can be modified as needed.
Python manage.py runserver 192.168.56.102:9001
Error 1 A server error occurred. Please contact the administrator.
Solution: modify the settings.py file
ALLOWED_HOSTS = ['*']
3) create an application
Suppose the application is named emp_test, and the application is part of the project or a module
Django-admin startapp emp_test
You need to configure the application to take effect in the project. Configure the settings.py file.
Add the following applications:
INSTALLED_APPS = (
'django.contrib.admin'
'django.contrib.auth'
'django.contrib.contenttypes'
'django.contrib.sessions'
'django.contrib.messages'
'django.contrib.staticfiles'
'emp_test'
)
(3) Construction of Django Admin Site
To quickly build an application interface, we can try using Django Admin Site
First of all, we need to do ORM mapping, because the Admin module will persist some data in the database, which needs to be in the form of tables. This is the built-in function of Django and requires object-relational mapping. If we use the default sqlite, we need to create database tables to the database.
Check to see if there are any database changes, because there is built-in functionality here, so we don't need to create any models.
[root@dev01 demo_test] # python manage.py makemigrations
No changes detected
Generate the tables of the database to the database (sqlite). You can see from the log that multiple tables have been created
[root@dev01 demo_test] # python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying sessions.0001_initial... OK
The Sqlite file is in the root directory of the project:
[root@dev01 demo_test] # ll
Total 48
-rw-r--r-- 1 root root 36864 Apr 8 15:44 db.sqlite3
Drwxr-xr-x 2 root root 4096 Apr 8 15:42 demo_test
Drwxr-xr-x 3 root root 4096 Apr 8 15:42 emp_test
-rwxr-xr-x 1 root root 252 Apr 8 15:37 manage.py
To build the Admin module, you need to enter a user name, password and mailbox:
[root@dev01 demo_test] # python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: admin@mail.jj.cn
Password:
Password (again):
Superuser created successfully.
Enter URL in the browser:
Http://192.168.56.102:9001/admin
Access to Admin Site
To implement custom front-end pages and meet complex requirements, we need to do it in a custom way.
(4) implementation of custom front and back end technology
The whole process will follow the steps of building the model, configuring URL, configuring VIEW, and configuring the front-end page.
1) build the model
Our requirement is to view the basic information of employees. We plan to create a table emp with two fields. Add the following content to the models.py under the emp_test directory:
As can be seen from the code, field empno is a self-increasing sequence, ename is an employee's name, is a character type, and the length is 50.
Class emp (models.Model):
Empno = models.AutoField (primary_key=True,verbose_name='emp ID')
Ename = models.CharField (max_length=50,verbose_name='emp name')
Persist model to database
[root@dev01 demo_test] # python manage.py makemigrations
Migrations for 'emp_test':
0001_initial.py:
-Create model emp
[root@dev01 demo_test] # python manage.py sqlmigrate emp_test 0001
BEGIN
CREATE TABLE "emp_test_emp" ("empno" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "ename" varchar (50) NOT NULL)
COMMIT
[root@dev01 demo_test] #
[root@dev01 demo_test] #
[root@dev01 demo_test] # python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, emp_test, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying emp_test.0001_initial... OK
2) configure URL
URL is the entrance to the page. Suppose the URL we want to visit is:
Http://192.168.56.102:9001/emplist
Configure the URL file urls.py, which is modified in the project file demo_test/urls.py, where emplist comes from the emplist function of the view layer
From emp_test.views import emplist
Urlpatterns = [
Url (r'^ admin/', include (admin.site.urls))
Url (r'^ emplist/',emplist)
]
3) configure view layer logic
From django.shortcuts import render_to_response, HttpResponseRedirect
From emp_test.models import emp
From django.template import RequestContext
Def emplist (request):
Return render_to_response ('emplist.html',context_instance=RequestContext (request))
4) configure the frontend page
According to the flow of the view layer, you need to configure the front-end page emplist.html to display the data.
Create a folder templates under the application emp_test directory
Mkdir-p templates
Cd templates
The contents of the file are:
Hello team
If the page can be displayed properly, it proves that the whole journey is unblocked, and then we continue to improve on this basis.
5) configure data access
On this basis, our data will be retrieved from the database, and the content of ORM will be used here.
If we don't have any foundation for ORM, we can familiarize ourselves with it first, and we can create some data through Django API.
Connect to sqlite on the command line
[root@dev01 demo_test] # python manage.py shell
Python 2.7.14 (default, Dec 12 2017, 14:17:04)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
Introduce the model that needs to be operated. This is emp, which we created in models.py.
> from emp_test.models import emp
Looking at all the databases in emp, the operation of the data is similar to that of API, and the data result set is currently empty.
> > emp.objects.all ()
[]
Let's create a few records, which can be created using create
> emp.objects.create (ename='jeanron')
Check it again and you'll have the data.
> > emp.objects.all ()
[]
If you want to see more detailed information, you can specify the output column, for example, here is ename
> emp.objects.all () .values ('ename')
[{'ename': upright jeanron'}]
> emp.objects.create (ename='wusb')
Insert a few more pieces of data.
> emp.objects.create (ename='macc')
> emp.objects.all () .values ('ename')
[{'ename': upright jeanronic'}, {'ename': upright wusb'}, {' ename': upright macc'}]
> emp.objects.filter (ename='wusb')
[]
If you want to do a filtering query, you can use filter, for example, specify the record of ename='wusb', and the output is listed as empno.
> emp.objects.filter (ename='wusb'). Values ('empno')
[{'empno': 2}]
Quit
> > exit ()
So to add the data lookup logic in the ORM layer, we need to do it in the view layer.
We modify the content of views.py slightly to specify the result set as emp_data, which can be returned by passing the result set into the response object.
From django.shortcuts import render_to_response, HttpResponseRedirect
From emp_test.models import emp
From django.template import RequestContext
Def emplist (request):
Emp_data = emp.objects.all ()
Return render_to_response ('emplist.html', {"emp_data": emp_data}, context_instance=RequestContext (request))
6) optimize the front-end page
Then we modify the front page to show the returned data.
The emplist.html is as follows:
Hello team
{{emp_data}}
{% for tmp_data in emp_data%}
{{tmp_data.empno}}
{{tmp_data.ename}}
{% endfor%}
When the browser accesses URL, the result is:
In the front-end page, you can use tags to implement the data returned from the back-end. For example, the data of emp_data is a result set, and we can iterate and do it in the way of for tmp_data in emp_data, which is the same as the syntax of Python. The output of each element in it is the {{tmp_data.empno}} way.
(5) Supplementary contents:
1)。 Change the data source to MySQL
The database defaults to sqlite, and there is no need to modify any configuration. If you use MySQL, you can configure the settings.py file and modify the following configuration
Database environment uses MySQL
DATABASES = {
'default': {
'ENGINE':'django.db.backends.mysql'
'NAME':'kmp'
'USER':'test_django'
'PASSWORD':'xxxx'
'PORT':3306
'HOST':'127.0.0.1'
}
}
2) configured model to Admin Site
Configure the file admin.py under emp_test
From emp_test.models import emp
Class category_emp (admin.ModelAdmin):
Fields = ['empno',' ename']
List_display = ('empno'
'ename')
List_filter = ['empno']
Admin.site.register (emp, category_emp)
After reading the above, do you have any further understanding of how to concatenate the front and back end of Python from scratch? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.