将请求的响应保存到文件

时间:2020-08-27 20:21:56

标签: python api

我正在使用邮递员来调用API。我的用例是我需要使用Python请求来调用api,并添加错误处理和电子邮件确认。我得到的答复应写入文件。我是python的新手,没有任何专业知识。有人可以帮忙吗?

这是我拥有的python请求代码

import { app, BrowserWindow, ipcMain } from 'electron';
import isDev from 'electron-is-dev';
import path from 'path';
import db from './database/database';

let mainWindow: BrowserWindow;

const createWindow = () => {
  mainWindow = new BrowserWindow({
    minWidth: 980,
    minHeight: 600,
    webPreferences: {
      nodeIntegration: true,
    },
    frame: false,
  });

  mainWindow.loadURL(
    isDev
      ? 'http://localhost:3000'
      : `file://${path.join(__dirname, "../build/index.html")}`
  );
  mainWindow.webContents.openDevTools();
};

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

ipcMain.on('mainWindow:close', () => {
  db.close();
  app.quit();
});

ipcMain.on('mainWindow:min', () => {
  mainWindow.minimize();
});

ipcMain.on('mainWindow:max', () => {
  if (mainWindow.isMaximized()) {
    mainWindow.unmaximize();
  }
  else {
    mainWindow.maximize();
  }
});

2 个答案:

答案 0 :(得分:0)

您可以通过以下操作将其写入文件:

import requests

url = "http://XXXX"

payload = {}
headers= {}

response = requests.request("GET", url, headers=headers, data = payload)

f = open('dir here', 'w')

f.write(response.text.encode('utf8'))
f.close()

答案 1 :(得分:0)

import requests

url = "http://XXXX"

payload = {}
headers= {}

response = requests.request("GET", url, headers=headers, data = payload)

print(response.text.encode('utf8'))


file = open("file_location.csv", 'a')
save = f"{response.text.encode('utf8')}"
file.write(save)
file.close()