简体   繁体   中英

What does 'request.GET.get' in an API creation do in Django and how does it work precisely?

I'm watching a lecture about Django. The lecturer explains everything wonderfully but didn't go into much detail into "an API I effectively created". This is my first time meddling with this so I'm a bit unsure.

What I don't understand is specifically this line request.GET.get("start") . How does one make that work in the index.html file (with embedded js script) by just using a fetch?

views.py

def posts(request):
    # Get start and end points
    start = int(request.GET.get("start") or 0)
    end = int(request.GET.get("end") or (start + 9))
    
    # Generate list of posts
    data = []
    for i in range(start, end + 1):
        data.append(f"Post #{i}")
    
    # Artificially delay speed of response
    time.sleep(1)

    # Return list of posts
    return JsonResponse({
        "posts": data
    })

index.html

    fetch(`/posts?start=${start}&end=${end}`)
    .then(response => response.json())
    .then(data => {
       data.posts.forEach(add_post);
    })

The request object contains information about the user's request. What data they've sent to the page, where they are coming from, etc.

request.GET contains the GET variables. These are what you see in your browser's address bar. The .get() method is a method used for dictionaries. What your snippet of code is doing is saying, " Get the value of a GET variable with name 'page ', and if it doesn't exist, return 1".

Likewise, you will see request.POST used when a user submits a form.

For the specific example posted: start = int(request.GET.get( "start" ) or 0) end = int(request.GET.get( "end" ) or (start + 9))

fetch( /posts?start=${start}&end=${end} )

eg. http://127.0.0.1:8000/posts?start=10&end=20 This will fetch post#10 to post#20 from the API.

You can change these start & end variable to first and last or anything else it would work same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM