there're an open source forum(flaskbb - github) writen by flask, they use from flaskbb.user.models import User in /flaskbb/user/models.py to load User class .
I was trying to imitate that so my project 'dawntime' file structure like this:
dawntime
-__init__.py
-app.py
-public
--__init__.py
--index.py
app.py:
from flask import Flask
from dawntime.public import index
...
both __init__.py file are empty and I really think it's not important about how the file /dawntime/public/index.py is, because of an error occured in line 2 of app.py, complier showed this:
Traceback (most recent call last):
File "app.py", line 2, in
from dawntime.public import index
ImmportError: No module named dawntime.public
would anyone tell what's wrong with that? tks in advanced
app.py is already in the dawntime directory, so instead I think you need
from public import index
Related
My directory looks like this
When I start directly with PyCharm it works.
But when I try to start the script with a commandline I get this error messsage
> python .\PossibilitiesPlotter.py
Traceback (most recent call last):
File "C:\Users\username\PycharmProjects\SwapMatrixPlotter\possibilitiesplotter\PossibilitiesPlotter.py", line 7, in <module>
from plotterresources.PlotterProps import PlotterProps
ModuleNotFoundError: No module named 'plotterresources'
This is how the import looks from my main class PossibilitesPlotter.py
import sys
sys.path.append("plotterresources/PlotterProps.py")
from csv import reader
from pathlib import Path
from plotterresources.PlotterProps import PlotterProps
from possibilitiesplotter.PossibilitiesGraph import PossibilitiesGraph
from possibilitiesplotter.PossibilitiesModel import PossibilitiesModel
class PossibilitiesPlotter:
As a workaround, add the following line to PossibilitesPlotter.py:
sys.path.append("../plotterresources/PlotterProps.py")
This will add the directory one level above the commandline pwd to the PATH variable. So this is always relative to the location of the calling script/shell.
Thus in general:
NEVER append to the PATH/PYTHONPATH variable from within modules. Instead restructure your module. For more details, take a look at the documentation on Packaging Python Projects
This question already has answers here:
Import a file from a subdirectory?
(13 answers)
Closed 11 months ago.
contents of "init.py" file inside "handlers" folder:
from handlers import client
from handlers import admin
from handlers import other
and the content of the "main.py" file looks like this inside the main folder:
from aiogram.utils import executor
from datetime import datetime
from create_bot import dp
from handlers import client, admin, other
client.register_handlers_client(dp)
other.register_handlers_other(dp) #last one!
async def on_startup(_):
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("Bot went online at " + start_time)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
the file structure of my project (this is a telegram bot) looks like this:
test_bot ---> __pycache__
|
|---> handlers ---> client.py, other.py,__init__.py
|
'---> main ---> main.py,config_testbot.py,etc...
when running the "main.py" file in cmd it outputs the following:
Traceback (most recent call last):
File "main.py", line 5, in <module>
from handlers import client, admin, other
ModuleNotFoundError: No module named 'handlers'
And so, how to run the file "main.py" without error? How to replace
from handlers import client, admin, other
so that everything works without errors?! My python version 3.8.10.
I hope you can help me with this problem, thanks in advance!
TLDR;
from handlers.client import *
from handlers.admin import *
from handlers.other import *
If I understood correctly, your question is 'How to import a file from a subdirectory'
I am reading from:
docs
stackoverflow
If you are not using Python 3.3 or upwards create a blank file called __init__.py in the subfolder.
Apparently after Python 3.3 you no longer need the __init__.py file.
And then,
Instead of trying to import handlers which I understood to be the subfolder, try to import the file from the subfolder referring to it as
from subfolder.filename import foo
in your case:
from handlers.client import foo
The Following is my code hierarchy.
I am trying to create a package for my project, "UIGenerator" but it is giving me following error.
traceback (most recent call last):
File "run.py", line 1, in <module>
from UIGenerator import app
File "/Users/______/Desktop/UIGenerator/UIGenerator/__init__.py", line 2, in <module>
from site.routes import site
ModuleNotFoundError: No module named 'site.routes'; 'site' is not a package
Here is the code for run.py =>
from UIGenerator import app
#app.route('/')
def test_connection():
return "<h1>Connected<h1>"
if __name__ == '__main__':
app.run(debug=True)
There is nothing in site =>__init__.py file and in site=>routes.py, I have some sample code to test-
from flask import Blueprint
site = Blueprint('site', __name__)
#site.route('/site')
def site():
return "this is test for site package"
The following is my code for the UIGenerator's init.py file =>
from flask import Flask
from site.routes import site
def getApp():
app = Flask(__name__)
app.register_blueprint(site)
return app
app = getApp()
Can anyone give me any clue, please.
One way to fix this is to build a Python package with you files, like outlined here. This will be better in the long run if you want to scale this project up, and will allow you to declare things in init
That being said, I think you can get your setup working by moving this chunk of code
def getApp():
app = Flask(__name__)
app.register_blueprint(site)
return app
app = getApp()
to the run.py file for the time being.
So, here is what I found out from a different post. In my site=>routes, I declared a global blueprint with the name, site and later I created a site() function which somehow masked my site blueprint. If I just renamed the site method name, it works.
I was writing a little application where I wanted to create a module containg a small group of classes, but when I try to import the classes from the main application, I get the error:
my_project python3 main.py
1
Traceback (most recent call last):
File "main.py", line 2, in <module>
import receivers
File "/home/mario/Documents/python/my_project/receivers/__init__.py", line 2, in <module>
from icinga import Icinga
ModuleNotFoundError: No module named 'icinga'
The file in the project are:
├── main.py
└── receivers
├── icinga.py
├── __init__.py
where main.py
#!/usr/bin/env python
import receivers
icinga = receivers.icinga.Icinga()
the file receivers/icinga.py
class Icinga:
def __init__(self):
print("I'm Icinga!")
the file receivers/__init__.py
print('1')
from icinga import Icinga
print('2')
Can someone please tell me what I do wrong?
Thanks in advance
If you just want to import the Icinga class, you can do it as
from receivers.icinga import Icinga
If you want to call the import statement on receivers, you should alter the init.py, on 2nd line, to:
from .icinga import Icinga
I reproduced your problem here, and was able to solve it like that.
Edit:
Doing this second thing (on __init__.py), you would be able to call it on the main.py as:
import receivers
receivers.icinga.Icinga()
My project structure is as follows:
my_proj
---calculation
---cardata
---master
---my_proj
--- __init.py__
--- admin.py
--- settings.py
--- url.py
--- update_db_from_ftp.py ///// This is my custom file
In update_db_from_ftp.py I want to download an csv file from ftp and update the database(if necessary) once every day with cron.
But the problem is that I can't import model which I want to update. The model which I want to update is inside master folder in models.py file.
I try to import model as follows:
from master.models import ModelName
But I'm getting an error as follows:
Traceback (most recent call last):
File "update_db_from_ftp.py", line 6, in <module>
from master.models import ModelName
ImportError: No module named master.models
But I use the same model in cardata and calculation folder and I import it the same way as I try in update_db_from_ftp.py file, but there it works without problems.
Any idea how to solve it?
UDPATE
The structure of the master folder is as follows:
For using django code in an arbitrary external script, two things are needed:
Django should be setup (exactly what happens when you run django shell).
The root project should be in python path (not the inner folder with same name).
Here is sample code which will work irrespective of the location of the script (although if the script is not one-off, better to add it as management command):
import django
import os
import sys
sys.path.append("/path/to/my-proj/")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my-proj.settings')
django.setup()
from master.models import ModelName
if __name__ == "__main__":
print(ModelName.objects.all())