プロジェクト機能の紹介


1.環境準備

  :   INSPINIA   
django==2.2.3
python==3.6.3
pymysql==0.9.3
djangorestframework==3.10.0
1.        linux 
https://blog.51cto.com/10983441/2380368
    1.11  ,       linux 

2.linux  
python  
cd /opt
wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
tar xf Python-3.6.3.tar.xz
cd /opt/Python-3.6.3/
./configure
yum install gcc-c++ gcc -y  #        
make  && make install

3.      
cat /etc/profile
export PATH=$PATH:/usr/local/python3/bin/
  
source /etc/profile

        
[root@m01 opt]# python3
Python 3.6.3 (default, Jul 15 2019, 09:46:16) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
[root@m01 opt]# pip3

Usage:   
  pip  [options]

4.  mysql        
 raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
    
       
#if version < (1, 3, 13):
#    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

File "/usr/local/python3/lib/python3.6/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'
    :
 decode  encode()
query = query.encode(errors='replace')

5.    , Linux   ,windows      
[root@m01 CMDB]# pwd
/project/CMDB
[root@m01 CMDB]# python3 manage.py makemigrations
[root@m01 CMDB]# python3 manage.py migrate

2.機能解析
2.1ユーザー認証のカスタマイズ
  https://docs.djangoproject.com/zh-hans/2.1/topics/auth/customizing/
               ,      ,        

models.py
from django.db import models

# Create your models here.
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUserManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    name = models.CharField(max_length=32)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
 admin.py
 from django.contrib import admin

# Register your models here.
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from web.models import MyUser

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email', 'name')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'name', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'name', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('name',)}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    #      ,            
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'name', 'password1', 'password2')}
        ),
    )
    #     
    search_fields = ('email',)
    #     
    ordering = ('email',)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
settings.py
#        user ,             
AUTH_USER_MODEL = 'web.MyUser'
  
[root@m01 CMDB]# python3 manage.py createsuperuser
(0.000) b'SELECT @@SQL_AUTO_IS_NULL'; args=None
(0.000) b'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED'; args=None
(0.001) b'SHOW FULL TABLES'; args=None
(0.001) b'SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`'; args=()
#    
Email address: [email protected]

(0.001) b"SELECT `web_myuser`.`id`, `web_myuser`.`password`, `web_myuser`.`last_login`, `web_myuser`.`email`, `web_myuser`.`name`, `web_myuser`.`is_active`, `web_myuser`.`is_admin` FROM `web_myuser` WHERE `web_myuser`.`email` = '[email protected]'"; args=('[email protected]',)
#        
Name: admin
Password: 
Password (again): 

This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y

(0.006) b"INSERT INTO `web_myuser` (`password`, `last_login`, `email`, `name`, `is_active`, `is_admin`) VALUES ('pbkdf2_sha256$150000$UTuxK141CULH$MNQ4TR8iwU7pVl8pEX03eb9KmEASze+4CoNK8d1PaCc=', NULL, '[email protected]', 'admin', 1, 0)"; args=['pbkdf2_sha256$150000$UTuxK141CULH$MNQ4TR8iwU7pVl8pEX03eb9KmEASze+4CoNK8d1PaCc=', None, '[email protected]', 'admin', True, False]
(0.003) b"UPDATE `web_myuser` SET `password` = 'pbkdf2_sha256$150000$UTuxK141CULH$MNQ4TR8iwU7pVl8pEX03eb9KmEASze+4CoNK8d1PaCc=', `last_login` = NULL, `email` = '[email protected]', `name` = 'admin', `is_active` = 1, `is_admin` = 1 WHERE `web_myuser`.`id` = 1"; args=('pbkdf2_sha256$150000$UTuxK141CULH$MNQ4TR8iwU7pVl8pEX03eb9KmEASze+4CoNK8d1PaCc=', '[email protected]', 'admin', True, True, 1)
Superuser created successfully.
  :
    python manage.py createsuperuser          ,          
             ,         。

2.2restframwork
http://10.0.0.61:8000/api/
          [email protected]/123

2.2.1データの表示
2.2.2 post送信データ
2.2.3関連表挿入データ

2.3ロール権限
                  
        ,          parent_menu child_munu URL  ,
                

            ,   Privilege    ,            
               

2.4前後のエンドツーエンド値
2.4.1フロントエンドクッキーの中国語入力、バックエンド復号
  
jquery
{#    $.cookie   js#}
    

   
$.cookie('role_search', '  ', { path: '/' });

  
from urllib.parse import unquote
print(search_val)
print(unquote(search_val, "utf-8"))#   
print(unquote(unquote(search_val,"utf-8")))#   

  
  
$.cookie('role_search', encodeURIComponent('  '), { path: '/' });
  
$("#search").val(decodeURIComponent(role_search));

  
from urllib.parse import unquote
print(search_val)#'%25E6%25B5%258B%25E8%25AF%2595'
print(unquote(search_val, "utf-8"))# %E6%B5%8B%E8%AF%95
print(unquote(unquote(search_val,"utf-8")))#   

2.4.2 (すなわちobjectタイプ)、
     
{"10.0.0.61":[1,2,3]}
     Json.Stringfy()     
   body    

   $(function () {
        $(".start-server").click(function () {
             let host_ip_app_info = {};
            $("li.application[aria-selected='true']").each(function () {

                let app_id = $(this).attr("value");
                let ip = $(this).attr("host");
                if (host_ip_app_info[ip]){
                    host_ip_app_info[ip].push(app_id)
                }else{
                    host_ip_app_info[ip]=[app_id]

                }
            });
            console.log("----------------",host_ip_app_info);
            $.ajax({
                url:'{% url "task_manage:start_server" %}',
                type:'post',
                headers:{'X-CSRFtoken':$.cookie("csrftoken")},
                data:JSON.stringify({
                    host_ip_app_info:host_ip_app_info
                }),
                success:function (res) {

                }
            })
        })

    })

    
def StartServer(request):
    print("------------------------",json.loads(request.body.decode()).get("host_ip_app_info"))
    # {'10.0.0.63': ['1', '2'], '10.0.0.61': ['1']}

    return JsonResponse({})

2.5 celeryタイミングタスク
2.5.1 celeryソフトウェアアーキテクチャ
    
# kombu  
pip install kombu==4.2.0
# celery  
pip install celery==4.1.1
    ,   
Django   redis-py versions 3.2.0 or later. You have 2.10.6    
No module named 'kombu.matcher'

[root@m01 CMDB]# pip3 install celery
[root@m01 CMDB]# pip3 install django-celery-beat
[root@m01 CMDB]# pip3 install django-celery-results

  :
celery  , pip install celery    ,     python     /usr/local/python3/bin/celery 
        :ln -s /usr/local/python3/bin/celery  /usr/bin/celery           

2.5.2 celeryモジュールの
     Task.py
           
    :             ,        ID,       task_id       。
    :         ,         

        Broker
app = Celery('tasks',backend='redis://10.0.0.61:6379/1',broker='redis://localhost:6379/0')
Broker,        ,            (  ),       。
Celery         ,      RabbitMQ Redis 。

       Worker
[root@m01 CMDB]# celery -A CMDB worker -l info
#CMDB Django   , py      
Worker          ,         ,          ,    。

         Backend
app = Celery('tasks',backend='redis://10.0.0.61:6379/1',broker='redis://localhost:6379/0')
Backend           ,    。
        ,       RabbitMQ Redis MongoDB    

       Beat
[root@m01 CMDB]# celery -A CMDB beat
        ,          broker 
worker    broker    ,      

2.5.3 celery タスク1-backendが されていない
1.   py      
[root@m01 project]# pwd
/project

2.         
[root@m01 project]# cat sync.py 
#/usr/bin/python3
from celery import Celery,shared_task

app = Celery('tasks', broker='redis://10.0.0.61:6379/1')

@shared_task(name="add")
def add(x, y):
    return x + y
[root@m01 project]# 

3.              
[root@m01 project]# python3
Python 3.6.3 (default, Jul 15 2019, 09:46:16) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sync import add
>>> add.delay(2,3)   


4.     xshell  ,       ,  worker      
[root@m01 project]# celery -A sync worker --loglevel=info
/usr/local/python3/lib/python3.6/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!

Please specify a different user using the --uid option.

User information: uid=0 euid=0 gid=0 egid=0

  uid=uid, euid=euid, gid=gid, egid=egid,

 -------------- celery@m01 v4.3.0 (rhubarb)
---- **** ----- 
--- * ***  * -- Linux-2.6.32-696.el6.x86_64-x86_64-with-centos-6.9-Final 2019-07-18 14:45:06
-- * - **** --- 
- ** ---------- [config]
- ** ---------- .> app:         tasks:0x7f226e9250b8
- ** ---------- .> transport:   redis://10.0.0.61:6379/1
- ** ---------- .> results:     redis://10.0.0.61:6379/1
- *** --- * --- .> concurrency: 2 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** ----- 
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . add

[2019-07-18 14:45:07,042: INFO/MainProcess] Connected to redis://10.0.0.61:6379/1
[2019-07-18 14:45:07,050: INFO/MainProcess] mingle: searching for neighbors
[2019-07-18 14:45:08,082: INFO/MainProcess] mingle: all alone
[2019-07-18 14:45:08,091: INFO/MainProcess] celery@m01 ready.
[2019-07-18 14:45:29,634: INFO/MainProcess] Received task: add[74d07c57-b74d-4ded-9831-73ec4f739940]  
[2019-07-18 14:45:29,649: INFO/ForkPoolWorker-1] Task add[74d07c57-b74d-4ded-9831-73ec4f739940] 
succeeded in 0.012957275001099333s: 5     #    

2.5.4 celery タスク2-backendの
1.   py      
[root@m01 project]# pwd
/project

2.    
[root@m01 project]# cat sync2.py 
#/usr/bin/python3
from celery import Celery,shared_task

app = Celery('tasks', backend='redis://10.0.0.61:6379/1',broker='redis://10.0.0.61:6379/1')

@shared_task(name="add")
def add(x, y):
    return x + y
[root@m01 project]# 

3.    worker ,      
[root@m01 project]# python3
Python 3.6.3 (default, Jul 15 2019, 09:46:16) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sync2 import add
>>> add.delay(2,3)   
 #   ID
>>> re=add.delay(2,3)    
>>> re.ready() #      backend    ready()。orker    ,       ,    False
False
>>> re.get(timeout=1)  #worker    ,       ,         
Traceback (most recent call last):
  File "/usr/local/python3/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 255, in _wait_for_pending
    on_interval=on_interval):
  File "/usr/local/python3/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 54, in drain_events_until
    raise socket.timeout()
socket.timeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/python3/lib/python3.6/site-packages/celery/result.py", line 226, in get
    on_message=on_message,
  File "/usr/local/python3/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 188, in wait_for_pending
    for _ in self._wait_for_pending(result, **kwargs):
  File "/usr/local/python3/lib/python3.6/site-packages/celery/backends/asynchronous.py", line 259, in _wait_for_pending
    raise TimeoutError('The operation timed out.')
celery.exceptions.TimeoutError: The operation timed out.
>>> re.get() #    worker,      ,    

4.  worker
[root@m01 project]# celery -A sync2 worker --loglevel=info
/usr/local/python3/lib/python3.6/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!

Please specify a different user using the --uid option.

User information: uid=0 euid=0 gid=0 egid=0

  uid=uid, euid=euid, gid=gid, egid=egid,

 -------------- celery@m01 v4.3.0 (rhubarb)
---- **** ----- 
--- * ***  * -- Linux-2.6.32-696.el6.x86_64-x86_64-with-centos-6.9-Final 2019-07-18 14:45:06
-- * - **** --- 
- ** ---------- [config]
- ** ---------- .> app:         tasks:0x7f226e9250b8
- ** ---------- .> transport:   redis://10.0.0.61:6379/1
- ** ---------- .> results:     redis://10.0.0.61:6379/1
- *** --- * --- .> concurrency: 2 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** ----- 
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . add

[2019-07-18 14:45:07,042: INFO/MainProcess] Connected to redis://10.0.0.61:6379/1
[2019-07-18 14:45:07,050: INFO/MainProcess] mingle: searching for neighbors
[2019-07-18 14:45:08,082: INFO/MainProcess] mingle: all alone
[2019-07-18 14:45:08,091: INFO/MainProcess] celery@m01 ready.
[2019-07-18 14:45:29,634: INFO/MainProcess] Received task: add[74d07c57-b74d-4ded-9831-73ec4f739940]  
[2019-07-18 14:45:29,649: INFO/ForkPoolWorker-1] Task add[74d07c57-b74d-4ded-9831-73ec4f739940] 
succeeded in 0.012957275001099333s: 5

5.          
>>> re.get()
5
>>> re.get(propagate=False)
5

6.      task_id      ,     backend    
>>> add.delay(1,2)  

>>> from celery.result import AsyncResult

>>> res=AsyncResult("57ddfa56-8e80-448a-b912-243ce44fef70")
>>> re.result
3

7.redis     

2.5.5 celeryサイクルタスク
1.  result 
[root@m01 project]# cd /tmp/untitled/
[root@m01 untitled]# ll
total 60
-rw-r--r-- 1 root root    89 Jul 18 13:13 celerybeat-schedule.bak
-rw-r--r-- 1 root root  8731 Jul 18 13:13 celerybeat-schedule.dat
-rw-r--r-- 1 root root    89 Jul 18 13:13 celerybeat-schedule.dir
-rw-r--r-- 1 root root 18432 Jul 16  2018 db.sqlite3
-rw-r--r-- 1 root root   540 Jul 16  2018 manage.py
-rw-r--r-- 1 root root  2862 Jul 18 15:54 readme.md
-rw-r--r-- 1 root root   188 Jul 18 14:46 te.py
drwxr-xr-x 4 root root  4096 Jul 18 13:05 testcelery
drwxr-xr-x 3 root root  4096 Jul 18 13:02 untitled
#   result 
[root@m01 untitled]# python3 manage.py migrate

2.  worker,        ,     
[root@m01 untitled]# celery -A untitled worker -l info
/usr/local/python3/lib/python3.6/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is
absolutely not recommended!

Please specify a different user using the --uid option.

User information: uid=0 euid=0 gid=0 egid=0

  uid=uid, euid=euid, gid=gid, egid=egid,

 -------------- celery@m01 v4.3.0 (rhubarb)
---- **** ----- 
--- * ***  * -- Linux-2.6.32-696.el6.x86_64-x86_64-with-centos-6.9-Final 2019-07-18 13:13:52
-- * - **** --- 
- ** ---------- [config]
- ** ---------- .> app:         untitled:0x7fa14a5312e8
- ** ---------- .> transport:   redis://10.0.0.61:6379/2
- ** ---------- .> results:     
- *** --- * --- .> concurrency: 2 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** ----- 
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . printqw

[2019-07-18 13:13:52,288: INFO/MainProcess] Connected to redis://10.0.0.61:6379/2
[2019-07-18 13:13:52,297: INFO/MainProcess] mingle: searching for neighbors
[2019-07-18 13:13:53,319: INFO/MainProcess] mingle: all alone
[2019-07-18 13:13:53,330: WARNING/MainProcess] /usr/local/python3/lib/python3.6/site-packages/celery/fixups/django.py:202: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments!
  warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2019-07-18 13:13:53,331: INFO/MainProcess] celery@m01 ready.
[2019-07-18 13:13:53,448: INFO/MainProcess] Received task: printqw[e3d1792f-7628-4861-9fc7-05fd8e7ce537]  
[2019-07-18 13:13:53,469: INFO/ForkPoolWorker-1] Task printqw[e3d1792f-7628-4861-9fc7-05fd8e7ce537] succeeded in 0.01883281399932457s: 'hello celery and django...'
[2019-07-18 13:13:53,969: INFO/MainProcess] Received task: printqw[b874cb79-4aac-4b09-a9f8-5906bf09326b]  
[2019-07-18 13:13:53,979: INFO/ForkPoolWorker-1] Task printqw[b874cb79-4aac-4b09-a9f8-5906bf09326b] succeeded in 0.009641711996664526s: 'hello celery and django...'

3.  beat,           
[root@m01 untitled]# celery -A untitled beat -l info
celery beat v4.3.0 (rhubarb) is starting.
__    -    ... __   -        _
LocalTime -> 2019-07-18 13:13:48
Configuration ->
    . broker -> redis://10.0.0.61:6379/2
    . loader -> celery.loaders.app.AppLoader
    . scheduler -> celery.beat.PersistentScheduler
    . db -> celerybeat-schedule
    . logfile -> [stderr]@%INFO
    . maxinterval -> 5.00 minutes (300s)
[2019-07-18 13:13:48,957: INFO/MainProcess] beat: Starting...
[2019-07-18 13:13:48,978: INFO/MainProcess] Scheduler: Sending due task task-one (printqw)
[2019-07-18 13:13:53,967: INFO/MainProcess] Scheduler: Sending due task task-one (printqw)

4.    

2.5.6 celeryサイクルタスクのadmin
task   ,      

[root@m01 CMDB]# celery -A CMDB worker --loglevel=info >/project/celery_work.log 2>&1 &
[1] 7071
[root@m01 CMDB]# celery -A CMDB beat --loglevel=info >/project/celery_beat.log 2>&1 &
[2] 7077

#      
[root@m01 CMDB]# python3 manage.py migrate

[root@m01 CMDB]# pwd
/project/CMDB
#   worker,        ,    
[root@m01 CMDB]# celery -A CMDB worker -l info
#             
[root@m01 CMDB]# celery -A CMDB beat

2.6/login/アクセス
models.py
class AccessLog(models.Model):
    """
            
    """
    id = models.AutoField(primary_key=True)
    # user_email = models.CharField(verbose_name="     ", max_length=32)
    remote_ip = models.CharField(verbose_name="   IP  ", max_length=32)
    request_path = models.CharField(verbose_name="     ", max_length=255, default="/")
    access_time = models.DateTimeField(verbose_name="    ", auto_now_add=True)

    class Meta:
        verbose_name = '       '
        verbose_name_plural = "       "

    def __str__(self):
        return self.remote_ip

access_times_limit_middleware.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import time
from CMDB import settings
from web.models import AccessLog

class AccessTimesLimitMiddleware(MiddlewareMixin):
    """
                
    """
    def process_request(self, request):
        #           ,            ,     
        if request.path.__contains__("login") and request.method == "POST":
            #       ,    60       
            access_time = settings.ACCESS_TIME if hasattr(settings, 'ACCESS_TIME') else 60
            ip = request.META.get('REMOTE_ADDR')
            request_path = request.path
            #    IP     
            ip_access_log = AccessLog.objects.filter(remote_ip=ip)
            now = time.time()
            if ip_access_log:

                #   ID    ,ID          ,           
                last_access_log = ip_access_log.order_by('id').first()
                # print("=========================", last_access_log.access_time)

                first_access_time = last_access_log.access_time.timestamp()
            else:
                #      IP       ,               
                first_access_time = now
            #          access_time,          ,        
            if float(now)-first_access_time > access_time:
                ip_access_log.delete()

            access_limit = settings.ACCESS_LIMIT if hasattr(settings, 'ACCESS_LIMIT') else 5
            if ip_access_log.count() >= access_limit:
                #       ,    ,        。  
                wait_second = round(access_time-(float(now)-first_access_time), 2)
                # "%s        %s " % (access_time, access_limit)
                return HttpResponse("%s        %s , %s     " % (access_time, access_limit, wait_second))

            AccessLog.objects.create(remote_ip=ip, request_path=request_path)

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',
    'web.access_times_limit_middleware.AccessTimesLimitMiddleware',
]
#            
ACCESS_TIME = 60
ACCESS_LIMIT = 5

login.html





    
    

    DevOps

    
    

    
    

    




    

Welcome to DevOps

{% csrf_token %}

Do not have an account?

Create an account

author:vita © 2019

$(function () { $('.my_login_commit').click(function () { $(".error_info").text(""); $.ajax({ url:"{% url 'login' %}", type:'post', data:{ csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(), email:$('#login_user_email_id').val(), password:$('#login_passwd_id').val() }, success:function (data) { {#console.log("data",data)#} if(data.user){ location.href="{% url 'index' %}" }else if (data.info){ $(".error_info").text(data.info).css("color", "red") }else{ {# ,HttpResponse data#} $(".error_info").text(data).css("color", "red") } }, exception: function (data) { console.log("exceptdata",data) } }) }) })

views.py
def login(request):
    """
        
    :param request:
    :return:
    """
    if request.method == 'POST':
        res = {"user": None, "info": None}
        email = request.POST.get("email")
        password = request.POST.get("password")
        user = auth.authenticate(email=email, password=password)
        if user:
            auth.login(request, user)
            res["user"] = email
        else:
            res["info"] = "         "
        return JsonResponse(res)

    return render(request, "login.html")

2.7restAPI
restAPI   --》  --》    
message = "     API_user       "

2.8 pyechartsリソースリファレンス
  
https://pyecharts.org/#/zh-cn/assets_host
pyecharts                pyecharts-assets    ,      https://assets.pyecharts.org/assets/

pyecharts         HOST      ,           FILE SERVER   ,    。

1.   pyecharts-assets   

 $ git clone https://github.com/pyecharts/pyecharts-assets.git
2.   HTTP file server

 $ cd pyecharts-assets
 $ python -m http.server 8001
 # Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8001/) ...
 #        8000            
3.   pyecharts    HOST

 #          CurrentConfig.ONLINE_HOST   
 from pyecharts.globals import CurrentConfig
 CurrentConfig.ONLINE_HOST = "http://10.0.0.61:8001/assets/"

 #                          
 from pyecharts.charts import Bar
 bar = Bar()