为了账号安全,请及时绑定邮箱和手机立即绑定

使我的代码在阅读和性能方面更好

使我的代码在阅读和性能方面更好

阿波罗的战车 2021-09-23 09:12:28
我有一个 python django 代码,我想让它在阅读和性能方面变得更好,因为我想将它添加到我的业余项目中,而且我是 python 和 django 的新手。有人可以帮帮我吗from django.views import Viewfrom django.http import HttpResponsefrom django.contrib.gis.geoip2 import GeoIP2from .models import Victims, Urlg = GeoIP2()def Get_Ip(request):    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')    if x_forwarded_for:        ip = x_forwarded_for.split(',')[-1].strip()    else:        ip = request.META.get('REMOTE_ADDR')    return ipdef Get_Country(request):    ip = Get_Ip(request)    country = g.country('31.13.75.36')    return countrydef Get_Browser(request):    browser = request.META['HTTP_USER_AGENT']    return browserdef save_vistor_data(request, slug):    ip = Get_Ip(request)    country = Get_Country(request)    browser = Get_Browser(request)    _url = Url()    url = Url.objects.get(slug=slug)    victim = Victims(_url=url, ip_address=ip, country=country, browser=browser)    victim.save()    return HttpResponse('Done')
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

g = GeoIP2()

IP = '31.13.75.36'


def get_Ip(request):

    """Get IP.


    Notes:

        This function retrieves/gets IP's.


    Args:

        request:


    Returns:

        some object.


    Raises:

        ConnectionError.



    """

    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    try:

        ip = x_forwarded_for.split(',')[-1].strip()

    except Exception:

        ip = request.META.get('REMOTE_ADDR')

    return ip



def get_country(request):

    """Get country.


    """


    ip = Get_Ip(request)

    country = g.country(IP)

    return country


def get_browser(request):

    """Get Browser


    Notes:

        What should we know about this function.

        That is not already obvious.


    Args:

        request (type)


    Raises:


    Returns:


    """

    browser = request.META['HTTP_USER_AGENT']

    return browser


def save_vistor_data(request, slug):

    """Save visitor data to ...


    Notes:

        Where is the visitor data going?



    Args:

        request ():

        slug ():


    Returns:


    """

    ip = Get_Ip(request)

    country = Get_Country(request)

    browser = Get_Browser(request)


    _url = Url()

    url = Url.objects.get(slug=slug)


    victim = Victims(

        _url=url,

        ip_address=ip,

        country=country,

        browser=browser

    )


    victim.save()


    return HttpResponse('Done')


查看完整回答
反对 回复 2021-09-23
  • 1 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信