[NetDevops] automation network operation and maintenance --1 get basic user information

 Disclaimer: This article is a blogger original article, follow the  CC 4.0 by-sa  copyright agreement, reproduced, please attach the original source link and this statement. 
Before the cloud host blog yet expired renewals, I deleted it [NetDevops] automation network operation and maintenance --1 get basic user informationthe most important thing is not backed up! Omitted words. . . . .
       This article from the beginning of my blog will open a new classification: NetDevops, hope here to record and share my story with network operation and maintenance and network security automation platform. Principles are: multi-line and have the time code on a regular basis through the blog summary[NetDevops] automation network operation and maintenance --1 get basic user information[NetDevops] automation network operation and maintenance --1 get basic user information[NetDevops] automation network operation and maintenance --1 get basic user information[NetDevops] automation network operation and maintenance --1 get basic user information[NetDevops] automation network operation and maintenance --1 get basic user information
This paper records the user to obtain basic information (IP address, the client angent and other information), to engage in this feature I think so by the Python implementation: users are mainly operation and maintenance platform administrator, operation and maintenance personnel, ordinary users, whenever we recorded the basic information of the user when the user logs or access platform and saved to the database. Perhaps we will use these data to do the audit function for their own platform in the future.
Closer to home, this development environment: Python 3.7.4, 2.2.4 Django, Mysql 8.0.15, Docker 18.09.2; compiler tools Pycharm; operating environment for Debian 4.19.0-kali5-amd64, VMware® Workstation 15 Pro
First, we create a Django project called NetDevOps
Can be created by Pycharm created by the terminal command, of course I use the command used to create the CLI interface [NetDevops] automation network operation and maintenance --1 get basic user informationcommand is as follows:
  A. Django-ADMIN startproject NetDevops        # Create Project
   b. Python manage.py startapp the Users        # create APP (to be switched to the project directory)
 
Second, modify the settings file (database connection)
a. find the configuration file settings See related DATABASES, and sqllite3 replaced the default mysql connection
 1 DATABASES = {
 2 'default': {
 3 'ENGINE': 'django.db.backends.mysql',
 4 'NAME': 'netdevops',
 5 'USER': 'forgeek',
 6 'PASSWORD': 'xxxxxx',
 7 'HOST': '172.16.127.128',
 8 'PORT': '3306',
 9 'OPTIONS': {},
10 'init_command': 'SET storage_engine=INNODB,'
11 'SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED, autocommit=1, names "utf8";',
12 }
13 }
View Code

 

b. Modify the init file
  Python3 mysqlclient can not be installed directly by pip, so we use pymysql instead. After installing pymysql by pip we want to modify MySQLdb () engine, we only need to modify init.py file to the project directory, add the following code:
  import pymysql
  pymysql.install_as_MySQLdb()
Third, a brief functional principle of this model
Enter the address of the user access to the platform through a browser ---> urls routing forwarding ---> interface to obtain information ---> view View ---> Database ---> view to the browser view by Httpresponse
 
Fourth, the start line and the code:
  • Mysql configuration
# Create mysql account (this account information to configure the settings in the configuration file database connection consistent)
mysql> alter user 'forgeek'@'%' identified with mysql_native_password by 'xxxx';
# Set forgeek account password never expires
mysql> alter user 'forgeek' @ '%' identified by 'xxxx' password expire never;
# Authorization (here I am here because the test environment to assign permissions is relatively large, we can according to their own situation)
grant all privileges on *.* to 'forgeek'@'%';
# Refresh permission
MySQL> flush privileges;
# to authenticate a user to create a successful
mysql> select host, user, authentication_string from mysql.user;
# Create a database named netdevops
mysql> create database netdevops;
  • models model class
      There models.py files Users of this app we created, in Django model is the single, definitive source of information for your data. It contains important field and behavior of your stored data. Typically, a model (Model) is mapped to a database table .

Defined profile:

  • 每个模型都是一个python类,它是django.db.models.Model的子类
  • 模型的每个属性都代表一个数据库字段
  • 综上所述,Django为您提供了一个自动生成的数据库访问API,详细见官方文档

model与数据库结构对应关系图如下:

[NetDevops] automation network operation and maintenance --1 get basic user information

  这个小功能中我们需要建立两张表,一个保存用户信息另一个保存浏览器信息。考虑到一个用户可能会有多个浏览器,因此需要建立一个一对多的关系。我这里直接贴源码好了,有不懂的直接留言好了。

 1 # coding=utf-8
 2 from django.db import models
 3 
 4 
 5 class UserIpInfo(models.Model):
 6     ip = models.CharField(max_length=40, default='', verbose_name=u'IP地址', null=True)
 7     time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
 8 
 9     class Meta:
10         verbose_name = u"用户访问IP地址表"
11         verbose_name_plural = verbose_name
12         db_table = "useripinfo"
13 
14 
15 class BrowseInfo(models.Model):
16     useragent = models.CharField(max_length=200, default='', verbose_name=u'用户浏览器信息', null=True)
17     models.CharField(max_length=256, verbose_name=u'设备唯一ID', default='')
18     user_ip = models.ForeignKey("UserIpInfo", on_delete=models.CASCADE)
19 
20     class Meta:
21         verbose_name = u"用户浏览器信息表"
22         verbose_name_plural = verbose_name
23         db_table = "browseinfo"
View Code

 

  • views视图
  Django 的视图层,主要是负责处理用户的请求并返回响应。视图函数只是一个Python函数,它接受Web请求并返回Web响应。此响应可以是网页的HTML内容,重定向,404错误,XML文档或图像或者其他什么。视图本身包含返回该响应所需的任意逻辑。只要在Python路径上,此代码就可以存在于您想要的任何地方。没有其他要求 - 没有“魔术”,可以这么说。为了将代码放在某处,惯例是将视图放在名为views.py的文件中,放在项目或应用程序目录中。
这里同样,我将整个源码贴出来。有问题就留言吧
 1 # from django.shortcuts import render
 2 from django.http import HttpResponse
 3 from .models import *
 4 import json
 5 
 6 
 7 def user_ip_info(request):
 8 # print('-----------------test/n', request.META)
 9 ip_addr = request.META['REMOTE_ADDR']
10 user_ua = request.META['HTTP_USER_AGENT']
11 print(len(user_ua))
12 
13 user_obj = UserIpInfo.objects.filter(ip=ip_addr)
14 if not user_obj:
15 res = UserIpInfo.objects.create(ip=ip_addr)
16 ip_addr_id = res.id
17 else:
18 ip_addr_id = user_obj[0].id
19 
20 BrowseInfo.objects.create(useragent=user_ua, user_ip=UserIpInfo.objects.get(id=ip_addr_id))
21 
22 result = {
23 "状态": "Success!",
24 "信息": "User info",
25 "IP": ip_addr,
26 "浏览器": user_ua
27 }
28 
29 return HttpResponse(json.dumps(result), content_type="application/json", charset="utf-8")
30 
31 
32 def user_infos(request):
33 ip_list = UserIpInfo.objects.all()
34 infos = {}
35 for item in ip_list:
36 infos[item.ip] = [b_obj.useragent for b_obj in BrowseInfo.objects.filter(user_ip_id=item.id)]
37 
38 result = {"状态": "Success!", "信息": infos}
39 
40 return HttpResponse(json.dumps(result), content_type="application/json", charset="utf-8")
View Code

 



  • urls路由转发
  对于高质量的Web 应用来说,使用简洁、优雅的URL 模式是一个非常值得重视的细节。Django 允许你自由地设计你的URL,不受框架束缚。
为了给一个应用设计URL,你需要创建一个Python 模块,通常被称为**URLconf**(URL configuration)。这个模块是纯粹的Python 代码,包含URL 模式(简单的正则表达式)到Python 函数(你的视图)的简单映射。映射可短可长,随便你。它可以引用其它的映射。而且,因为它是纯粹的Python 代码,它可以动态构造。
  Django 还提供根据当前语言翻译URL 的一种方法。更多信息参见 国际化文档

----------------该段落引用官方文档-------------------(https://docs.djangoproject.com/zh-hans/2.2/topics/http/urls/

 
我这里还是同样直接贴出源码,有问题留言即可。
 1 NetDevops项目中urls.py
1 from django.urls import path
2 from . import views
3 
4 urlpatterns = [
5 path('send/', views.user_ip_info),
6 path('get/', views.user_infos),
7 
8 ]
View Code


2, User application urls.py:
1 from django.urls import path
2 from . import views
3 
4 urlpatterns = [
5 path('send/', views.user_ip_info),
6 path('get/', views.user_infos),
7 
8 ]
View Code

 



  Since I am here is fed back to the browser via JSON format, so there is no more special HTML file, other features such as the late again perfect template for this project.
Here is the directory structure of this function:
 
We open the terminal command:
1, generate the migration file:  python3 manage.py makemigrations
2, the migration: python3 manage.py the migrate
3, open Djang comes with debugging web server: python3 manage.py the runserver 0.0.0.0:80
 
The last test is to open the browser, the premise is to ensure that your connection is good and the whole project.
 
 
 
 
 
 

Guess you like

Origin www.cnblogs.com/4geek/p/11414020.html