First, understand the nature of Web applications
For all Web applications, essentially a socket server, the user's browser is actually a socket client.
A simple web framework is implemented using the socket:
#!/usr/bin/env python#Coding:utf-8 ImportSocketdefhandle_request (client): BUF= CLIENT.RECV (1024) Client.send ("http/1.1 ok\r\n\r\n") Client.send ("Hello, Seven.") defMain (): Sock=Socket.socket (socket.af_inet, socket. Sock_stream) Sock.bind (('localhost', 8000)) Sock.listen (5) whiletrue:connection, Address=sock.accept () handle_request (connection) connection.close ()if __name__=='__main__': Main ()
For a real-world Python Web application, it is generally divided into two parts: server programs and Applications. The server program is responsible for encapsulating the socket server and collating the various data requested when the request arrives. The application is responsible for the specific logical processing. In order to facilitate the development of the application, there are many web frameworks, such as Django, Flask, web.py and so on. Different frameworks have different ways of developing them, but in any case, the applications you develop will have to work with the server program to provide services to the user. In this way, the server program needs to provide different support for different frameworks. This chaotic situation is bad for both the server and the framework. For the server, you need to support a variety of frameworks, for the framework, only the servers that support it can be used by the development of the application. Standardization becomes particularly important at this time. We can set up a standard that is supported by the framework as long as the server program supports this standard, so they can work with it. Once the criteria are determined, both parties are implemented. In this way, the server can support more frameworks that support standards, and the framework can use more servers that support standards.
WSGI (Web server Gateway Interface) is a specification that defines the interface format between Web apps and Web servers written in Python, enabling decoupling between Web apps and Web servers.
The standalone WSGI server provided by the Python standard library is called Wsgiref.
#!/usr/bin/env python#Coding:utf-8 fromWsgiref.simple_serverImportMake_serverdefrunserver (environ, start_response): Start_response ('OK', [('Content-type','text/html')]) return ''if __name__=='__main__': httpd= Make_server ("', 8000, Runserver)Print "serving HTTP on port 8000 ..."Httpd.serve_forever ()
All web frameworks are extended and supplemented on this basis.
Two. MVC & MTV
The full name of MVC is the model View Controller, which is the abbreviation for the models-view-controller, a software design paradigm that organizes the code with a method of business logic, data, and interface display separation. Aggregating business logic into a single component does not require rewriting business logic while improving and personalizing the interface and user interaction. MVC is uniquely developed to map the traditional input, processing, and output functions in a logical graphical user interface structure.
MTV is similar to the model framework.
Mvc:model, View, Controller
Mtv:model, Template, View
Three. About Django
Django is an open-source Web application framework written by Python. The MVC Software Design pattern is used, i.e. model M, view V and Controller C. It was originally developed to manage some of the news content-based websites of the Lawrence Publishing Group, namely CMS (Content management system) software. and was released in July 2005 under the BSD license. The framework is named after the Belgian gypsy jazz guitarist Django Reinhardt.
Django is a framework based on MVC constructs. But in Django, the part of the controller that accepts user input is handled by the framework itself, so Django is more concerned with models, templates, and views, called MTV mode. Their respective responsibilities are as follows:
Model, which is the data access layer
Handle all transactions related to the data: how to access it, how to validate it, what behavior it contains, and the relationship between the data.
Templates (template), which is the presentation layer
Handle performance-related decisions: How to display them in a page or other type of document.
View, which is the business logic layer
Access to the model and the relevant logic to tune the appropriate template. The bridge between the model and the template.
Basic structure:
│db.sqlite3----------sqlie3 Database │manage.py│├─logres││admin.py background, you can have a strong background with a very small amount of code. ││APPS.PY││MODELS.PY is related to database operations, where data is stored or read using this ││tests.py││urls.py││views.py││ process user requests, from URLs . py in the corresponding, by rendering templates in the page can be displayed ││ content such as login user name, the user requested data, output to the Web page. ││__init__. py│││├─migrations││0001_initial.py││__init__. py││││├─mushishi││settings.py Django settings, configuration files, such as DEBUG switches, static file locations, etc. ││urls.py urls.py││ URL entry, associated to a function (or generic class) in the corresponding views.py, ││ access URL corresponds to a function. ││wsgi.py WSGI There are multiple kinds of uwsgi and WSGI, you use that kind of wsgi to run Django, generally do not change only when you use the time to change ││__init__. py││├─static└─templates templates in HTML templates, index.html login.html regist.htm L
Four. Install Django
1. Window uses the Pycharm installation process slightly 2. Use PIP on the window to install the PIP installation Django3. Install yum using pip under Linux Install Python-pip pip install Django=1.9.54. Check if the installation was successful import Django >>> Django. VERSION
V. Django BASIC commands
1. Create a django command Django-admin.py Startproject project-Name (names of your projects)2. Create a Django Apppython manage.py startapp app-Name (your app) or Django-admin.py Startapp app-Name (of your app)3. Synchronizing databases python manage.py syncdb Note: Django1.7. Versions 1 and above need to use the following command Python manage.py makemigrationspython manage.py migrate4. Debug mode python manage.py runserver8001#listen to all available IPs (the computer may have one or more intranet IPs, one or more extranet IPs, i.e. multiple IP addresses)Python manage.py runserver 0.0.0.0:80005. Clear database python manage.py flush6. Create Super Admin Python manage.py createsuperuser Follow the prompts to OK7. Modify the administrator password Python manage.py changepassword username (the user name you set at that time)8. Import and Export data Python manage.py dumpdata appname>Appname.jsonpython manage.py loaddata Appname.json9. Enter database python manage.py Dbshell10. More commands for Python manage.py
Application Practice:
Create a Project Project
First click File-newproject and then follow the Create a project
The following directory structure is executed:
The catalogue is interpreted as follows:
Hello--A custom project name
--settings.py Master configuration file
--urls URL Routing file
--WSGI Network Communication interface
Teplates HTML file Storage archive
Next, start creating the app
The following are performed in the terminal under Pychrom
$ python3 manage.py Startapp HelloWorld
The directory structure is as follows:
To write a routing rule:
Routing rules in the URLs file: Add the following rules
"""Hello URL configurationthe ' urlpatterns ' list routes URLs to views. For more information see:https://docs.djangoproject.com/en/1.10/topics/http/urls/examples:function views 1. ADD an import:from My_app import views 2. Add a URL to Urlpatterns:url (R ' ^$ ', views.home, Name= ' home ") class-based views 1. ADD an import:from other_app.views import Home 2. Add a URL to Urlpatterns:url (R ' ^$ ', Home.as_view (), name= ' Home ') including another URLconf 1. Import the Include () function:from django.conf.urls import URL, include 2. Add a URL to Urlpatterns:url (R ' ^blog/', include (' Blog.urls '))""" fromDjango.conf.urlsImportURL fromDjango.contribImportAdmin fromHelloWorldImportViewsurlpatterns=[url (r'^admin/', admin.site.urls), url (r'^index/', Views.index), #制定路由规则]
In views.py
from Import Render # Create your views here. from Import HttpResponse def Index (Request): return HttpResponse ("HelloWorld") #
To start a Django program:
Then visit:
http://127.0.0.1:8000/index/
。。
Wencheng Small pot friend Python-num17-django Foundation