Code release 03

Today Executive Summary

  • Server Management
  • Project management
  • Published Task Management
  • Posted task execution flow dynamic display to the front

Extended knowledge: when a particularly large number of servers when downloading data from the platform, how to reduce stress Platform

The latest technology is the point p2p technology, also known as bit-stream technology

Everyone can become a data downloaders and uploaders

Why sometimes fast movie download speeds, sometimes slow, fast time may be because your roommate inside the computer have the resources, you are downloading from a computer in your roommate, slow is because when you do not have perimeter the resource provider

Today's detailed content

The main project is to achieve and server additions and deletions to change search operation with modelform

Any project is no exaggeration to say that more than 80% by the CRUD composition, and secondly take you to witness what is the real move bricks

We do not directly create all the tables, but to write a create a

Server Management

In order to understand more clearly the logical coupling and projects

The global templates folder removed, create your own templates folder within the application, and delete the application inside views.py

Create a folder views, which do not create a different function according to py files

Data validation

The front end of the field label to render

Display error messages

>>> modelform component assembly forms

Expand knowledge

return redirect('server_list')
# redirect括号内可以直接写url 其实也可以写反向解析的别名 但是如果带有名无名分组的情况 则必须使用reverse

django default locale is English, but it offers a lot of internal national language environment, you can modify

# 配置文件中修改参数
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'

"""django内部能够支持的语言环境 可以查看它的全局配置文件"""
from django.conf import global_settings
LANGUAGE_CODE = 'en-us'

# Languages we provide translations for, out of the box.
LANGUAGES = [
    ('af', gettext_noop('Afrikaans')),
    ('ar', gettext_noop('Arabic')),
    ('ast', gettext_noop('Asturian')),
    ...
]

modelform editing function is very simple, you only need to give a parameter instance

def server_edit(request,edit_id):
    # 获取编辑对象 展示到页面给用户看 之后用户再编辑 提交
    edit_obj = models.Server.objects.filter(pk=edit_id).first()
    """
    其实编辑页面和添加页面是一样的 不同的在于是否需要渲染默认数据
    所以我们直接使用用一个页面
    """
    form_obj = ServerModelForm(instance=edit_obj)
    if request.method == 'POST':
        form_obj = ServerModelForm(data=request.POST,instance=edit_obj)
        if form_obj.is_valid():
            form_obj.save()  # 编辑
            # 新增和编辑都是save方法 区分就依据与instance参数
            return redirect('server_list')
    return render(request,'form.html',locals())

Secondary needs to be done to confirm the delete function

When removal is complete and the need to allow the user to visually see in the browser data is deleted

Not directly refresh the page, because if the case is paged, then refresh the page must be on the first page

If I was on page 99 delete a data, data deletion and also 99

<script>
        function removeData(ths,delete_id) {
            var res = confirm('是否确定删除?');
            // 返回值 判断用户点击的确定还是取消
            if(res){
                // 朝后端发送删除数据的请求
                $.ajax({
                    url:'/server/delete/' + delete_id + '/',
                    type:'get',
                    dataType:'JSON',
                    success:function (args) {
                        if(args.status){
                             // 通过DOM操作 来删除页面数据
                            $(ths).parent().parent().remove()
                        }
                    }
                })
            }
        }
</script>

Project management

class Project(models.Model):
    """项目表"""
    # luffycity  cmdb crm ...
    title = models.CharField(verbose_name='项目名',max_length=32)
    
    # https://www.github.com/xxx.git/
    repo = models.CharField(verbose_name='仓库地址',max_length=32)
    
    env_choices = (
        ('prod','正式'),
        ('test','测试'),
    )
    env = models.CharField(verbose_name='环境',max_length=16,choices=env_choices,default='test')

For additions and deletions to change search item list server code directly copy the table to modify

Optimization Project

Do not come to do after optimization, must be the most lowb simple way to write the code, and then consider the optimization problem

  • View function and should be distinguished from modelform

    """
    app01
      -myforms
          --project.py
          --server.py
    """
  • Modelform same integration server code classes and projects modelform evacuated to base class

    """
    什么是类
      类是对象公共的属性与技能的结合体
    什么是基类
      基类是类公共的属性与技能的结合体
    """
    from django.forms import ModelForm
    
    # 父类
    class BaseModelForm(ModelForm):
        # 将是否添加样式 做成可配置的
        exclude_bootstrap = []
        # 重写init方法  当你不知道一个方法是否有参数或者有几个参数的时候 建议你写*args,**kwargs
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # 额外的操作
            # print(self.fields)  # 有序字典 OrderedDict([('hostname', <django.forms.fields.CharField object at 0x1092abf60>)])
            # 给所有的字段添加样式form-control
            for k, field in self.fields.items():
                # 判断当前字段是否需要加
                if k in self.exclude_bootstrap:
                    # 直接跳过
                    continue
                field.widget.attrs['class'] = 'form-control'
    
    # 子类
    from app01 import models
    from app01.myforms.base import BaseModelForm
    
    
    class ProjectModelForm(BaseModelForm):
        class Meta:
            model = models.Project
            fields = "__all__"
  • List of items need to add a few fields

          # /data/temp/...
        path = models.CharField(verbose_name='线上项目地址',max_length=32)
        # 项目跑在服务器上  那么项目和服务器应该是有关系的
        """
        一个项目可以是否可以跑在多台服务器上   可以!
        一台服务器上是否可以跑多个项目呢      当资金不是很充足的时候 服务器是可以混用的 可以!
        """
        servers = models.ManyToManyField(verbose_name='关联服务器',to='Server')

Published MO

class DeployTask(models.Model):
    """发布任务单
    项目主键            项目版本
    1                      v1
    1                      v2
    1                      v3
    2                      v1
    """
    # luffycity-test-v1-20201111111
    """项目名-环境-版本-日期"""
    uid = models.CharField(verbose_name='标识',max_length=32)

    # 任务与项目是一对多的关系  并且任务是多 项目是一
     # django 升级到2.0之后,表与表之间关联的时候,必须要写on_delete参数,否则会报异常:
    # TypeError: init() missing 1 required positional argument: ‘on_delete’
    project = models.ForeignKey(verbose_name='项目',to='Project',on_delete=models.CASCADE)

    tag = models.CharField(verbose_name='版本',max_length=32)

    status_choices = (
        (1,'待发布'),
        (2,'发布中'),
        (3,'成功'),
        (4,'失败'),
    )
    status = models.IntegerField(verbose_name='状态',choices=status_choices,default=1)

    """预留了一些钩子功能"""
    before_download_script = models.TextField(verbose_name='下载前脚本', null=True, blank=True)
    after_download_script = models.TextField(verbose_name='下载后脚本', null=True, blank=True)
    before_deploy_script = models.TextField(verbose_name='发布前脚本', null=True, blank=True)
    after_deploy_script = models.TextField(verbose_name='发布后脚本', null=True, blank=True)

Django Model Times created the following error:

TypeError: init() missing 1 required positional argument: ‘on_delete’

When executing python manage.py makemigrations error: TypeError: init () missing 1 required positional argument: 'on_delete'

Solution:
define the foreign key when the need to add on_delete =;
i.e.: contract = models.ForeignKey (Contract, on_delete = models.CASCADE)

For the following reasons:
Django upgrade to 2.0 after the association between the table and the table, you must write on_delete parameters, otherwise it will report an exception:
TypeError: the init () 1 Missing required Positional argument: 'on_delete'

On_delete meaning of each parameter are as follows:

on_delete=None,               # 删除关联表中的数据时,当前表与其关联的field的行为
    on_delete=models.CASCADE,     # 删除关联数据,与之关联也删除
    on_delete=models.DO_NOTHING,  # 删除关联数据,什么也不做
    on_delete=models.PROTECT,     # 删除关联数据,引发错误ProtectedError
    # models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True)
    on_delete=models.SET_NULL,    # 删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空,一对一同理)
    # models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值')
    on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值,一对一同理)
    on_delete=models.SET,         # 删除关联数据,
     a. 与之关联的值设置为指定值,设置:models.SET(值)
     b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

Due to many to many (ManyToManyField) on_delete no parameters, so the above only for the foreign key (ForeignKey) and one (OneToOneField)

For more information about the field models of Django: https://www.cnblogs.com/Darksugar/p/7426490.html

Guess you like

Origin www.cnblogs.com/zhangchaocoming/p/12521677.html