Day63 (ORM supplement (1 pair 1, Django type) pages, CSRF attacks)

Table 1. One to One

1.1 Creating

class UserInfo(models.Model):
    name = models.CharField(max_length=32, null=True)

class Salary(models.Model):
    money = models.CharField(max_length=32, null=True)
    su = models.OneToOneField('UserInfo', null=True)

1.2 Queries

# 1、普通查询
res = models.UserInfo.objects.all()
print(res)
for row in res:
    print(row.id, row.name)

# 2、正向查询
res = models.Salary.objects.all()
for row in res:
    print(row.su.name, row.money)

# 3、反向查询
res = models.UserInfo.objects.all()
for row in res:
    print(row.name, row.salary.money)

2. Django type

3, parameter

- Parameters: 
    MAX_LENGTH = 32 
    null = True: can be set to null 
    db_index = True: Setting Index 
    default: Set default values 
    unique: setting a unique index 
        
    db_column: setting a name column 
    
    unique_together: United unique index 
    index_together: Normal joint index 
        class Meta -: 
            unique_together = ( 
                ( ' Money ' , ' us_id ' ), 
                .... 
            ) 
            index_together = ( 
                ( ' Money ', '')
                ....
            )

4、Django-admin

djagno- ADMIN: 
    Django's own back-end systems management 
        command generation: 
            python3 manage.py createsuperuser 
    want to manage their own table generated: 
        admin.py: 
            from app01 Import Models 
            admin.site.register (models.UserInfo) 
        
    
        Django - ADMIN in column type: 
            EmailField (as CharField):
                 - a string type, Django Admin and authentication mechanisms provided ModelForm 
            IPAddressField (Field,)
                 - string type, Django Admin IPV4 and authentication mechanisms provided ModelForm 
            GenericIPAddressField (Field,)
                 - string type, Django Admin and provides verification ModelForm Ipv4 and Ipv6
                 - parameters:
                    Protocol, specifies Ipv4 or Ipv6, ' both ' , " IPv4 " , " IPv6 " 
                    unpack_ipv4, if designated as True, the input FFFF ::: 192.0.2.1 time, may be resolved to 192.0.2.1, open stab function, = Protocol " both " 
            URLField (as CharField)
                 - string type, Django Admin ModelForm provide authentication and the URL 
            SlugField (as CharField)
                 - string type, Django Admin ModelForm provide authentication and support letters, numbers, underscore, hyphen (minus ) 
            CommaSeparatedIntegerField (as CharField)
                 - string type digital format must be a comma-separated 
            UUIDField (Field,)
                 - string type, Django Admin ModelForm and provides verification of the UUID format
            The FileField (Field,) 
    
        djagno - Parameter admin in: 
            Field name displayed verbose_name Admin of         
    
            whether the blank Admin allows a user to enter the air 
            editable Admin whether to edit the 
            message help_text Admin in this field 

            content selection frame display choices Admin in the data in memory does not vary across the operating table to avoid 
            choices = ( 
                ( . 1, ' M ' ), 
                ( 2, ' F ' ) 
            ) 
            Gender = models.IntegerField (choices = chocies)
            
            id name gender (men and women)

5, Page

class PageInfo():
    def __init__(self, cur_page, total, per_page=5, show_page=5):
        try:
            self.cur_page = int(cur_page)
        except Exception as e:
            self.cur_page = 1

        self.per_page = per_page
        self.show_page = show_page

        a, b = divmod(total, per_page)  # a为商, b为余数
        if b:
            self.total_page = a + 1
        else:
            self.total_page = a

    def get_start(self):
        return (self.cur_page - 1) * (self.per_page)


    def get_stop(self):
        return self.cur_page * self.per_page

    def page(self):
        half = int((self.show_page) / 2)

        # 总页数 < show_page
        if self.total_page < self.show_page:
            begin = 1
            stop = self.total_page
        else:  # 总页数 > show_page
            if self.cur_page - 1 < half:
                begin = 1
                stop = self.show_page + 1
            elif self.cur_page + half > self.total_page:
                begin = self.total_page - self.show_page + 1
                stop = self.total_page + 1
            else:
                begin = self.cur_page - half
                stop = self.cur_page + half + 1

        sli = []

        if self.cur_page == 1:
            s = "<li class='disabled'><a  href='#'>上一页</a></li>"
        else:
            s = "<li><a href='/app2/students/?cur_page=%s'>上一页</a></li>" % (self.cur_page - 1)

        sli.append(s)
        for num in range(begin, stop):
            if num == self.cur_page:
                s = "<li><a href='/app2/students/?cur_page=%s'>%s</a></li>" % (num, num)
            else:
                s = "<li><a href='/app2/students/?cur_page=%s'>%s</a></li>" % (num, num)
            sli.append(s)
        if self.cur_page == self.total_page:
            s = "<li class='disabled'><a href='#'>下一页</a></li>"
        else:

            s = "<li><a href='/app2/students/?cur_page=%s'>下一页</a></li>" % (self.cur_page + 1)
        sli.append(s)
        page_str = " ".join(sli)

        return page_str


def students(request):
    classes = Class.objects.all()

    cur_page = request.GET.get('cur_page'
    total =Get the number of rows, number of pages and then get#)

     Students.objects.count()

    pageinfo = PageInfo(cur_page, total)
    start = pageinfo.get_start()
    stop = pageinfo.get_stop()

    students = Students.objects.all()[start:stop]
    return render(request, 'students.html', {'students': students, 'classes': classes, 'pageinfo':pageinfo})

HTML core code

</li>
    {{ pageinfo.page | safe}}
<li>

6, web attacks

Xss: cross-site scripting attacks

CSRF: Cross-site request forgery

6.1 XSS attack

Web attacks 
Xss attack
 1 , the principle 

  xss attack as cross-site scripting attacks, mainly due to user input in the form of uncontrollable people's comments area, 

  write js code or message board and submit, if we do not add protective measures, it cause, entered 

  js code will be parsed to perform browser, allowing others to get information about our browser

 2 , the code 

  django there is a default xss protection 

  if we want to cancel xss protection, customs clearance pipe character plus safe 

  distal page_info reception parameters {{ | safe}} 

  rear end directly into js code, can be resolved executing a browser

6.2 CSRF attacks

6.2.1 Enable global csrf verification

1. settings, open annotation 'django.middleware.csrf.CsrfViewMiddleware',
2. a form, open csrf_token

<form>
    {% csrf_token %}
    <input type='text'>
</form>

As above, the station will be verified csrf

6.2.2 Close csrf verification section:

 

1. settings, open Notes ==== " 'django.middleware.csrf.CsrfViewMiddleware',
2. views, the following function is introduced

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def csrf1(request):
if request.method == 'GET':
return render(request, 'csrf1.html')
else:
return HttpResponse('ok')

As above, even if the global open authentication, it may be used for special handling decorator not used

6.2.3 open CSRF verification section:

1. settings, the comment ==== "# 'django.middleware.csrf.CsrfViewMiddleware',
2. views, the following function is introduced

from django.views.decorators.csrf import csrf_protect

@csrf_protect
def csrf1(request):
if request.method == 'GET':
return render(request, 'csrf1.html')
else:
return HttpResponse('ok')

As above, even if the global closure verification, it may be used for special handling decorator

 

6.2.4 CBV: If CBV:

from django.utils.decorators import method_decorator

@method_decorator(csrf_protect, name='get')
class User(View):
    def get(self, request):
        pass
    def post(self, request):
        pass    

ajax:

csrftoken = $('input[name="csrfmiddlewaretoken"]').val()

$.ajax({
    type:"POST",
    url : '/xxxx/',
    data: {"name":'xxxx'},
    headers : {'X-CSRFToken': token},
    success: function(){
        console.log(data)
    }
})

 

Guess you like

Origin www.cnblogs.com/gouyang/p/11221397.html