码迷,mamicode.com
首页 > 编程语言 > 详细

python requests常见使用方法记录

时间:2021-06-02 16:41:52      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:poi   dom   pat   date   from   methods   get post   efault   source   

requests是py用来进行http和https请求的支持库,在进行http或者https请求时能够很方便的构造对应请求,下面就以get  post方法以及带请求体  不带请求体 ,headers   session鉴权等使用方法进行说明。

下面示例是以华为云华北-北京四  vpc为操作对象,分别进行鉴权   查询vpc 和创建vpc的。具体api格式可以登录华为云官网查看

示例中账号密码信息需要根据自己的账号信息填写

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests

URI_scheme = "https://"
BJ4_ED = "iam.cn-north-4.myhuaweicloud.com"
JSON_H = {"Content-Type": "application/json"}
TOKEN_H = {"X-Auth-Token": ""}


def jointURI(resource_path, uri_scheme=URI_scheme, endPoint=BJ4_ED):
    #拼接url
    return uri_scheme+endPoint+resource_path

def postToken(resource_path, endPoint, username, password, domainname, projectName):
    #请求用户token
    url = jointURI(resource_path, endPoint=endPoint)
    headers = JSON_H
    jsonBody = {
                    "auth": {
                        "identity": {
                            "methods": [
                                "password"
                            ],
                            "password": {
                                "user": {
                                    "name": "%s" % username,
                                    "password": "%s" % password,
                                    "domain": {
                                        "name": "%s" % domainname
                                    }
                                }
                            }
                        },
                        "scope": {
                            "project": {
                                "name": "%s" % projectName
                            }
                        }
                    }
                }
    #请求体为json格式时使用json形参进行传递
    res = requests.post(url=url, headers=headers, json=jsonBody)
    TOKEN_H["X-Auth-Token"] = res.headers[X-Subject-Token]
    return res

def getVpcList(endPoint, projectId, queryStr=None):
    #使用headers鉴权获取用户vpc列表
    resource_path = "/v1/%s/vpcs" % projectId
    #get方法如果有queryStr则进行拼接,一般与url使用?间隔
    if queryStr is None:
        url = jointURI(resource_path, endPoint=endPoint)
    else:
        url = jointURI(resource_path, endPoint=endPoint)
        url += queryStr
    headers = {}
    for val in [JSON_H, TOKEN_H]:
        headers.update(val)
    #正常http请求有url和headres传参,headers为字典格式
    res = requests.get(url=url, headers=headers)
    return res

def getVpcListFromSession(endPoint, projectId, queryStr=None):
    #使用session进行鉴权获取用户vpc列表
    resource_path = "/v1/%s/vpcs" % projectId
    if queryStr is None:
        url = jointURI(resource_path, endPoint=endPoint)
    else:
        url = jointURI(resource_path, endPoint=endPoint)
        url += queryStr
    headers = {}
    for val in [JSON_H, TOKEN_H]:
        headers.update(val)
    #创建session对象,并更新session的headers信息,将token信息在session中传递
    mySession = requests.session()
    mySession.headers.update(headers)
    #使用session对象进行请求,session已经更新了headers所以请求参数不再需要heasers
    res = mySession.get(url=url)
    return res

def getVpcListFromCookies(endPoint, projectId, queryStr=None):
    #使用cookies鉴权获取用户vpc列表
    resource_path = "/v1/%s/vpcs" % projectId
    if queryStr is None:
        url = jointURI(resource_path, endPoint=endPoint)
    else:
        url = jointURI(resource_path, endPoint=endPoint)
        url += queryStr
    headers = {}
    for val in [JSON_H, TOKEN_H]:
        headers.update(val)
    #创建session对象,并更新session的cookies信息,将token在cookies中传递
    mySession = requests.session()
    mySession.cookies.update(headers)
    #使用session对象进行请求,session已经更新了headers所以请求参数不再需要heasers。服务方不支持这种鉴权方式,返回401。用法就是这样
    res = mySession.get(url=url)
    return res

def createVpc(endPoint, projectId, name, cidr, description="default", enterprise_project_id="0"):
    #带请求体的请求示例
    resource_path = "/v1/%s/vpcs" % projectId
    url = jointURI(resource_path, endPoint=endPoint)
    headers = {}
    for val in [JSON_H, TOKEN_H]:
        headers.update(val)
    jsonBody = {
                    "vpc": {
                        "name": "%s" % name,
                        "description": "%s" % description,
                        "cidr": "%s" % cidr,
                        "enterprise_project_id": "%s" % enterprise_project_id
                    }
                }
    #带url headers requestbody的请求传参
    res = requests.post(url=url, headers=headers, json=jsonBody)
    return res

if __name__ == "__main__":
    #使用header鉴权进行get post请求
    postToken("/v3/auth/tokens", "iam.cn-north-4.myhuaweicloud.com", "用户名", "用户密码", "账号", "cn-north-4")
    res = getVpcList("vpc.cn-north-4.myhuaweicloud.com", "项目id")
    #newVpc = createVpc("vpc.cn-north-4.myhuaweicloud.com", "项目Id", "createVpc1", "10.0.0.0/16")
    #print(newVpc.json()["vpc"]["id"])
    #使用session鉴权进行get post请求
    vpclist = getVpcListFromSession("vpc.cn-north-4.myhuaweicloud.com", "项目id")
    for obj in vpclist.json()[vpcs]:
        print(obj[id])
    vpclist = getVpcListFromCookies("vpc.cn-north-4.myhuaweicloud.com", "项目id")
    for obj in vpclist.json()[vpcs]:
        print(obj[id])

 

python requests常见使用方法记录

标签:poi   dom   pat   date   from   methods   get post   efault   source   

原文地址:https://www.cnblogs.com/flags-blog/p/14826853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!