django preliminary understanding

Learn Preschool

wsgiref module (web services gateway interface)

1 socket code that help you a good package
2 http data automatically help you deal with the
time 1. Request to help you split the data format http
2. Response time to go there to help you become a package in line with the data format http The data

According to different functions into different py files opened

urls.py routing function and view correspondence between
views.py handle back-end business logic view function (not just the view function may also be a function class)
Templates specialized storage html file
rule: if you want to add functionality requires only Add a correspondence relationship in urls.py
go views.py write a view function

Static and dynamic pages

1. The rear end of the acquired time is transmitted to the front page
with a replacement character string to pass data
2. Dictionary passes to the front page and convenient operation
by means of a module for rendering template jinja2

from jinja2 import Template
temp = Template(data)
res = temp.render(user={'name':'jason'})

Template rendering: use template syntax to achieve back-end transfer of data to the front end html page

The format of the template on the two kinds of syntax
-related variables: {} {}
logically related to: {} %%

HTTP protocol

Hypertext Transfer Protocol

1. Characteristics of the four
1 protocol based on the TCP / IP application layer acting
2. Based on the request response
3. stateless
Cookie, the session, token, ...
4. connectionless
long connection websocket

2. Data Format
Request format
request the first line (request mode protocol version)
request header (a bunch k: v key-value pairs) similar to the pioneer inform each other in advance the necessary information
\ r \ n

Request body (get request does not request body)

Response format


3. The response status codes
1XX
2XX
3XX
4XX
5XX

Request method
get request
toward the data to others (get request no request body, get request may also carry parameters)
POST request
to submit data (user login) towards others

django preliminary understanding 1

1. White will be three tricks

 from django.shortcuts import render,HttpResponse,redirect
        HttpResponse  # 返回字符串的

        render  # 返回html页面

        redirect  # 重定向

2. Static configuration file

静态文件
    网站所用到的
        自己写好js
        自己写好css
        第三方的框架 bootstrap fontwesome sweetalert
    
通常情况下 网站所用到的静态文件资源 统一都放在static文件夹下
STATIC_URL = '/static/'  # 是访问静态资源的接口前缀
"""只要你想访问静态资源 你就必须以static开头"""
# 手动配置静态文件访问资源
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static'),
    os.path.join(BASE_DIR,'static1'),
    # os.path.join(BASE_DIR,'static2'),
]

接口前缀 动态解析
{% load static %}
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
 form表单 action参数可以写的形式
        1.不写 默认朝当前地址提交
        2.只写后缀/index/
        3.写全路径
       
    form表单默认朝后端提交的方式 默认是get请求
        get请求携带参数的方式 是在url后面?
        url?username=admin&password=213213213213213
        缺点
            1.不安全
            2.get请求携带的参数有大小限制(最大不能超过4KB左右)
    
    前期你如果要提交post请求 你就去settings.py文件注释掉一个中间件
    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',
        ]

3.request Subjects and Methods

 前后端数据交互
        如何获取请求方式
        
        获取post请求携带的数据
            request.POST
           
        获取get请求携带的数据
            request.GET
        get和post在后端获取用户数据的时候 规律是一样的
        <QueryDict: {'username': ['admin', 'tank'], 'password': ['123']}>
        tank <class 'str'>
        123 <class 'str'>
        request.POST.get('username') 默认只取列列表的最后一个元素
        如果你想将列表完整的取出 你必须用getlist()

4.pycharm connect to the database django database connection

 django连接MySQL
            第一步配置文件中配置
                DATABASES = {
                    'default': {
                        'ENGINE': 'django.db.backends.mysql',  # 指定数据库 MySQL postgreSQL
                        'NAME': 'day56',  # 到底使用哪个库
                        'USER':'root',
                        'PASSWORD':'root',
                        'HOST':'127.0.0.1', 
                        'PORT':3306,
                        'CHARSET':'utf8'
                    }
                }
    
            第二步 
                django默认使用的是mysqldb连接数据库  但是该模块不支持了
                所以你要告诉django不要用mysqldb该用pymysql连接
                
                你可以在项目名下面的__init__.py也可以在应用名下面的__init__.py文件中指定
                import pymysql
                pymysql.install_as_MySQLdb()

5.django orm Profile

 orm对象关系映射
        
        类                   数据库的表
        
        对象                  表的记录
        
        对象获取属性          记录的某个字段对应的值
        
        优点:能够让一个不会数据库操作的人 也能够简单快捷去使用数据库
        
        缺点:由于封装程度太高 可能会导致程序的执行效率偏低
        有时候 结合项目需求 可能需要你手写sql语句
        
        
    注意事项
        1.django的orm不会自动帮你创建库,库需要你自己手动创建
            表会自动帮你创建  你只需要书写符合django orm语法的代码即可
    
    去应用下所在的models.py中书写类
    
    from django.db import models

    # Create your models here.
    class Userinfo(models.Model):
        # 设置id字段为userinfo表的主键  id int primary key auto_increment
        id = models.AutoField(primary_key=True)  # 在django中 你可以不指定主键字段 django orm会自动给你当前表新建一个名为id的主键字段
        # 设置username字段  username varchar(64)  CharField必须要指定max_length参数
        username = models.CharField(max_length=64)  # 在django orm中 没有char字段  但是django 暴露给用户 可以自定义char字段
        # 设置password字段  password int
        password = models.IntegerField()
    ******************************数据库迁移(同步)命令***********************************    
    python manage.py makemigrations  # 不会创建表 仅仅是生成一个记录  将你当前的操作记录到一个小本本上(migrations文件夹)
    
    python manage.py migrate  # 将你的orm语句真正的迁移到(同步)到数据库中
    
    
    只要你在models.py中修改了跟数据库相关的代码  你就必须重新开始执行上面两条命令
    
            

Guess you like

Origin www.cnblogs.com/leaf-wind/p/11722908.html