Python full stack web framework Django Advanced

Source: Internet
Author: User
Tags bitwise

In the Django Advanced Foundation, some of the operations are to manually create the non-mainstream operation of the connection, which is too low, of course, also to familiarize yourself with this framework! In practice, Django comes with a mechanism for connecting databases and creating apps, along with a more sophisticated routing system mechanism. Now that the basics are understood, talk about the mainstream stuff. First, the web framework re-cognition: since it is the framework, it must have included these modules and corresponding functions! But the different frameworks are also somewhat surprised, after all, the encapsulation method is different. django:-Routing (URL routing system)-Views (view functions)-templates (template pages)-Database---> ORM (Classes-tables; objects-rows; pymysql connection database) torando:-routing-View-templates-Database---> Free: Pymysql; sqlachemyflask:-routing-View-templates (third-party components)-Database---> Freedom: pymysql; Sqlachemy database: The operation of the database on two options: ORM Framework or native SQL, for complex SQL statements, ORM Framework is not implemented, but also to write native SQL statements to execute. So, for database operations, this has to be a choice. Ii. Django Creation project and directory setup operations: the operation on Django to create a new project has already been mentioned in the basics and is no longer reiterated.  Since I use Pycharm, some serious operations will be pycharm. 1, create a new project, create a satic file, configure the settings.py file, these operations are skipped 2, using Django to create the app: (1) pycharm The bottom line is the operation line, find terminal, click into the command Line Operation window. (2) Execution naming: Python manage.py startapp app01-Here is a description: First, when you create a project, there is a python environment. See what version of Python was created. Second, if the computer is loaded with two different versions of the Python environment, first look at its own Python program is renamed. Because the creation is to use the Python program to execute, the operation must write right! Finally: Single environment, directly execute the above code to complete the creation. Since I am a dual environment, execute the creation code as: Python3 manage.py Startapp App01-Another note: You can create multiple app! A Django can have multiple apps (Programs) exist! Example: Python3 manage.py Startapp app02 (3) after a successful creation, a folder named app*** is generated in the current project, with multiple py files in each folder. First do the following explanation:-app01-migrations folder for the database operation log, do not easily delete the data inside-__init__ module before the implementation of the automatic loading of the file (learning module is specific)-Admindjango with background management related configuration-a  PPS saves some configuration information for the current app-modal write classes, create database tables based on classes-Test unit tests-Views Business processing-APP02 ... 3, a number of different applications represent different business, in charge of different modules and functions, so that the same framework can be done in co-development operations. Third, routing system: URL-----> function static route: Refers to the dead URL, corresponding to the operation of a view function! To see the corresponding template, you also need to manually in the browser address bar, if you know the URL, otherwise it will!
The base is all static routes:/login/-def login dynamic routing: Using regular to match, while taking into account the problem of SEO weights (crawler crawl rule)-seo weight: Is the search engine matching rules-Note: Get parameters can be implemented, although the function,      However, the parameters of the values will change frequently, and the weight of this method is too low, and the security is not high! #-------> Get parameter Flags--->? To avoid this problem, use as little as possible.  -URL in essence or regular expression, web address bar address, in essence, or in the regular match! Avoid get pass value: 1. Regular matches the URLs page, when the view function needs to write a formal parameter to receive the value after the fixed URL. -Bitwise (sequential)/add-user/(\w+)/def add_user (REQUEST,A1)---A1 receive (\w+) match pass value/add-user/(\w+)/(\w+)/def add _user (REQUEST,A1,A2)--A1 is the first to receive, the A2 is to receive the second-here it is important to note: matching to the value of the view function, the function in the reception, is strictly in order to receive! -Specify the parameters to pass by name (no longer in order)/add-user/(? p<a1>\w+)/def add_user (REQUEST,A1)/add-user/(? p<a1>\w+)/(?  p<a2>\w+)/def add_user (REQUEST,A1,A2) Note: In the routing system: sequential and specified name parameters cannot be mixed, otherwise the view function cannot complete the matching receive. is omnipotent (*args,**kwargs) also no law corresponding to receive!  So be sure to use it uniformly when writing. Sequential parameters are received by: args and received by Kwargs by the specified name! PS: Terminator $:-If the page does not have a terminator, then the URL can be arbitrarily written URLs or multiple URLs together, so that the page can also be accessed.
However, we do not want this to happen, after all, different URLs correspond to different pages, so the URLs are written on the Terminator, only write a fixed URL to access, the others are not. ^edit$ pseudo-static: Add. html after URLs, disguised as fixed static websites (features: Fast!)    ) The highest weight! URL (r ' ^edit/(\w+). html$ ', Views.edit), 2. Route distribution: (Applied to multiple app development)-first make it clear: multiple apps represent multiple different businesses.            -Used to solve multi-sectoral collaborative development of different business function modules on the same framework. This mechanism is to let each line of business operations write routing relationship URLs when they do not intervene, to avoid simultaneous operation of a file is a URL duplication problem! -Routing distribution configuration: 1, the app file copies a copy of the urls.py file, the py file is used to write the corresponding relationship of the current app 2, in the project home directory mysite urls.py file import include from Django.conf.urls import Include Configuration: URL (r ' ^app filename/', include (' app filename. URLs '), #注意: All examples of string formats: urls.py URL (r ' ^app01/', include (' App01 . URLs ')),
app01.urls.py URL (r ' ^index.html$ ', Views.index), PS: The principle of execution: the route matching is divided into two levels,  To match the route in the urls.py in the project first, the routing URLs point to the corresponding app file, and then the urls.py matches the URL in the Go app file. 3. Default route: (often used for access errors, or fixed information returned if the route does not match)-all routes do not match successfully, then perform a routing relationship, return a fixed hint or a fixed page example: from APP01 import view from Django.shortcuts Import HttpResponse def default (Request): Return HttpResponse (' Dude, go the wrong way. ‘)
URL (r ' ^ ', default), #返回固定的提示! views.py def index (Request): Return render (Request, "index.html")
URL (r ' ^ ', views.index), #返回默认页面 4, Name: Used to reverse-generate URLs by name (maximum feature: You can reverse the URL by name, to write or store complex or long path)-to the urls.py file in the corresponding relationship, name name = "xxx"/add-user/(\d+)/-def add_user (REQUEST,A1) name=n1 can reverse-generate URL 1 by name. In Python code: reverse-Generate URLs with request and parameters
From Django.urls import reversedef add_user (request,a1) v = reverse (' N1 ', args=xxx, #对应顺序传参 kwargs={' A1 ': 1111} #对 Should be a bitwise pass #为url传值, generate a new URL, want to get what URL to get what URL two ways two choose one) print (v) return render (Request, "index.html") browser address bar: 127.0.0.1:80 00/index/123 backstage to get the v:index/1111 2.  In a template page, you can also reverse-generate the URL by name (no value is passed in the View function, and no return value)-when there is no parameter: In the View function: Def login (Request) return Reder (Request, "login.html") Template file: url (r ' ^login/', Views.login,name= ' M1 ') {% URL ' m1 '%}-parameter, value: In view function: Def login (REQUEST,A1 (*args)) return Reder (Request, "login.html") template file: url (r ' ^login/', Views.login,name= ' M1 ') {% URL "M1" value%} #按照顺序传值 Single value {% URL "M1" value 1 Value 2} #按照顺序传值 multi-value #写值的时候, be sure to pay attention to the space!  V. ORM Operation: Relational object map operation database! Django's ORM is not directly connected to the database, it needs to connect to the database using Pymysql third-party tools, but Django uses MYSQLDB to connect to MySQL by default.
However, there is no mysqldb in Python3, so you need to modify the way Django defaults to MySQL connection!
At the same time, Django uses SQLite (file type) to manipulate the database by default, and it needs to be modified!  1, configuration database: # because the Django internal connection MySQL is using the MySQLdb module, and Python3 does not have this module, so you need to use Pymysql instead of 1, the following settings placed in the same name as the configuration of project __init__.py file  Import Pymysql pymysql.install_as_mysqldb () 2, modify the configuration information for the databases connection database in the configuration file settings.py with the same name as Project: (1) Comment out the original message! (2) Write new configuration information: DATABASES = {' default ': {' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' s4day70 ', #数据库名称 ' USER ': ' Root ', #账号 ' PASSWORD ': ', #密码 ' HOST ': ' localhost ', #IP ' PORT ': 3306, #端口号 ' CHARSET ': ' UTF8 ', #字符编码}}3, register app:-in settings.py file Installed_apps configuration information, and finally add the app file name to be manipulated to complete the registration operation. Note is a string type! Installed_apps = [' django.contrib.admin ', ' Django.contrib.auth ', ' django.contrib.contenttypes ', ' Django.contrib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', ' app01 ',]-some will automatically add, no fuss, Check if it's right!

Vi. Django ORM Operations:

1. Fields and Parameters:

Http://www.cnblogs.com/zh605929205/articles/7103825.html

2, models operation:

Http://www.cnblogs.com/zh605929205/articles/7103831.html

Seven, the template:

Http://www.cnblogs.com/zh605929205/articles/7103790.html

Eight, pagination:

Http://www.cnblogs.com/zh605929205/articles/7103887.html

Ix. Django's XSS and CSRF mechanism:

Http://www.cnblogs.com/zh605929205/articles/7103796.html

Ten, Django session:

Http://www.cnblogs.com/zh605929205/articles/7103775.html

XI. Middleware:

Reference Address:

Http://www.cnblogs.com/wupeiqi/articles/5237704.html

Http://www.cnblogs.com/wupeiqi/articles/5246483.html

Http://www.cnblogs.com/wupeiqi/articles/6216618.html

Python full stack web framework Django Advanced

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.