Django- separated front and rear ends

Create a subproject testcase

 Create a subproject testcase in Django, the new name of the project need to increase the subprojects in settings.py-> INSTALLED_APPS years, namely 'testcase', or else when the subsequent construction of the table is not found in this sub-project, will take effect .

When construction of the table will have different tables between some public fields, if the construction of the table when each class have a lot of trouble to write it again, this time we can write pulled out a common parent class of the field, the rest of the table when using inheritance can be. Note that when the parent table in the construction of the table should not be created, so the need for a special statement. For details, see examples

When construction of the table, two tables in many relationships in django is by creating a third table to achieve many relationships,

class BaseModel (models.Model):   # parent class 
    the create_time = models.DateTimeField (auto_now_add = True, the verbose_name = ' Created ' ) 
    UPDATE_TIME = models.DateTimeField (auto_now = True, the verbose_name = ' modified ' ) 
    is_delete = models.BooleanField (verbose_name = ' delete ' , default = false) # default = false representation deleted when not actually be deleted, will be marked false 
    class Meta: 
        abstract = True # declare the class just to inherited, not created this table 

class CaseSet (BaseModel):   # inherit the parent class
    = models.CharField name (the verbose_name = ' collection name ' , MAX_LENGTH = 60 ) 
    desc = models.CharField (= the verbose_name ' Collection Description ' , MAX_LENGTH = 70 ) 


    DEF  __str__ (Self):
         return the self.name 

    class Meta -: 
        named db_table, = ' case_set ' 
        the verbose_name = ' use cases collection table ' 
        verbose_name_plural = the verbose_name
class Case (BaseModel): Example # table for 
title = models.CharField (verbose_name = 'with the title's', 80 = MAX_LENGTH, db_index = True, UNIQUE = True)
desc = models.CharField (= the verbose_name 'use described', max_length = 120 )
method_choice = [
[0, 'GET'],
[. 1, 'POST'],
[2, 'PUT'],
[. 3, 'Delete'],
]
Method = models.SmallIntegerField (= method_choice choices, the verbose_name = ' request mode ', default = 0)
URL = models.URLField (= 50 MAX_LENGTH, the verbose_name =' request URL ')
the params = models.TextField (the verbose_name =' parameter request ')
run_count = models.IntegerField (= the verbose_name' run times' , default = 0, null = True, blank = True)
run_time = Models.DateTimeField (verbose_name = 'runtime', null = True, blank = True)
case_set = models.ManyToManyField(CaseSet,db_constraint=False,verbose_name='用例集合',null=True,blank=True)
    #ManyToManyField represent many relationships, case and case_set table is many relationship, above this line will actually create a third table to record many relationships.
    def __str__(self):
return self.title

class Meta:
db_table = 'case'
verbose_name ='用例表'
verbose_name_plural = verbose_name

End of the separation results before and after the item can not be used to render the rear end of the return, to return json string needs to be imported from django.http import JsonResponse

How to manage url when multiple sub-projects?

A project in multiple sub-projects, if all the url are configured in urls.py under django project where it would be more chaos, then we can create a file in each subproject urls.py in separate, individual configuration for url for each item, simply django project in total urls.py in the sub-project configuration go to url.

 

 

 Django in the parameter calibration form

导入:from django import forms

It will be returned by the check form a dictionary in the dictionary data by using ** form.cleaned_data

can form in the custom validation rules, such as a checksum field methon, to begin Clean, i.e. def clean_method, which belong to a single field check, it is checked if a plurality of fields, directly def clean

 

 method one:

# form 校验请求参数
class CaseForm(forms.Form):
    """校验请求参数"""
    title = forms.CharField(max_length=50, min_length=2)
    desc = forms.CharField(max_length=60, required=False)
    method = forms.IntegerField()  # 0 1 2 3
    url = forms.URLField()
    params = forms.CharField(max_length=100)

    def clean_title(self):  # 校验单个字段
        title = self.cleaned_data.get('title')
        if models.Case.objects.filter(title=title).count() >0:
             The raise the ValidationError ( ' use cases title already exists ' ) # throws an exception, the code does not progress downward 
        return title 

    DEF Clean (Self):   # check plurality of fields 
        title = self.cleaned_data.get ( ' title ' ) 
        Method = self.cleaned_data.get ( ' Method ' ) 

when the reference: 
class CaseView (View):
     DEF POST (Self, Request): 
        form = CaseForm (of request.POST)
         IF form.is_valid ():
             Print ( 'This is a form of parity ' ) 
            models.Case.objects.create ( ** form.cleaned_data) 
            Data = { ' code ' : 0, ' MSG ' : ' added successfully ' } 

        the else :
             Print (form.errors. as_data ()) 
            Data = { ' code ' : -1, ' MSG ' : ' parameter error ' } 

        return jsonResponse (Data)

Method Two: This database has a relationship and there is a simple way to check

class CaseForm2 (forms.ModelForm):
     class Meta -:
         # Fields = '__all__ is' representing all fields # 
        # Fields = [ 'Method', 'URL'] # representative of the two fields check 
        the exclude = [ ' case_set ' ] # negative a field 
        Model = models.Case # refers to the association which tables 

when referring to the: 
class CaseView (View):
     DEF POST (Self, Request): 
        form = CaseForm2 (request.POST)
         IF form.is_valid ():
             Print ( ' this is a form of parity ' ) 
            form.save ()#save way is directly connected to the database save, with the following line, so we can write the second method 
            # models.Case.objects.create (** form.cleaned_data) # manually find this operating table, insert the data into test by table 
            Data = { ' code ' : 0, ' MSG ' : ' added successfully ' } 

        the else :
             Print (form.errors.as_data ()) 
            Data = { ' code ' : -1, ' MSG ' : ' parameter error ' } 

        return jsonResponse (Data)

Custom return type

from django.http import JsonResponse

def NbResponse(code=0,msg='操作成功',**kwargs):
    response = {'code':code,'msg':msg}
    response.update(kwargs)
    return JsonResponse(response,json_dumps_params={'ensure_ascii': False})

 

If you do not know the information in the database table, under the command generated by the database table to model1.py file, you do not need to write, and this method will only generate a single table, if there is an association between the table and the table relations, the need to manually associate.

python manage.py inspectdb > model1.py

 

How Django connection redis

The following arranged in settings.py

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://118.23.3.41:6399/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "PASSWORD": "666667&*",  # 密码
        }
    },
    "redis2": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100, 'decode_responses': True},
            "PASSWORD": "123456",  # 密码
        }
    }
}  # redis配置

 

 

 

 

 

 

 

 

 

 

 

 

 

 




Guess you like

Origin www.cnblogs.com/tata-learning/p/12216046.html