Python在请求中使用时更改了变量

时间:2018-03-10 08:58:57

标签: python

它是一个奇怪的错误(我是python的新手),我希望我能解释一下。 我需要使用REST调用更新swarm堆栈并使用requests。我有一个yaml文件,我将其转换为字符串并放入请求主体。

yaml文件:

version: '3'
networks:
 ycf:
  driver: overlay
services:
 api:
  image: registry.gitlab.com/ycf/api/api:latest
  restart: always
  environment:
   - MONGODB_DB_URL=mongodb://mongodb:27017
   - MONGODB_USER=ycf
   - MONGODB_PSW=xxxx
   - AUTH_KEY=wrv9ghefiu
   - PASSWORD_KEY=xxxx
   - PORT=3000
  working_dir: /opt/api
  command: ./node_modules/yarn/bin/yarn.js prod
  networks:
   ycf:
  links:
   - mongodb
 app:
  image: registry.gitlab.com/ycf/app/app:latest
  restart: always
  networks:
   ycf:

转换后我有:

version: '3'\r\nnetworks:\r\n ycf:\r\n  driver: overlay\r\nservices:\r\n api:\r\n  image: registry.gitlab.com\/ycf\/api\/api:latest\r\n  restart: always\r\n  environment:\r\n   - MONGODB_DB_URL=mongodb:\/\/mongodb:27017\r\n   - MONGODB_USER=ycf\r\n   - MONGODB_PSW=xxxx\r\n   - AUTH_KEY=wrv9ghefiu\r\n   - PASSWORD_KEY=xxxx\r\n   - PORT=3000\r\n  working_dir: \/opt\/api\r\n  command: .\/node_modules\/yarn\/bin\/yarn.js prod\r\n  networks:\r\n   ycf:\r\n  links:\r\n   - mongodb\r\n app:\r\n  image: registry.gitlab.com\/ycf\/app\/app:latest\r\n  restart: always\r\n  networks:\r\n   ycf:\r\n

我做了这个步骤:

# Convert swarm-stack.yml to string and assign the result to "compose" variable
run = subprocess.run(['./jsonstring.py', 'swarm-stack.yml'], stdout=subprocess.PIPE)
compose = run.stdout.decode('utf-8')
print(compose) # this result is identical to the string written above 
url_update = 'http://www.example.com:9000/api/endpoints/1/stacks/id'
# Then use variable "compose" to build the body of requests
body_update = {'StackFileContent' :'%s'%(compose)}

body_update现在是:

{'StackFileContent': "version: '3'\\r\\nnetworks:\\r\\n ycf:\\r\\n  driver: overlay\\r\\nservices:\\r\\n api:\\r\\n  image: registry.gitlab.com\\/ycf\\/api\\/api:latest\\r\\n  restart: always\\r\\n  environment:\\r\\n   - MONGODB_DB_URL=mongodb:\\/\\/mongodb:27017\\r\\n   - MONGODB_USER=ycf\\r\\n   - MONGODB_PSW=xxxx\\r\\n   - AUTH_KEY=wrv9ghefiu\\r\\n   - PASSWORD_KEY=xxxx\\r\\n   - PORT=3000\\r\\n  working_dir: \\/opt\\/api\\r\\n  command: .\\/node_modules\\/yarn\\/bin\\/yarn.js prod\\r\\n  networks:\\r\\n   ycf:\\r\\n  links:\\r\\n   - mongodb\\r\\n app:\\r\\n  image: registry.gitlab.com\\/ycf\\/app\\/app:latest\\r\\n  restart: always\\r\\n  networks:\\r\\n   ycf:\\r\\n\n"}

反斜杠被添加到现有的,并且\ n被添加到字符串的末尾,这会导致500错误。我使用python 3.5.2,任何想法?

由于

1 个答案:

答案 0 :(得分:1)

我想也许您可以尝试不同的解码选项。

在这种情况下,unicode_escape可能有所帮助..

compose = run.stdout.decode('unicode_escape')