fetch_dcm.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. """
  3. 下载需要登录才能访问的 DICOM 文件
  4. """
  5. import requests
  6. from pathlib import Path
  7. # =========== 按需修改 ===========
  8. USERNAME = 'admin'
  9. PASSWORD = '123456'
  10. # 如需忽略自签名证书,把 VERIFY 设成 False
  11. VERIFY = True
  12. # ================================
  13. # BASE_URL = 'http://192.168.11.12:6001/dr/api/v1'
  14. BASE_URL = 'http://101.43.219.60:7700/dr/api/v1'
  15. login_url = f'{BASE_URL}/pub/login'
  16. file_url = f'{BASE_URL}/auth/image/dcm/DemoImage.dcm'
  17. local_file = Path('DemoImage.dcm')
  18. sess = requests.Session()
  19. sess.headers.update({'User-Agent': 'python-requests/2.x'})
  20. # 1. 登录
  21. login_payload = {
  22. 'username': USERNAME,
  23. 'password': PASSWORD
  24. }
  25. resp = sess.post(login_url, json=login_payload, verify=VERIFY, timeout=10)
  26. print(resp.text)
  27. resp.raise_for_status()
  28. # 2. 先 HEAD 看文件信息
  29. head = sess.head(file_url)
  30. print('[HEAD]', head.status_code, head.headers)
  31. # 如果你的接口返回 {"token": "xxxx"},可以存下来备用
  32. print('登录成功,获取 token...')
  33. print(resp.json()['data']['token'])
  34. token = resp.json()['data']['token']
  35. sess.headers.update({'Authorization': f'Bearer {token}'})
  36. sess.headers.update({'Language': f'en'})
  37. sess.headers.update({'Product': f'DROS'})
  38. sess.headers.update({'Source': f'Electron'})
  39. # 2. 下载文件
  40. print('正在下载文件...')
  41. with sess.get(file_url, stream=True, verify=VERIFY, timeout=3000) as r:
  42. r.raise_for_status()
  43. with open(local_file, 'wb') as f:
  44. for chunk in r.iter_content(chunk_size=8192):
  45. if chunk: # 过滤 keep-alive
  46. f.write(chunk)
  47. print(f'下载完成:{local_file.absolute()}')