简体   繁体   English

Python URL请求

[英]Python URL Requests

Let me start by saying I am extremely new to Python, but I am familiar with other programming languages. 让我先说我非常新的Python的开始,但我熟悉的其他编程语言。 Before I dive into this project, I need to ask a few questions. 在深入研究这个项目之前,我需要问几个问题。

I need to be able to make URL GET, PUT, POST, and DELETE requests straight out of Python. 我需要能够直接从Python发出URL GET,PUT,POST和DELETE请求。

I'll be writing a library for specific use cases of those functions and I don't want users to have to go installing external libraries (like "Requests"). 我将为这些函数的特定用例编写一个库,我不希望用户必须安装外部库(如“请求”)。

What is the best way to do this, urllib.request? 什么是最好的方法,urllib.request?

Thank you for educating me. 谢谢你教育我。

I need to be able to make URL GET, PUT, POST, and DELETE requests straight out of Python. 我需要能够直接从Python发出URL GET,PUT,POST和DELETE请求。 ... What is the best way to do this, urllib2? ...最好的方法是什么,urllib2?

Since urllib.request.urlopen() is hard-wired to GET or POST, you will need http.client.HTTPConnection instead: 由于urllib.request.urlopen()硬连接到GET或POST,因此您需要http.client.HTTPConnection

import http.client
import pprint

conn = http.client.HTTPConnection('www.jython.org')
c = conn.request('HEAD', '/index.html')
r = conn.getresponse()

pprint.pprint(r.getheaders())
print('Size of body:', len(r.read()))

The technique gets you "closer to the metal" and gives more control, but it loses all the comforts of urllib.request and its various highlevel services (like following redirects). 该技术让你“更接近金属”并提供更多控制,但它失去了urllib.request及其各种高级服务(如跟随重定向)的所有舒适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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