day50 django

Yesterday patronage

2. the aid of third-party modules to help you roll up

wsgiref web services gateway interface module

Help you encapsulates socket

Help you deal with the HTTP data directly into a large account closure dictionary

Flask source also start

The amount of concurrent template itself can withstand low django dictionary probably about 1000

3. Based on the above code is opened to the different functions according to different folders

urls.py view function Routing and a correspondence relationship (the view function can also be a function class)

views.py view of a push service function processing logic

templates put html file

If you want to add a feature, just make the changes in both files can be. First, a new set of correspondence relationship urls.py

4. dynamic and static pages

Whether the data is written on the page html dead or back-end dynamic acquisition

The rear end of the acquisition time to display HTML pages directly string replacement is completed

6. Based on jinja2 template syntax, HTML page to achieve back-end traditional values

Template syntax is at the back end of the entry into force, the browser is unable to identify the template syntax, all data previously generated rendering are all good at the back end, the party will complete HTML page

{} {} Related variables

Logically related %% {}

7. The use of the three distal end database jinja2 achieve binding

8. A simple version of a frame of the flowchart web

python three major framework

django: large and

flask: a small but

tornado: asynchronous non-blocking

django profile:

Precautions:

1. The name of the computer can not have Chinese

2. After the index does not have a Chinese name Project

3.python interpreter 3.4-3.6 is recommended not to use python3.7

4. A window can only run a python project

Version of the problem:

There are some differences between 1.X 2.X version

Uniform use of 1.11.11, and not to use a virtual environment

pip3 install django==1.11.11

django-admin

Create a project: django-admin startproject mysite

mysite folder, inside a folder (with the same name project) plus a manage.py

Project start: first need to switch to the project directory cd / masite

python3 manage.py runserver # default port 8000 of the machine

​ python3 manage.py runserver 127.0.0.1:8888

Creating app:

app is similar to the division of specific functions

python3 manage.py startapp day01 # APP's name should also be done to see to know the name of Italy

Command line to create django project, the default will not take the initiative to create the templates folder, and the configuration file settings no path to the folder configuration.

Need manual configuration: DIR: [os.]

Create a matter to note app

White will be three tricks

Returns a string HTTPresponse

render HTML file returns and support traditional values

Redirection can redirect the path of writing this website suffix can also write the full path to other sites

To log function, for example

Static configuration file

1. Under default, all files are placed in HTML templates folder

2. What is a static document:
site used to advance written css js third-party front-end module picture called static resources

3. Default site uses static resource files will be on static folder case
Normally, the static folder will also create additional folders

css folder
js folder
font folder
img folder
bootstrap folder
fontawesome folder
for easier management of file
django need to manually create a static file storage folder

STATIC_URL = '/static/' #访问静态文件资源接口前缀  通常情况下接口的前缀名也叫static 如果后缀是static  就拿路径到下面的文件夹下找
#手动开设静态文件访问资源
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')# 将static文件里面所有的资源暴露给用户 可以有多个,自上往下查找
]

4. Static files Dynamic Binding

{% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist\css\bootstrap.min.css' %}">
    <script src="{%  static 'bootstrap-3.3.7-dist\js\bootstrap.min.js' %}"></script>

form is the default form get request, and get the request parameters is also capable of carrying

http://127.0.0.1:8000/login/?username=jason&password=jason123
#特点:url?xxx=xxx&yyy=yyy
1.携带的数据不安全
2.携带的数据大小有限制,4KB左右
3.通常只会携带一些不是很重要的数据

single form of action parameters
1. do not write, default towards current address submitted
2. Write only the suffix, / index
3. Write the full path

Pre toward backing the request submitted by post 403 cases arise, the need to comment out the line in the configuration file content

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

The view function has to return the objects and return values ​​are HTTPresponse (render, HttpResponse, redircet objects are HTTPresponse)

django rear view function, default processing is get request. But whether it is fat or get post request, will perform the view function.

get requests to get the login page, post a request would like to submit data, and then do the back-end verification

How to determine the current request method
request.method get a string uppercase request method GET POST

if request.method == "POST":
    return HttpResponse('收到了')
return render(request,'login.html')

The initial request method

request.method  获取请求方式,并且是纯大写的字符串
如何获取用户提交的post请求数据:
    request.POST
    request.POST.get()  #默认只会获取列表最后一个元素,里面要写属性名
    request.POST.getlist()  #获取列表,里面要写属性名
 如何获取用户提交的get请求数据:
    request.GET
    request.GET.get()   #默认只会获取列表最后一个元素,里面要写属性名
    request.GET.getlist()   #获取列表,里面要写属性名

pycharm database connection

django connection mysql

There are two actions:
1. The profile configuration

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',#指定数据库类型
        'NAME': 'day50',#指定库的名字
        'USER':'root',#注意 所有的键都是全大写
        'PASSWORD':'',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'CHARSET':'utf8'
    }
}

2. initiative to tell django, do not use the default connection MySQLdb, but with pymysql

In the name of the project may be __init__.pyin writing, you may also be applied in the name of __init__.pywriting in

import pymysql
pymysql.install_as_MySQLdb()

django orm Profile

Why use databases:
can not let people database operations can be simple and convenient to operate the database

orm drawback: the
high degree of encapsulation, sometimes low query efficiency.
So work: The simple need to manually write SQL statements with complex pursuit of speed orm

orm django how to operate the
writing model class, models.py to applications written in the model class (class is)

Note:
After the time to write django project, corresponding to a database on a django, do not appear the case of multiple projects use the same database

Database Migration (synchronous) command:

1. python3 manage.py makemigrations #将数据库的修改记录到小本本上(migrations文件内)
2. python3 manage.py migrate  #将修改操作正在同步在数据库中
注意:
    上面两条命令必须是成双成对出现的,只要修改了models里面跟数据库相关的代码,就必须重新执行上面的两条命令

Field of deletions model change search

class User(models.Model):
    id=models.AutoField(primary_key=True)#django当你不指定主键的时候,会自动帮你创建一个id字段,并且作为主键,如果自己创建了,django就不会帮你创建
    username=models.CharField(max_length=255)#charField必须要指定max_length参数,CharField就是mysql的varchar
    password=models.CharField(max_length=32)
    #设置默认值
    #方式一:
    email=models.EmailField(default='[email protected]')
    #方式二:
    phone=models.BigIntegerField(null=True)
    #还可以直接在提示中给默认值,

Modified fields:
modifying the code, and then execute the migration command database (not a two less)

Increased field:
Mode 1: Set Default default = 'hehehe'
way: field empty to allow null = True

Delete field:
direct comment out the corresponding fields, then execute the database migration command

Deletions model change search table data

Check data

data=models.User.objects.filter(username=username,password=password)## <QuerySet [<User: User object>]>
user_list = models.User.objects.all()# 等价models.User.objects.filter() 所有数据都查出来 里面是一个个的数据对象
user_obj=data[0] 
user_obj.username 

fileter返回的结果是一个“列表”,里面才是数据对象,filter括号内可以放多个关键字参数,这多个关键参数在查询的时候是and关系

Increased data

models.User.objects.create(username=username,password=password)# create方法 会有返回值 返回值就是当前被创建的数据对象本身

Change data

models.User.objects.filter(id=edit_id).update(username=username,password=password)
#批量操作,会将filter查询出来的列表中所有的对象都更新

Delete data

models.User.objects.filter(id=delete_id).delete()
#批量操作,会将filter查询出来的列表中所有的对象都删除

Guess you like

Origin www.cnblogs.com/zqfzqf/p/11924278.html