实现一个计数器,用django计数请求 [英] implementing a counter that counts requests with django

查看:127
本文介绍了实现一个计数器,用django计数请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是尝试使用Django,
我如何实现一个计数器来存储数据库中服务的请求计数?

I'm just trying with Django, how can i implement a counter that stores the count of requests served on the database?

我想计算GET请求,我该怎么办?

I want to count the GET requests, what should I do make it work?

我的模板,

<form action="/submit/" method="GET">
    <input type="text" name="q">
    <input type="submit" value="Submit">
</form>

我的观点

def result(request):
    name = request.GET['q']
    message = 'your name is %r ' % name
    return render(request, 'result.html', {'message': message})

我想计算次数我按提交按钮。我应该启动一个新的应用程序 counter 还是存在其他实现计数器的方法?

I want to count the number of times i press the submit button. should I start a new app counter or there exist some other way to implement a counter?

推荐答案

这可能有点混乱,但是您应该从会话中获得基本概念,而不是get方法
model / .py吸引朋友的模型

This might be a little messed up but you should get the basic concept you get it from the session not the get methods model/.py the model that tracts your friend

friend = models.ForeignKey("self", related_name="referral", null=True, blank=True) 

view.py这是您计数的朋友

view.py this is how many friends you have counted

cool_obj = cool.objects.get(ref_id=ref_id)
obj = cool.objects.filter(friend=cool_obj)
count = cool_obj.referral.all().count()

这是如何通过中间件获取内容的方法

this how you get your stuff through the middleware

def home(request):
try:
    cool_id = request.session['cool_id_ref']
    obj = cool.objects.get(id=cool_id)
except:
    obj = None 
form = CoolJoin(request.POST or None)
if form.is_valid():
    new_cool = form.save(commit=False)
    email = form.cleaned_data['email']
    new_cools, created = cool.objects.get_or_create(email=email)
    if created:
        new_cools.ref_id = get_ref_id()
        if not obj == None:
            new_cools.friend = obj
        new_cools.ip_adress = get_ip(request)
        new_cools.save()

    return HttpResponseRedirect("/%s" %(new_cools.ref_id))
context = {"form": form}
template = "home.html"
return render(request, template, context)

中间件/

class ReferMiddleware():
def process_request(self, request):
        ref_id = request.GET.get("ref")
        try:
            obj = cool.objects.get(ref_id = ref_id)
        except:
            obj = None   
        if obj:
            request.session['cool_id_ref'] = obj.id

这篇关于实现一个计数器,用django计数请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆