zoukankan      html  css  js  c++  java
  • 接口测试-模拟网络请求

    1 发送HTTP请求

    postman构建HTTP请求:

    1. Method(请求方法)
    2. URL: url参数 query string/ endoceURIComponet
    3. Headers(请求头)
    4. 消息体:
        • application/x-www-form-urlencoded
        • application/json
        • application/xml
        • application/form-data     

    1.1 requests模块

    安装:pip install requests

    导入模块:import requests

    1.2 请求与响应

    r = requests.方法(url,headers,data,......)
    r = requests.get('https://github.com/timeline.json')
    r = requests.post("http://httpbin.org/post")
    r = requests.put("http://httpbin.org/put")
    r = requests.delete("http://httpbin.org/delete")
    r = requests.head("http://httpbin.org/get")
    r = requests.options("http://httpbin.org/get")

    请求后获取常用的响应结果:

    r.headers       #获取返回的头信息
    r.text          #获取返回额主体
    r.cookies        #获取返回的cookie
    r.status_code    #获取返回的状态码

    1.2.1 请求参数

    详情可参考:https://www.cnblogs.com/shapeL/p/9037035.html

    常用post请求,请求正文是raw,可传入json格式文本:

    import requests,json
    test_url='http://111.230.173.51:2018/app'
    h ={
        'sid':'1010',
        'partnerNo':'15601',
        'Content-Type':'application/json',
    }
    body ={
      "serviceHeader":{
        "sessionId":"",
        "userId":"",
        "deviceId":"990009263463478",
        "osType":"1",
        "version":"",
        "lang":""
      },
      "serviceBody":{}
    }
    response = requests.post(test_url,headers =h,data=json.dumps(body))  #另一种写法json=body
    print(response.status_code)
    print(response.headers)
    print(response.text)  #response = json.loads(response.text) 前者类型为字符串,后者为字典,推荐使用后者

    2 发送HTTPS请求

    url ='https//www.zhihu.com' #只需要修改url
    response = requests.get(url,headers=h,cookie=c,params=p)

    3 发送WebSocket请求

    3.1 WebSocket模块

    安装: pip install websocket

                pip install websocket-client

    导入模块: import websocket

    3.2 请求与响应

    3.2.1 建立连接,URL以ws开头

    变量 = websocket.create_connection(url)

    3.2.12 发送数据

    变量.send(发送内容)

    3.2.3 接收数据

    变量.recv()

    3.3 请求实例

    import websocket
    url = 'ws://www.xxx.com/xxxx'
    ws = websocket.create_connection(url)
    ws.send("{"request":1111,“service”:1001,"name":"xxxx"}")
    new.msg1 = ws.recv()
    print (new.msg1)
    ws.send("{"request":1111,“service”:1003,"name":"xx","message":"1111"}")
    new.msg2= ws.recv()
    print (new.msg2)

    附:

    1、django安装:pip install requests;

    2、配置django环境变量:D:pythonScripts;

    3、在工作空间目录下用django创建项目:django-admin startproject 项目名称;

    目录结构如下:

    ├── HelloWorld
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── manage.py
    说明:
    • HelloWorld: 项目的容器。
    • manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。
    • HelloWorld/__init__.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
    • HelloWorld/settings.py: 该 Django 项目的设置/配置。
    • HelloWorld/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。
    • HelloWorld/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。

    4、Django提倡基于应用作为单位进行开发,创建djangoapp:进入HelloWorld目录下执行django-admin startapp say_hello命令;

    ├── HelloWorld
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── manage.py
    └── say_hello
        ├── admin.py
        ├── apps.py
        ├── __init__.py
        ├── migrations
        │   └── __init__.py
        ├── models.py
        ├── tests.py
        └── views.py

    5、say_hello目录下,新建一个templates目录,其中创建LoginPage.html页面;

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>login</title>
    </head>
    <body>
    <form action="/say_hello/" method="POST">      #action后面是应用名称
        <h1>用户名:<input name="username"></h1>
        <h1>密码:<input name="password"></h1>
        <input type="submit" value="登录">
    </form>>
    </body>
    </html>

    6、添加控制器:在say_hello目录下的views.py中添加函数;

    使用render_to_response函数,该函数会返回一个对象,对象有经过渲染的html。

    from django.http.response import HttpResponse
    from django.shortcuts import render_to_response
    
    def Login(request):
        if request.method =='POST':
            username = request.POST.get('username')
            return  HttpResponse(username)
        else:
            return render_to_response('LoginPage.html')

    7、设置一下url映射,打开HelloWorld目录下的urls.py,添加映射;

    from django.contrib import admin
    from django.urls import path
    from say_hello import views
    from django.urls import re_path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path(r'^login/',views.Login)
    ]

    django2.0使用path,不是url,可以用re_path代替原来的url。若要用path可参考:https://www.cnblogs.com/feixuelove1009/p/8399338.html

    8、注册应用,打开settings.py文件,在INSTALLED_APPS列表中添加一项"say_hello";

    找不到templates目录需要添加:

    'DIRS': [os.path.join(BASE_DIR,'templates')],

    遇到安全问题需要注释:

    #'django.middleware.csrf.CsrfViewMiddleware',

    9、启动服务器python manage.py runserver,在浏览器输入localhost:8000/login。

  • 相关阅读:
    SQL Server TSQL高级查询
    ado.net
    Apache配置详解(最好的APACHE配置教程)
    CrystalReport for vs2010 水晶报表的发布问题以及捆绑发布
    Rails 疑难解决
    [转]if 命令示例详解
    How To Deploy on Bluehost
    CustomActionData 属性 [Visual Studio 中的部署]
    BlueHost下部署rails app经验
    Using Ruby On Rails on Bluehost
  • 原文地址:https://www.cnblogs.com/cirr-zhou/p/9368396.html
Copyright © 2011-2022 走看看