本篇我们来学习HTTP中常见的请求方法,一般我们都知道有GET和POST两种,其他的可能就记得不是很清楚。其实,和数据库操作一样,HTTP请求也有好几种,至少是有增删改查这四种方法。为了弄清楚这几种方法和方法的含义,我直接从别的网上截图贴到这里。
看完之后,很多人会说GET就是用来获取信息的,POST是用来发送数据到服务器,例如提交表单。而HEAD这个请求头部报头速度非常快,很多黑客会利用这个来攻击,获取一些信息。PUT是修改服务器上存在的文档并更新,DELETE就是从服务器上删除数据。我想说的是,POST方法不一定是用在提交数据这方面,我在数据查询,获取查询结果,也遇到过有的开发使用的是POST方法。
1.requests举例,获取github上用户信息
大家应该都听说过Github,这个网站,开发者大牛集结地。我们本系列的requests也是在github上下载的。github网站提供了一些API接口,接口文档链接是https://developer.github.com/v3/, 我们今天练习的是用户相关的接口,所以具体用户相关接口文档描述链接是:https://developer.github.com/v3/。在开始之前,你需要去github上创建一个账号,才能继续跟着我往下走。我本来不想这样做,但是实在找不到公开接口的网站,有些天气预报网站接口只能提供GET方法,但是我们希望GET和POST都学习,实战一下,最终还是选择了Github网站。不多说,先去注册一个账号吧,国外的网站,访问可能比较慢。
假如你准备好了,我在github上有一个账号:Anthonyliu86,根据下面图,我们来仿照写一个获取自己账号信息的一个GET请求例子。
在代码编辑工具,新建一个test_get.py,我用的是Pycharm,具体代码如下:
import requests
import json
URL = 'https://api.github.com'
def build_uri(endpoint):
return '/'.join([URL, endpoint]) # 主要作用是拼接接口请求地址
def better_output(json_str):
return json.dumps(json.loads(json_str), indent=4) #采用json里面提供方法打印出来,格式更好看
def request_method():
response = requests.get(build_uri('users/Anthonyliu86')) #调用get方法,注意用户名这个地方写法,没有图片中冒号
print(better_output(response.text)) #调用json更好格式输出
if __name__ == '__main__':
request_method()
测试,运行一下,由于是github服务器在国外,所以,请求回来并显示数据,会很慢,好像有两三分钟,具体看你网速。
{
"login": "Anthonyliu86",
"id": 24694636,
"avatar_url": "https://avatars3.githubusercontent.com/u/24694636?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Anthonyliu86",
"html_url": "https://github.com/Anthonyliu86",
"followers_url": "https://api.github.com/users/Anthonyliu86/followers",
"following_url": "https://api.github.com/users/Anthonyliu86/following{/other_user}",
"gists_url": "https://api.github.com/users/Anthonyliu86/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Anthonyliu86/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Anthonyliu86/subscriptions",
"organizations_url": "https://api.github.com/users/Anthonyliu86/orgs",
"repos_url": "https://api.github.com/users/Anthonyliu86/repos",
"events_url": "https://api.github.com/users/Anthonyliu86/events{/privacy}",
"received_events_url": "https://api.github.com/users/Anthonyliu86/received_events",
"type": "User",
"site_admin": false,
"name": null,
"company": null,
"blog": "",
"location": null,
"email": null,
"hireable": null,
"bio": null,
"public_repos": 1,
"public_gists": 0,
"followers": 1,
"following": 0,
"created_at": "2016-12-21T09:20:51Z",
"updated_at": "2017-08-26T09:02:16Z"
}
上面返回来的就是我账号的信息,我们发现,这个请求没有用到参数,用户名称直接在uri后面。下一篇,介绍带参数的请求。