Django Miscellany

Django Miscellany

Because it is general to explain every aspect of no particular point, so this is Miscellany

HHTP agreement

Hypertext Transfer Protocol

  1. Four characteristics
    • Over TCP / IP based application layer acting
    • Socket-based request response
    • no status
    • not connected
  2. Data Format
    • Request format
      1. The first line of the request (request method, protocol version ...)
      2. Request header (lot k: v key-value pairs)
      3. \r\n
      4. Request form () (real time data send post request only if the request is to get no)
    • Response format
      1. The first line of response
      2. Response header
      3. \r\n
      4. Response Body
  3. The response status code
    indicates a specific meaning in some of the figures
    • 1XX: the server has successfully received your data is being processed you can continue to submit additional data
    • 2XX: server success response (200 requests the successful)
    • 3XX: Redirection
    • 4XX: request error (404 403 to request resources do not exist to refuse access)
    • 5XX: internal server error (500)

Request method

  1. get request
    towards others to data
  2. post request
    to submit data to others
  3. url Uniform Resource Locator
    management url

python three major framework

Django:

  • Especially large and comes with features similar to a particularly large aircraft carriers sometimes too heavy

Flask

  • Small but comes with features similar to the Rangers in particular are extremely rare special third-party modules particularly, if the flask third-party modules can all add up to more than django
  • More dependent on third-party modules

Tornado

  • Asynchronous non-blocking
  • Regressed to develop a game server

A: socket Part
B: corresponding relationship between the routing and view function
C: Template grammar

Django:

  • A use someone else's (wsgiref)
  • Write your own B
  • Write your own C

Flask

  • A use of someone else's werkzeug (based wsgiref)
  • Write your own B
  • C with others jinja2

Tornado

  • Three full write your own

Create a Django project Notes

  1. The computer name can not have Chinese
  2. A window is a project pycharm
  3. Try not to use the project name inside Chinese

A django project is similar to a university, while the app is similar to the inside of the University, django is actually used for one application, an app is equivalent to a separate function, django support as many app

Use the command line

  1. Create a project django
    django-admin startproject mysite (project name)
  2. Start django project
    python.manage.py runserver
  3. Creating App
    python.manage.py startapp app01 (App name)

note:

  1. Command line newly created app requires manual configuration settings to a file registration

  2. pycharm wisdom to help you write your first application registered at the time of creating the project
  3. Using the command line to create a django project, will not automatically help you create templates folder, you need to create your own
  4. settings file, you need good enough to write configuration TEMPLATES

  5. Django project at startup, make sure that only one port of a django project

The format of template syntax

Related variables: {} {}

Related logic: {%}%

All users can gain access to the resources of the program are exposed in advance ape good, if not exposed, users can not always access

White will be three tricks

  • HTTPResponse
    Returns a string
  • render
    returns html page
  • redirect
    redirect (jump page)

Static configuration file

Static files

  1. Write your own js
  2. Write your own css
  3. Third-party frameworks, bootstrap, fontwesome, sweetalert

Static file resource site used static files are placed unified normally folder

STATIC_URL = '/ static /' # is a static resource access interface prefix

"""只要你想访问静态资源 你就必须以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 form action parameters can be written in the form

  1. Do not write, default submission towards current address
  2. Write only the suffix / index /
  3. Write full path

form the default form submission data toward the rear end

The default is the get request

get request carries parameters of the way, it's behind url

Disadvantages:

  1. Unsafe
  2. Get request parameters carried in size limit (maximum in Chrome not more than 8182 bytes)

If you want to submit preliminary request to post a comment out you go settings.py file middleware

  • django.middleware.csrf.CsrfViewMiddleware

request Subjects and Methods

Front and rear ends data exchange

How to get request method

  1. Post data acquisition request carries the
    request.POST
  2. Get request to get data carried
    request.GET

get and post acquire user data in the back end when the law is the same

<QueryDict: {'username': ['admin', 'jie'], 'password': ['123']}>

request.POST.get ( 'username') only take default to the last element of the list of columns

If you want a complete list of out you must getlist ()

pycharm connect to the database django database connection

django connect to MySQL

The first step in the configuration file configuration

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 指定数据库 MySQL postgreSQL
        'NAME': 'day56',  # 到底使用哪个库
        'USER':'root',
        'PASSWORD':'root',
        'HOST':'127.0.0.1', 
        'PORT':3306,
        'CHARSET':'utf8'
    }
}

The second step

django default is mysqldb connect to the database but the module does not support the

So you do not have to tell django connection with mysqldb the pymysql

You can also specify the name of the application in the following __init__.py file in the project were the following __init__.py

import pymysql

pymysql.install_as_MySQLdb()

django orm Profile

Class ---> database table

Object ---> table records

Get Object Properties ---> records a value corresponding to a field

Pros: can not make a database of people who can operate fast and easy to use database

Cons: Because of the extent of the package is too high may lead to execution efficiency of the program sometimes combined with low demand items may require you to hand sql statement

Note: django orm of not automatically help you create a library, the library requires you to manually create the table will automatically help you create you just need to write code to comply with django orm syntax

models.py is located next to the application in writing class

# 设置id字段为userinfo表的主键  (id int primary key auto_increment)对应的SQL语句
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()

Database Migration (synchronous) command important !!!!!!!

python manage.py makemigrations # tables are not created just to generate a record of your current operation to record a small notebook (migrations folder)

python manage.py migrate # to migrate your real orm statement to (synchronized) to the database

As long as you modify the code in the database associated with models.py you have to restart the implementation of the above two commands

To be continued ...

Guess you like

Origin www.cnblogs.com/jie9527-/p/11729533.html