Python 中的简单 URL GET/POST 函数 [英] Simple URL GET/POST function in Python

查看:61
本文介绍了Python 中的简单 URL GET/POST 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在 Google 上搜索它,但我想要一个可以执行此操作的函数:

接受 3 个参数(或更多,无论如何):

  • 网址
  • 参数字典
  • POST 或 GET

返回结果和响应代码.

是否有一个片段可以做到这一点?

解决方案

请求

https://github.com/kennethreitz/requests/

以下是几种常用的使用方法:

导入请求url = 'https://...'有效载荷 = {'key1': 'value1', 'key2': 'value2'}# 得到r = requests.get(url)# 使用 URL 中的参数 GETr = requests.get(url, params=payload)# POST 表单编码数据r = requests.post(url, data=payload)# 使用 JSON 发布导入jsonr = requests.post(url, data=json.dumps(payload))# 响应、状态等r.textr.status_code

httplib2

https://github.com/jcgregorio/httplib2

<预><代码>>>>从 httplib2 导入 Http>>>从 urllib 导入 urlencode>>>h = Http()>>>data = dict(name="Joe", comment="一个测试评论")>>>resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))>>>分别{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent','server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT','内容类型':'文本/html'}

I can't seem to Google it, but I want a function that does this:

Accept 3 arguments (or more, whatever):

  • URL
  • a dictionary of params
  • POST or GET

Return me the results, and the response code.

Is there a snippet that does this?

解决方案

requests

https://github.com/kennethreitz/requests/

Here's a few common ways to use it:

import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}

# GET
r = requests.get(url)

# GET with params in URL
r = requests.get(url, params=payload)

# POST with form-encoded data
r = requests.post(url, data=payload)

# POST with JSON 
import json
r = requests.post(url, data=json.dumps(payload))

# Response, status etc
r.text
r.status_code

httplib2

https://github.com/jcgregorio/httplib2

>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
 'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT', 
 'content-type': 'text/html'}

这篇关于Python 中的简单 URL GET/POST 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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