我一直在编写 API 过程来测试使用 JwToken 身份验证发布到 http RestAPI。在这种情况下,它用于患者管理系统,我正在生成一个约会。 API 业务规则不允许同一时间重复预订。
我正在使用 python 3.5.3 虚拟环境(在 pycharm IDE 中编写)并使用 Pytest 框架运行我的测试。 还使用 PyJWT 1.5.2。 ,请求 2.18.3,simplejson 3.11.1 和 urllib3 1.22 已安装(我假设请求正在使用 urllib3)。我使用的是 simplejson.dumps 而不是普通的 json.dumps,因为虚拟环境没有那个库,我在添加它时遇到了麻烦。据我所知,simplejson 对转储过程具有相同的功能。
使用下面的代码,我发现我可以运行 requests.post 调用以成功传送 Json 数据有效负载并生成一个帖子,但随后它似乎执行了第二个帖子,生成了 409 冲突错误。我可以访问相应 api 服务器上的日志数据库,可以看到它实际上已经尝试发布两次,但我无法弄清楚为什么会发生这种情况,我认为请求库中的某些内容被调用了两次.可能是由于我发布的 Json。
输出看起来像这样:
https://targerserver.url.com.au/API/Core/v2.1/appointment/
200
{'statusMessages': [], 'appointment': {'startDateTime': '2017-08-15T11:00:00 +10:00', 'appointmentReferenceNumber': '39960337', 'notes': '', 'clients': [{'clientId': 'abeff2be-ce6e-4324-9b57-e28ab7967b6c'}], 'status': 'Booked', 'locationId': 'd8d4fe7c-765a-46a3-a389-54ce298a27e9', 'notifyPractitioner': False, 'endDateTime': '2017-08-15T11:30:00 +10:00', 'subject': 'Jim Beam ', 'appointmentId': '08b37ce3-25e1-4e2a-9bb7-9ec2d716f83b', 'practitioner': {'practitionerId': 'a630f4ad-8b4b-4e06-8cee-7db56ba8b9bf'}}}
collected 1 item
test_PMSAPI_availability.py https://targerserver.url.com.au/API/Core/v2.1/appointment/
409
我的 Json 需要一个对象(它是一个字典)以及另一个字段的键列表(其中有一个条目),我想知道请求库是否没有处理这个。这是 json 的示例
payload_str = {"startDateTime":"2017-08-15T11:00+10:00","endDateTime":"2017-08-15T11:30+10:00","practitioner": {"practitionerId":"a630f4ad-8b4b-4e06-8cee-7db56ba8b9bf"}, "locationId":"d8d4fe7c-765a-46a3-a389-54ce298a27e9","clients":[{"clientId":"abeff2be-ce6e-4324-9b57-e28ab7967b6c"}]}
我有类似的代码可用于同一系统上的 Get 调用,但发布 Json 似乎确实存在问题。我们有其他工具可以调用相同的 API 端点,但似乎没有这个问题。日志表明我提供的 JSON 数据与来自具有相同数据的另一个工具的数据相同。
我从输出中看到的是在初始响应中收到成功的 200 代码,但是如果查询 response.status_code 它已变成 409 响应。我还尝试不对响应执行任何操作,以防导致请求重新查询并产生冲突。
我的代码是这样的:
import jwt
import _datetime
import requests
import simplejson
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from string import Template
def app_undertest_credentials(keyname):
app_credentials = {'app_consumer_id': 'MyTestApp',
'app_consumer_secret': 'where my secret goes',
'app_access_token': 'where my access token goes',
'base_url': 'https://targerserver.url.com.au'
}
return app_credentials.get(keyname)
def end_points_dict(keynameStr, versionStr):
end_points = {'location': '/API/Core/$version/location/',
'practitioner': '/API/Core/$version/practitioner/',
'availabilityslot': '/API/Core/$version/AvailabilitySlot/',
'client': '/API/Core/$version/client/',
'healthfundproviderlist': '/API/Core/$version/healthfundproviderlist/',
'timezone': '/API/Core/$version/timezone/',
'clientgroup': '/API/Core/$version/clientgroup/',
'appointment': '/API/Core/$version/appointment/'
}
lower_keynameStr = keynameStr.lower()
url_extension_no_version = Template(end_points.get(lower_keynameStr))
url_extension_with_version = url_extension_no_version.safe_substitute(version=versionStr)
return url_extension_with_version
def test_api_appointment_post():
# Set Client app credentials
app_consumer_id = app_undertest_credentials('app_consumer_id')
app_consumer_secret = app_undertest_credentials('app_consumer_secret')
app_access_token = app_undertest_credentials('app_access_token')
base_url = app_undertest_credentials('base_url')
end_point_url_sfx_str = end_points_dict('Appointment', 'v2.1')
httpmethod = 'POST'
# Create dictionary for json post payload
data_payload = {'startDateTime':'2017-08-15T11:00+10:00',
'endDateTime':'2017-08-15T11:30+10:00',
'practitioner': {'practitionerId':'a630f4ad-8b4b-4e06-8cee-7db56ba8b9bf'},
'locationId': 'd8d4fe7c-765a-46a3-a389-54ce298a27e9',
'clients': [{'clientId':'abeff2be-ce6e-4324-9b57-e28ab7967b6c'}]
# Create claims dictionary payload for generation of JwToken
claims = {
'iss': 'http://myappsdomain.com.au',
'aud': 'https://targetservers.domain.com.au',
'nbf': _datetime.datetime.utcnow(),
'exp': _datetime.datetime.utcnow() + _datetime.timedelta(seconds=60),
'consumerId': app_consumer_id,
'accessToken': app_access_token,
'url': base_url + end_point_url_sfx_str,
'httpMethod': http_method
}
#create jwtoken and then convert to string
encoded_jwt_byte = jwt.encode(claim_payload, app_consumer_secret, algorithm='HS256')
jwt_str = encoded_jwt_byte.decode()
#Create authentication header
headers = {'Authorization': 'JwToken' + ' ' + jwt_str, 'content-type': 'application/json'}
uri = base_url + end_point_url_sfx_str
response = requests.post(uri, headers=headers, json=datapayload)
print(response.status)
print(response.json())
response.close()
我正在考虑使用 wireshark 来确定我的调用实际发送了什么,但我怀疑它只会告诉我调用被发送了两次
请您参考如下方法:
Comment: But I require a base64 encoded string for the sending the api requrest.
关于来源
segments.append(base64url_encode(signature))
return base64.urlsafe_b64encode(input).replace(b'=', b'')
return b'.'.join(segments)
全部为 base64 并以 bytes 形式返回。所以你应该没问题使用
jwt_str = str(encoded_jwt_byte)
抱歉,不能使用PyJWT。
尝试使用 python_jwt 并按预期工作。
使用 Python:3.4.2 - requests:2.11.1 测试
你真的需要encode(...然后decode()吗?
#create jwtoken and then convert to string
encoded_jwt_byte = jwt.encode(claim_payload, app_consumer_secret, algorithm='HS256')
jwt_str = encoded_jwt_byte.decode()
jwt_str 不会和claim_payload 一样吗?
