Search code examples
pythonflaskmathcad

Run a package to control a program inside flask


I'm pretty new in flask and I'm trying to build a web app that takes into account some inputs, and try to pass this ones to another function based on a package that overwrite inputs in a program (MathCAD). Basically for the web app part it's working fine and I can easily retrieve all the variables, but when I try to pass those variables to that packages (called MathcadPy) I've a missing attribute error. This is the part of code for write Input into the program (that works fine in local) that i called "Mathcad_exp.py":




from MathcadPy import Mathcad
import os
folder = os.getcwd()

def mathcad_try(var):
    mathcad_app = Mathcad(visible=False)
    w_math = mathcad_app.open(folder+ "\Mathcad\Sample.mcdx")
    w_math.set_real_input("d_cond", var)
    w_math.save_as(folder + "\Mathcad\Sample.mcdx")
    w_math.close()
    return

and this is my flask code:

import os 
from pathlib import Path
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_migrate import Migrate
from flask_session import Session
from flask import Flask, render_template, request, url_for, redirect,session
import numpy as np
import Mathcad_exp

app = Flask(__name__)
Session(app)
Bootstrap(app)

@app.route('/test/',methods=['POST','GET'])
def test():
  if request.method =="GET":
    return render_template("test.html")
  else:
    test_math=Mathcad_exp.mathcad_try(10)
    return redirect(url_for("test"))

inside the html I only put a button to pass a 'Post' method:

<form action="#" method="post">
        <!--Submit Button -->
        <div class="py-1">
            <div class="btn-example">
              <button type="submit" class="btn btn-primary">Try to write a mathcad</button>
            </div>
          </div>
        </div>
</form>

The two python files are on the same level folder. But anyway I got an attribute error:"AttributeError: 'Mathcad' object has no attribute '_Mathcad__mcadapp'". Where I can notice that somehow the name of the attribute seems changed from when I run locally. I know that this is a very specific question, because Mathcad is licensed software, but am I missing some important part to use another API script in python inside Flask? I repeat that I'me very new at this and maybe I'm missing something basic.


Solution

  • I solved this by adding to the flask route, inside the request method the for Coinizialitze and Counitialize:

    @app.route('/test/',methods=['POST','GET'])
    def test():
      if request.method =="GET":
        return render_template("test.html")
      else:
        import pythoncom
        pythoncom.CoInitialize()
        test_math=Mathcad_exp.mathcad_try(10)
        pythoncom.CoUninitialize()
        return redirect(url_for("test"))