I'm trying with a web application Flask/Python start a macro in excel, when the user press the button the behind process open an excel do a macro and return the result.
If I do this with the IDE Visual Studio 2015 there is not problem and the process works fine, when I try with IIS (Publish) I can navigate into the web application but when I press the button this error comes up:
Error occurred:
Traceback (most recent call last):
File "C:\inetpub\wwwroot\MyWebSite\wfastcgi.py", line 736, in main
result = handler(record.params, response.start)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File ".\QPX_Test\upload.py", line 62, in upload
process_excel.up_route(variable_forsave, 'C:\Tool_OP14\System\Main System FIndx', 'System','B1')
File ".\QPX_Test\process_excel.py", line 27, in up_route
xlApp = win32com.client.Dispatch('Excel.Application')
File "C:\Anaconda2\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\Anaconda2\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Anaconda2\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2147024891, 'Access is denied.', None, None)
StdOut:
StdErr:
I tried everything:
Security folder ( C:\inetpub\wwwroot) I added IUSR user with full permissions, same to PCNAME\IIS_IUSRS and my web application (app pool identity).
On the DCOMcnfg on Microsoft Excel I set on Launch and Activation Permissions the customize option and add privileges to:
- IUSR
- IIS_IUSRS
- Mywebsite (web app)
Here's part of the code but the essential part:
So this is the part wrote in jade for start the Python code:
.container-fluid
.row
.grid-12
.jumbotron
h1 Test Tool
p Testing for web application development
.row
.section.group
.col.span_2_of_3
h1 Step 1
p For select the Input Data File, please press the "Select Data Input" button
form(action='upload', method='post', enctype='multipart/form-data')
.table
input.filestyle(type='file', name = 'file', data-buttonname='btn-primary', data-buttonText= 'Select Data File', data-iconName= 'fa fa-database', data-buttonBefore='true', data-placeholder = 'No File')
.table
span.btn.btn-primary.btn-file
| Upload
span.fa.fa-cloud-upload.fa-1x.pull-left
input(type='submit')
So when the user press the button the file selected is uploaded, but first the Python code call another routine an open an excel and do some things
import os
from QPX_Test import app
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, after_this_request
from werkzeug import secure_filename
from win32com.client import Dispatch
import pythoncom
import process_excel
main_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Server')
# Initialize the Flask application
# app = Flask(__name__)
# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = main_path
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['xls', 'xlsm','xlsx'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/up')
def index():
return render_template('upload.jade')
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
#return redirect(url_for('uploaded_file',
# filename=filename))
variable_forsave = os.path.join(main_path, filename)
filename_save= os.path.join(main_path, 'Test.xlsm')
# Select Excel File and Save Route into System
process_excel.up_route(variable_forsave, 'C:\inetpub\wwwroot\MyWebSite\Tool\Main System', 'System','B1')
return render_template('webtools_petro.jade')
# after save the file do something
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
#@app.route('/static/uploads/<filename>')
#def uploaded_file(filename):
# return send_from_directory(app.config['UPLOAD_FOLDER'],
# filename)
Finally the routine for open and do some things
import os
import win32com.client
from QPX_Test import app
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, after_this_request
from werkzeug import secure_filename
from win32com.client import Dispatch
import pythoncom
import upload
from flask import send_file
import StringIO
pythoncom.OleInitialize()
def up_route(variabletosave, forsave, sheetsave, rangesave):
pythoncom.CoInitialize ()
xlApp = win32com.client.Dispatch('Excel.Application')
xlWb = xlApp.Workbooks.Open(forsave)
xlSht = xlWb.WorkSheets(sheetsave)
xlSht.Range(rangesave).value= variabletosave
xlApp.visible = True
xlWb.Saved = 0
xlWb.Save()
xlWb.Close(SaveChanges=True)
xlApp.application.Quit()
So I think the problem occurs when Python try to open the excel and don't have the permission, there's a way to bring Python privileges?
EDIT HERE------------------------------------------------------------------
OK, so i created a new application only for testing...
'Index
extends layout
block content
.jumbotron
h1 Excel Test
p.lead Testing the Privileges Features
p Current directory {{ testfile }}
form(action='test', method='post', enctype='multipart/form-data')
button(type="submit)
Very simple
and the views.py
import os, sys
from datetime import datetime
from flask import render_template
from flask import request
from Test_Excel_Python import app
from Test_Excel_Python import Excel_test
import win32com.client
from werkzeug import secure_filename
from win32com.client import Dispatch
import pythoncom
import StringIO
app.debug = True
Folder_File= os.path.dirname(os.path.abspath(sys.argv[0]))
Folder_Excel_Files='Test_Excel_Python\Excel Files'
File_open = 'Test File'
File_Suffix= 'xlsx'
Real_Excel_Route= os.path.join(Folder_File, Folder_Excel_Files, File_open + "." + File_Suffix)
@app.route('/')
@app.route('/home')
def home():
"""Renders the home page."""
return render_template(
'index.jade',
title='Home Page',
year=datetime.now().year, testfile=Real_Excel_Route
)
@app.route('/test', methods=['POST'])
def test():
#Excel_test.Excel_Open #'esto es un test', Real_Excel_Route, 'Prueba','A1')
pythoncom.CoInitialize ()
xlApp = win32com.client.Dispatch('Excel.Application')
xlWb = xlApp.Workbooks.Open('C:\inetpub\wwwroot\MyTestExcel\Test_Excel_Python\Excel Files\Test File.xlsx')
xlSht = xlWb.WorkSheets('Sheet1')
xlSht.Range('A1').value= 'Testing Write here'
xlApp.visible = True
xlWb.Saved = 0
xlWb.Save()
xlWb.Close(SaveChanges=True)
xlApp.application.Quit()
return render_template('index.jade')
and the webconfig is very simplistic
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="FlaskHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Anaconda2\python.exe|C:\inetpub\wwwroot\MyTestExcel\wfastcgi.py" resourceType="Unspecified" />
</handlers>
<rewrite>
</rewrite>
</system.webServer>
</configuration>
Like the first program, This routine works fine on Visual Studio 2015 (start) and visit Localhost:5000
But when i tried with IIS localhost:82 this error appears:
Error occurred:
Traceback (most recent call last):
File "C:\inetpub\wwwroot\MyTestExcel\wfastcgi.py", line 736, in main
result = handler(record.params, response.start)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Anaconda2\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File ".\Test_Excel_Python\views.py", line 64, in test
xlWb = xlApp.Workbooks.Open('C:\inetpub\wwwroot\MyTestExcel\Test_Excel_Python\Excel Files\Test File.xlsx')
File "<COMObject <unknown>>", line 8, in Open
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Microsoft Excel cannot access the file 'C:\\inetpub\\wwwroot\\MyTestExcel\\Test_Excel_Python\\Excel Files\\Test File.xlsx'. There are several possible reasons:\n\n\u2022 The file name or path does not exist.\n\u2022 The file is being used by another program.\n\u2022 The workbook you are trying to save has the same name as a currently open workbook.", u'xlmain11.chm', 0, -2146827284), None)
StdOut:
StdErr:
i already tried with add "xlApp.Interactive = False" but the problem is persistent and i change the app identy on local onnly for testing, of course with this last change the "access denied" problem disappear.
I add APPTOOL\appname to the security folder read/write Access permissions.
PLEASE HELP, this is so frustrating!! :(