編寫了信號函數(shù)后,并沒有如預(yù)期一般在必要時候觸發(fā),函數(shù)如下:
創(chuàng)新互聯(lián)制作網(wǎng)站網(wǎng)頁找三站合一網(wǎng)站制作公司,專注于網(wǎng)頁設(shè)計,成都網(wǎng)站制作、成都做網(wǎng)站,網(wǎng)站設(shè)計,企業(yè)網(wǎng)站搭建,網(wǎng)站開發(fā),建網(wǎng)站業(yè)務(wù),680元做網(wǎng)站,已為上1000+服務(wù),創(chuàng)新互聯(lián)網(wǎng)站建設(shè)將一如既往的為我們的客戶提供最優(yōu)質(zhì)的網(wǎng)站建設(shè)、網(wǎng)絡(luò)營銷推廣服務(wù)!
@receiver(signals.post_save, sender=Prometheus)
def monitor_prometheus_update(instance, **kwargs):
# 當(dāng)發(fā)生修改時,更新控制臺url
web_url = "http://{ip}:{port}/{route}".format(ip=instance.ip, port=instance.port, route=instance.url)
Prometheus.objects.filter(ip=instance.ip).update(web_url=web_url)
print("觸發(fā)", web_url, instance)
理論上應(yīng)該在每次信息修改時觸發(fā),print出觸發(fā)信息,但是并沒生效,我是在apps.py中定義ready方法:
from django.apps import AppConfig
class ServicesConfig(AppConfig):
name = 'apps.services'
default_auto_field = 'django.db.models.BigAutoField'
def ready(self):
import apps.services.signals
使用startapp創(chuàng)建一個新的應(yīng)用到指定目錄時,報錯:
CommandError: 'apps' conflicts with the name of an existing Python module and cannot be used as an app directory. Please try another directory.
使用的命令是startapp services .apps
在項目目錄下新建apps目錄,然后在其中新建空目錄services,此時使用命令startapp services ./apps/services
就可以在指定的目錄下創(chuàng)建新的應(yīng)用了。
編寫了Get請求后,需要支持用戶在請求時攜帶部分參數(shù),方便查詢
使用rest_framework.request.Request
的query_params能夠方便拿到請求參數(shù):
class PrometheusList(APIView):
def get(self,request: Request):
"""
:param request:
:return:
"""
param=request.query_params
if param and 'group' in param.keys():
# 支持通過group來進行查詢
queryset = Prometheus.objects.filter(group=param['group'])
else:
queryset = Prometheus.objects.all()
s = PrometheusSerializer(instance=queryset, many=True)
return Response(s.data, status = status.HTTP_200_OK)
隨后創(chuàng)建三條記錄,分組不同,進行測試:
執(zhí)行GET請求如下:
GET /api/v1/services/prometheus?group=default
返回結(jié)果
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"ip": "1.1.1.1",
"port": 9090,
"url": "",
"web_url": "http://1.1.1.1:9090/",
"group": "default",
"create_by": "2022-08-23 18:06:19",
"update_by": "2022-08-23 18:06:19"
},
{
"ip": "1.1.1.2",
"port": 9090,
"url": "",
"web_url": "http://1.1.1.2:9090/",
"group": "default",
"create_by": "2022-08-23 18:06:25",
"update_by": "2022-08-23 18:06:25"
}
]
在我的模型類中,web_url字段需要依賴于ip、port以及url字段生成,格式如下:
web_url = "http://{ip}:{port}/{url}"
原先使用信號機制實現(xiàn)這種,當(dāng)任意一個字段變化時也會觸發(fā)web_url變化,但是發(fā)現(xiàn)這樣實現(xiàn)并不好;
新的實現(xiàn)方法如下,在模型類中實現(xiàn)save方法:
class Prometheus(models.Model):
STATUS = (
("UP", "運行中"),
("DOWN", "已停止")
)
# Prometheus服務(wù)的模型
ip = models.GenericIPAddressField(protocol="IPV4",help_text="指定了Prometheus服務(wù)所在服務(wù)器IP", verbose_name="服務(wù)IP", blank=False,
primary_key=True)
port = models.IntegerField(help_text="指定了Prometheus服務(wù)的端口號,不正確會導(dǎo)致服務(wù)狀態(tài)獲取異常", verbose_name="服務(wù)端口",
default=9090)
url = models.CharField(max_length=50, help_text="該值對應(yīng)了Prometheus的啟動參數(shù)web.external-url", verbose_name="訪問路由",
blank=True)
web_url = models.URLField(help_text="可以通過此URL跳轉(zhuǎn)到Prometheus的Web", verbose_name="控制臺", default="")
group = models.CharField(max_length=50, help_text="用戶定義的Prometheus服務(wù)所屬的組", verbose_name="分組", default="default")
status = models.CharField(max_length=50,choices=STATUS, help_text="Prometheus節(jié)點的狀態(tài),已停止時無法進行部分操作",verbose_name="狀態(tài)", default="DOWN")
create_by = models.DateTimeField(verbose_name="創(chuàng)建時間", auto_now_add=True)
update_by = models.DateTimeField(verbose_name="更新時間", auto_now=True)
def save(self, *args, **kwargs):
"""
重寫save方法,自動生成web_url
:param args:
:param kwargs:
:return:
"""
self.web_url = "http://{ip}:{port}/{route}".format(ip=self.ip, port=self.port, route=self.url)
super(Prometheus, self).save(*args, **kwargs)
在通用類視圖中,使用默認(rèn)分頁類的默認(rèn)的返回結(jié)構(gòu)是這樣的:
字段并不是我要的,所以對其最新一定的自定義;
自定義分頁類繼承自PageNumberPagination,然后實現(xiàn)get_paginated_response方法,原本的改方法返回的是OrderDict類型的結(jié)果,不過我看python3.6以后的dict也是默認(rèn)有序了,所以我覺得返回dict是沒問題的:
from rest_framework.pagination import PageNumberPagination
class ServicePageNumberPagination(PageNumberPagination):
page_size_query_param = 'page_size'
page_query_param = "page"
max_page_size = 100
def get_paginated_response(self, data):
return Response(dict([
('total', self.page.paginator.count),
('results', data),
('success', True)
]))
這里如果想要在返回的結(jié)構(gòu)中打印出當(dāng)前的url連接,可以通過get_html_context()方法實現(xiàn):
get請求中,添加篩選項,這里是期望用group和status作為篩選項:
需要使用到django-filter
包,使用pip進行安裝:
pip install django-filter
修改settings.py全局配置:
INSTALLED_APPS = [
......
'django_filters',
]
REST_FRAMEWORK = {
......
# 過濾查詢,全局配置
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend"
]
}
在對應(yīng)的視圖里添加filter_backends
和filterset_fields
:
from django_filters.rest_framework import DjangoFilterBackend
class ServiceMixinView(ListAPIView, CreateAPIView):
"""
查詢、添加Prometheus服務(wù)的操作,設(shè)計中暫不準(zhǔn)備支持批量更新
"""
# 使用Mixin實現(xiàn)
queryset = Prometheus.objects.all()
serializer_class = PrometheusSerializer
# 分頁類的實現(xiàn)
pagination_class = ServicePageNumberPagination
# 設(shè)置lookup_field
lookup_field = 'ip'
filter_backends = [DjangoFilterBackend]
filterset_fields = ['group', 'status']
這樣便可以在get時添加param進行篩選了: