Capturing URL parameters in request.GET

后端 未结 13 868
说谎
说谎 2020-11-22 08:30

I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the

13条回答
  •  伪装坚强ぢ
    2020-11-22 08:48

    You have two common ways to do that in case your URL looks like that:

    https://domain/method/?a=x&b=y
    

    Version 1:

    If a specific key is mandatory you can use:

    key_a = request.GET['a']
    

    This will return a value of a if the key exists and an exception if not.

    Version 2:

    If your keys are optional:

    request.GET.get('a')
    

    You can try that without any argument and this will not crash. So you can wrap it with try: except: and return HttpResponseBadRequest() in example. This is a simple way to make your code less complex, without using special exceptions handling.

提交回复
热议问题