从 URL 中检索参数

编程入门 行业动态 更新时间:2024-10-25 00:31:20
本文介绍了从 URL 中检索参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个像下面这样的 URL,我如何解析查询参数的值?例如,在这种情况下,我想要 some_key 的值.

Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of some_key .

/some_path?some_key=some_value'

我在我的环境中使用 Django;request 对象上是否有可以帮助我的方法?

I am using Django in my environment; is there a method on the request object that could help me?

我尝试使用 self.request.get('some_key') 但它没有像我希望的那样返回值 some_value.

I tried using self.request.get('some_key') but it is not returning the value some_value as I had hoped.

推荐答案

这并非特定于 Django,而是适用于一般的 Python.对于 Django 的特定答案,看到这个来自@jball037

This is not specific to Django, but for Python in general. For a Django specific answer, see this one from @jball037

Python 2:

import urlparse url = 'www.example/some_path?some_key=some_value' parsed = urlparse.urlparse(url) captured_value = urlparse.parse_qs(parsed.query)['some_key'][0] print captured_value

Python 3:

from urllib.parse import urlparse from urllib.parse import parse_qs url = 'www.example/some_path?some_key=some_value' parsed_url = urlparse(url) captured_value = parse_qs(parsed_url.query)['some_key'][0] print(captured_value)

parse_qs 返回一个列表.[0] 获取列表的第一项,因此每个脚本的输出为 some_value

parse_qs returns a list. The [0] gets the first item of the list so the output of each script is some_value

这是 Python 3 的parse_qs"文档

更多推荐

从 URL 中检索参数

本文发布于:2023-11-01 11:32:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!