返回json数据有两种方式
1.model_name.objects.values()
2.serializers.serialize()
urls.py中
path('user-json1/',views.ApiView.as_view(),name="user1json"),
path('user-json2/',views.SerialazerView.as_view(),name="user2json"),
views.py中
from django.views import View
from django.http import JsonResponse,HttpResponse
class ApiView(View):
def get(self, request):
users = Server.objects.values()
return JsonResponse(list(users), safe=False)
from django.core import serializers
class SerialazerView(View):
def get(self,request):
users = UsersProfile.objects.all()
data = serializers.serialize('json',users)
return HttpResponse(data)
ajax请求 两种方法可以实现
在urls.py文件中
from django.views.generic import TemplateView #可以直接跳转网页
path('server-jQuery/',TemplateView.as_view(template_name="api/jQuery.html"),name="jQuer"),
path('server-axios/',TemplateView.as_view(template_name="api/vue-axios.html"),name="VueAxiox"),
1.jQuery方法
jQuery.html中
{% extends "base.html" %}
{% block content %}
<button id="btn" class="btn btn-success">获取数据</button>
<h1 id="title"></h1>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>id</th>
<th>主机名</th>
<th>内核</th>
<th>操作系统</th>
</tr>
</thead>
<tbody id="body" >
</tbody>
</table>
{% endblock %}
{% block script %}
<script>
("#title")
var tr_tg =("#btn").on('click',function(){
console.log("===>")
{res[0].host_name}</div>
title_tg.html(str_tag) // tags = '' n=0 for (let i of res){ n += 1 // tags =tags +
<tr>
// <th scope="row">{i.id}</td>
// <td>{i.kernel}</td>
// <td>{n}</th>
<td>{i.host_name}</td>
<td>{i.os_name}</td>
</tr>`)
}
// tr_tg.html(tags)
}
});
})
})
</script>
{% endblock %}
2.js的axios用Vue方法
{% verbatim %} {% endverbatim %}
目的是让在其中的代码的变量不被django所使用,交给vue来使用
vue-axios.html中
{% extends "base.html" %}
{% block content %}
<div id="app">
{% verbatim %}
<button id="btn" class="btn btn-success">获取数据</button>
<h1>Vue出现 {{ msg }}</h1>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>主机名</th>
<th>内核</th>
<th>操作系统</th>
</tr>
</thead>
<tbody id="body" >
<tr v-for="item in servers" :key="">
<td>{{ item.id }}</td>
<td>{{ item.host_name }}</td>
<td>{{ item.kernel }}</td>
<td>{{ item.os_name }}</td>
</tr>
</tbody>
</table>
{% endverbatim %}
</div>
{% endblock %}
{% block script %}
<script>
var app =new Vue({
el: "#app",
data: {
msg: '服务器信息',
servers: ''
},
mounted() {
axios.get("{% url 'api:user1json' %}",).then(
res => {
this.servers = res.data;
});
},
})
</script>
{% endblock %}
中间件
settings.py
'MyMiddleware.test_middleware.RejectIpMiddleware',
![](https://img.haomeiwen.com/i18938642/816ce59e2febe126.png)
from django.shortcuts import HttpResponse
class RejectIpMiddleware:
def init(self, get_response):
self.get_response = get_response
def __call__(self, request):
remote_ip = request.META['REMOTE_ADDR']
print(f"接收到请求后 --> 我在这里呀{remote_ip}--》调用视图前")
# return HttpResponse(f"{request.META['REMOTE_ADDR']}")
response = self.get_response(request)
print("调用视图后--》我在这里呀--》返回页面前")
return response
网友评论