从BaseHTTPHandler解析http GET和POST参数? [英] Parse http GET and POST parameters from BaseHTTPHandler?

查看:2941
本文介绍了从BaseHTTPHandler解析http GET和POST参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自BaseHTTPServer模块的BaseHTTPHandler似乎没有提供任何方便的方式来访问http请求参数。解析路径中的GET参数和请求体中的POST参数的最佳方法是什么?

BaseHTTPHandler from the BaseHTTPServer module doesn't seem to provide any convenient way to access http request parameters. What is the best way to parse the GET parameters from the path, and the POST parameters from the request body?

现在,我正在使用它来进行GET:

Right now, I'm using this for GET:

def do_GET(self):
    parsed_path = urlparse.urlparse(self.path)
    try:
        params = dict([p.split('=') for p in parsed_path[4].split('&')])
    except:
        params = {}

这适用于大多数情况,但我想要更强大的东西来正确处理编码和空参数等情况。理想情况下,我想要一些小而独立的东西,而不是一个完整的Web框架。

This works for most cases, but I'd like something more robust that handles encodings and cases like empty parameters properly. Ideally, I'd like something small and standalone, rather than a full web framework.

推荐答案

你可以试试 Werkzeug 模块,基础Werkzeug库不是太大,如果需要的话你可以简单地提取这段代码就可以了。

You could try the Werkzeug modules, the base Werkzeug library isn't too large and if needed you can simply extract this bit of code and you're done.

url_decode 方法返回一个MultiDict并且有编码支持:)

The url_decode method returns a MultiDict and has encoding support :)

urlparse.parse_qs 方法相反,Werkzeug版本负责:

As opposed to the urlparse.parse_qs method the Werkzeug version takes care of:


  • 编码

  • 多个值

  • 排序顺序

如果您不需要这些(或在编码的情况下,使用Python 3),请随意使用内置解决方案。

If you have no need for these (or in the case of encoding, use Python 3) than feel free to use the built-in solutions.

这篇关于从BaseHTTPHandler解析http GET和POST参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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