'Proper way to integrate these functions into a main script
I am trying to write a script that will read the contents of multiple .xml files, make a webservice request, and log if that request was successful or not. As of right now I have 3 functions - one that outputs the contents of the folders for validation, one that reads the contents of the files, and one that makes the request from the contents of these files. On their own they work exactly as I need them to, but the purpose of my project is to automate this process so that I can put the files in this specified directory and run the script to make all the webservice calls. How would I structure my def main() function to accomplish this?
import os
import requests
from requests.auth import HTTPBasicAuth
from bs4 import BeautifulSoup
RESEND_FILES = os.path.join("resend_files")
def main():
get_xml_list()
read_file()
resend(?)
def resend(data):
out = open('output.xml', 'w')
url = 'https://url.com/path/to/wsdl?wsdl'
headers = {'content-type': 'text/xml'}
response = requests.post(url,
data=data,
headers=headers,
verify=False,
auth=HTTPBasicAuth('user', 'pass')
)
out.write(response.text)
bs = BeautifulSoup(open("output.xml"), "xml")
xml_content = bs.prettify()
out.write(xml_content)
print(xml_content)
def get_xml_list():
for root, dirs, files in os.walk(RESEND_FILES):
level = root.replace(RESEND_FILES, '').count(os.sep)
indent = ' ' * 4 * level
print('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
print('{}{}'.format(subindent, f))
def read_file():
for dirPath, foldersInDir, fileName in os.walk(RESEND_FILES):
if fileName is not []:
for file in fileName:
loc = os.sep.join([dirPath, file])
txt = open(loc)
data = txt.read()
return data
if __name__ == "__main__":
main()
Solution 1:[1]
If you change read_file to be a generator function so that it can be iterated ..
def read_file():
for dirPath, foldersInDir, fileName in os.walk(RESEND_FILES):
if fileName is not []:
for file in fileName:
loc = os.sep.join([dirPath, file])
txt = open(loc)
data = txt.read()
yield data
Then in main you could have:
for data in read_file():
resend(data)
You may have to make other changes though.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wwii |
