Import Error in flask application - python

I have an application. Below is o/p of tree command -
app
|-- main
| |-- lib
| | |-- constants.py
| | |-- helper.py
| | `-- __init__.py
| `-- src
| |-- __init__.py
| `-- web.py
web.py
from flask import Flask, request
app = Flask(__name__)
from lib.helper import endpoints
.....
Some code
.....
if __name__ == '__main__':
app.run('0.0.0.0', 5433, debug=True)
I am getting this error
ImportError: No module named lib.helper.
where am I doing wrong?

from flask import Flask, request
app = Flask(__name__)
import sys
from os.path import abspath, dirname
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from lib.helper import endpoints
.....
Some code
.....
if __name__ == '__main__':
app.run('0.0.0.0', 5433, debug=True)

Lib module is outside of src folder, need to go up one folder up and use that model.
from ..lib.helper

Or else a fully qualified namespace as
from app.main.lib

Related

relative paths in python not finding parent package

I have a file system like this at the moment.
app
|--__init__.py (empty)
|
|--domain
| |--__init__.py (empty)
| |--model.py
| |--questionmatcher.py
|
|--interface
| |--__init__.py (empty)
| |--basiccli.py
| |--userinterface.py
|
|--parser
| |--__init__.py (empty)
| |--json_loader.py
| |--parsing.py
|
|--testfiles
| |--__init__.py (empty)
| |--testsuite.py
I am trying to run the testsuite.py which will need to import classes from various files in directory.
I have tried this structure:
import unittest
from ..parser.json_loader import JsonLoader
from ..parser.parsing import get_vectors, parseThreadsFromFile, getPostsFromThreads
from ..domain import UniversalEncoder, SentBERT
class TestParsing(unittest.TestCase):
def test(self):
pass
class TestJson(unittest.TestCase):
def test(self):
pass
class TestModelEncoders(unittest.TestCase):
def test(self):
pass
if __name__ == "__main__":
unittest.main()
However when I go to run the test I get:
from ..parser.json_loader import JsonLoader
ImportError: attempted relative import with no known parent package
EDIT:
I have tried
from parser.json_loader import JsonLoader
but now I get
from parser.json_loader import JsonLoader
ModuleNotFoundError: No module named 'parser.json_loader'; 'parser' is not a package
you can add this package to your PYTHONPATH environmental variable:
export PYTHONPATH=$PYTHONPATH:/path/to/parser

What is the right way to import this python file?

I have the current directory structure:
- api
|
- app.py
|
- tests
|
- test_app.py
What is the correct way to import app.py into test_app.py?

Import a file from another directory

I have a file call entryPoint.py :
from .commonLib.deviceLib import *
And I have a file called deviceLib.py :
import math
import sys
import logging
import requests
import this
class DeviceLib(object):
def __init__(self, connectionDb):
self.__db = connectionDb
The tree is like this :
/test
entryPoint.py
/commonLib
__init__.py
deviceLib.py
When I execute python entryPoint.py I get the error : Attempted relative import in non-package. Please help me.
use sys.path.append to append the directory where your python file (module is). E.g if your entryPoint.py is inside address directory
import sys
sys.path.append('/path/to/your/module/address/')
import entryPoint
There should be __init__.py in the folder both /test and /commonLib reside.
then just do
from commonLib import deviceLib
For example
sound
|-- effects
| |-- echo.py
| |-- __init__.py
| |-- reverse.py
| `-- surround.py
|-- filters
| |-- equalizer.py
| |-- __init__.py
| |-- karaoke.py
| `-- vocoder.py
|-- formats
| |-- aiffread.py
| |-- aiffwrite.py
| |-- auread.py
| |-- auwrite.py
| |-- __init__.py
| |-- wavread.py
| `-- wavwrite.py
`-- __init__.py
lets assume you are right now opened wavread.py in format subdirecory, you can import karaoke.py from filters by just
from filters import karaoke
More information Here,
https://www.python-course.eu/python3_packages.php
To import a file from another directory you can use this code :
import sys
sys.path.insert(0, 'folder destination')
import file
As you can see here we included the path so python will look for the file in that path as well.

Import via relative path global variables module

Here is my directory structure:
.
`-- parent
|-- child
| |-- globalvar.py
| |-- __init__.py
| `-- subchild
| |-- __init__.py
| `-- module.py
`-- main.py
The globalvar.py in the child directory consist of the global variables that I would like to use in my application:
globalvar.py
def variables():
global event_id
event_id = 2100
In main.py, I'm calling the globalvar.py via import to initialize (child.globalvar.variables):
main.py
import child.globalvar
from child.subchild.module import display
child.globalvar.variables()
display()
Here is what I in my module.py file under the directory subchild:
from ..globalvar import variables
def display():
print globalvar.event_id
This is the traceback I get when I execute main.py:
Traceback (most recent call last):
File "main.py", line 6, in <module>
display()
File "/parent/child/subchild/module.py", line 5, in display
print globalvar.event_id
NameError: global name 'globalvar' is not defined
How do I fix this?
I was able to fix it by changing the import statement in my module.py file:
BEFORE:
from ..globalvar import variables
AFTER:
from .. import globalvar

Inserting a folder containing specific routes to a bottle application in Python

Let us say that we have the following directory structure ...
+-- main.py
|
+--+ ./web
| |
| +--- ./web/bottleApp.py
Currently, I want to organize the files so that the I can separate different functionality in different areas. Template main.py and ./web/bottleApp.py look like the following ...
This is the ./web/bottleApp.py file:
import bottle
app = bottle.Bottle()
#app.route('/')
def root():
return 'This is the root application'
# some additional functions here ...
And this is the main.py file ...
from web import bottleApp as app
with app.app as report:
# Some random routes here ...
report.run(host = 'localhost', port=8080)
Now I want to add another folder which can handle some functions which I may optionally use is a bunch of my projects, (for example configuration file handling via the web interface just created)
Let us say we want to insert the following folder/file configuration ...
+-- main.py
|
+--+ ./web
| |
| +--- ./web/bottleApp.py
|
+--+ ./configure
|
+--- ./configure/config.py
Given the original app = bottle.Bottle() I want to create the following sample route in the file ./configure/config.py:
#app.route('/config/config1')
def config1():
return 'some config data'
How do I even go about doing this? Once I run the main.py file, how do I make sure that the other routes are available?
Bottle can run multiple bottle apps as a single instance.
You can use something like this on main.py
import bottle
from web.bottleApp import app
from configure.config import configure_app
main = bottle.Bottle()
main.mount("/config/",configure)
main.mount("/",app)
main.run(host = 'localhost', port=8080)
and on configure/config.py something like this:
import bottle
config_app = bottle.Bottle()
#config_app.route('/config1')
def config1():
return 'some config data'

Categories