jjjbeard
jjjbeard

Reputation: 43

Importing class from another directory to Flask App routes/views

I have a flask application, I used the below to import a module I wrote into the forms.py file and it seems to work.

sys.path.append('/home/user/lib/')
from mymodule import *

However when I attempt to import it into my routes.py file it fails. When I restart my WSGI apache server it will not load, unfortunately I don't get any logs telling why for some reason.

Below is the layout of my application.

flaskapp
├── config.py
├── forms.py
├── flaskapp.wsgi
├── __init__.py
├── routes.py
├── static
│   ├── search.js
│   └── sort.js
└── templates
    ├── base.html
    ├── certs_view.html
    ├── results.html
    ├── index.html
    ├── new_org.html
    ├── submit_csr.html
    └── upload.html

I have tried the append, and insert methods to try an import the module without any success. I even created a symbolic link to try it that way but the WSGI server won't load as soon as I attempt to import that into the routes.py.

init.py

from flask import Flask
app = Flask(__name__)
import flaskapp.routes
import flaskapp.config
import flaskapp.forms
from flask_bootstrap import Bootstrap
from flaskapp.forms import RequestCSRForm
from flaskapp.forms import SubmitForm
from flaskapp.forms import UploadCertificate
from flaskapp.forms import CreateNewOrg
#from mymodule import *
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] = ''
app.config.from_object(config)
...

config.py

import os
from flaskapp import app
...

!This One Works! forms.py

import sys, json
from flaskapp import app
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import DataRequired
sys.path.append('/home/user/lib/')
from mymodule import *
...

!This One DOESN'T Works! routes.py

import os, datetime, json, time, OpenSSL.crypto
from flaskapp import app
from flask import render_template, Flask, redirect, url_for, flash
from flask_bootstrap import Bootstrap
from flaskapp.forms import RequestCSRForm
from flaskapp.forms import SubmitForm
from flaskapp.forms import UploadCertificate
from flaskapp.forms import CreateNewOrg
from OpenSSL.crypto import load_certificate_request, FILETYPE_PEM
sys.path.append('/home/user/lib')
from mymodule import *
...

I want to be able to call functions from mymodule from the routes.py or ideal all of them...

Upvotes: 1

Views: 1124

Answers (1)

Hildeberto
Hildeberto

Reputation: 434

Why not create a setup to your module, then pip install mymodule in the venv of your flaskapp?

https://packaging.python.org/tutorials/packaging-projects/

Upvotes: 1

Related Questions