django 基础
 

Django

初始化

python3 -m venv env
source  env/bin/activate

pip  install -i http://mirrors.aliyun.com/pypi/simple  --trusted-host mirrors.aliyun.com  -r requirements.txt



django-admin startproject website .
django-admin startapp  asset
django-admin startapp dashboard
# 建立项目和app应用

mkdir  static templates uploads


python manage.py makemigrations user
python manage.py makemigrations asset
python manage.py makemigrations
python manage.py migrate 

python manage.py  createsuperuser # 初始化管理员账号
python manage.py runserver 0.0.0.0:8000 # 启动服务

settings

读取settings

# CIPHER_KEY = 'JhpsbscR9FWrCt3eWxxxxxx'

# 外部脚本加载django模块
import  os,django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
django.setup()

# 导入settings
from django.conf import settings
print(settings.CIPHER_KEY)

model业务模型

from django.db import models
class Host(models.Model):
    hostname = models.CharField(db_column='hostname', max_length=64, unique=True, verbose_name='主机名')
    instance_id = models.CharField(db_column='instance_id', max_length=255, blank=True, null=True,verbose_name="实例ID")

   class Meta:
        db_table = 'host'
        unique_together = (('instance_id', 'hostname'),)
        verbose_name = '主机'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.hostname

view视图

template页面渲染模板

django admin 后台

from django.contrib import admin
from .models import *

@admin.register(CmdbHost)
class CmdbHost_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in CmdbHost._meta.fields  if key.name !='id') # 变量字段排除id
    list_display = all_fields

    search_fields = ['hostname', 'management_ip','floatingip',  'ipv6']
    list_filter = ['region_id','platform_id']  # 右侧过滤栏
    list_editable = ['status']  # 可编辑项
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']


    fieldsets = (
        ('主机信息', {
            'fields': ['hostname', 'management_ip', 'ssh_id']
        }),
        ('云平台', {
            # 'classes': ('collapse',),  # 隐藏显示
            'fields': ['instance_id', 'floatingip','ipv6', 'region_id', 'platform_id']
        }),
        ('硬件信息', {
            # 'classes': ('collapse', ),  # 隐藏显示
            'fields': ['cpu', 'memory', 'disk']
        }),
         ('其他信息', {
            # 'classes': ('collapse', ),  # 隐藏显示
            'fields': ('tag','status', 'description'),
        }),
    )


    formfield_overrides = {
        models.CharField: {'widget': TextInput(attrs={'size': '20'})},
        models.TextField: {'widget': Textarea(attrs={'rows': 4, 'cols': 60})},
    }

    # 新增或修改数据时,过滤外键可选值
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'ssh_id':
            # 过滤
            kwargs["queryset"] = SSH_authentication.objects.filter(is_manager=True)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(Region)
class CmdbRegionadmin(admin.ModelAdmin):
    all_fields = list(key.name for key in Region._meta.fields  if key.name !='id' )  # 变量字段排除id
    list_display =  all_fields

Django REST Framework

路由

URL配置

from django.urls import path, re_path
urlpatterns = [
    path('host', views.HostView.as_view(), name="hostview"), # 基于类视图
    re_path('host/(?P<pk>\d+)$', views.HostDetailView.as_view(), name="hostdetial"), # re_path支持正则表达式
]

生成swagger api文档

pip  install -i http://mirrors.aliyun.com/pypi/simple  --trusted-host mirrors.aliyun.com  drf-yasg
##### settings.py #####
  'drf_yasg', # swagger文档

##### urls.py #####
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
# swagger文档
schema_view = get_schema_view(
    openapi.Info(
        title="API",
        default_version='v1',
        description="API开发文档",
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)


urlpatterns = [
  path('swagger/', schema_view.with_ui('swagger',
         cache_timeout=0), name='schema-swagger-ui'),
    path('docs/', schema_view.with_ui('redoc',
         cache_timeout=0), name='TBoss Api'),

文章作者: 以谁为师
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源!
              
  目录