Home > Software engineering >  python issue while importing a module from a file
python issue while importing a module from a file

Time:12-03

the below is my main_call.py file

from flask import Flask, jsonify, request

from test_invoke.invoke import end_invoke

from config import config

app = Flask(__name__)


@app.route("/get/posts", methods=["GET"])
def load_data():
    
        res = "True"
        
        # setting a Host url
        host_url = config()["url"]

        # getting request parameter and validating it 
        generate_schedule= end_invoke(host_url)

        if generate_schedule == 200:
            return jsonify({"status_code": 200, "message": "success"})
        elif generate_schedule == 400:
            return jsonify(
                {"error": "Invalid ", "status_code": 400}
            )

    

if __name__ == "__main__":
    app.run(debug=True)

invoke.py

import requests
import json
import urllib
from urllib import request, parse
from config import config
from flask import request




def end_invoke(schedule_url):

    

    

    headers = {
        "Content-Type":"application/json",
    }
    schedule_data = requests.get(schedule_url, headers=headers)

    if not schedule_data.status_code // 100 == 2:
        error = schedule_data.json()["error"]
        print(error)
        
        return 400
    
    else:
        success = schedule_data.json()
        
        return 200

tree structure

test_invoke
├── __init__.py
├── __pycache__
│   ├── config.cpython-38.pyc
│   └── invoke.cpython-38.pyc
├── config.py
├── env.yaml
├── invoke.py
└── main_call.py

However when i run, i get the no module found error

 python3 main_call.py 
Traceback (most recent call last):
  File "main_call.py", line 3, in <module>
    from test_invoke.invoke import end_invoke
ModuleNotFoundError: No module named 'test_invoke'

CodePudding user response:

Python looks for packages and modules in its Python path. It searches (in that order):

  • the current directory (which may not be the path of the current Python module...)
  • the content of the PYTHONPATH environment variable
  • various (implementation and system dependant) system paths

As test_invoke is indeed a package, nothing is a priori bad in using it at the root for its modules provided it is accessible from the Python path.

But IMHO, it is always a bad idea to directly start a python module that resides inside a package. Better to make the package accessible and then use relative imports inside the package:

  • rename main_call.py to __main__.py
  • replace the offending import line with from .invoke import end_invoke
  • start the package as python -m test_invoke either for the directory containing test_invoke or after adding that directory to the PYTHONPATH environment variable

That way, the import will work even if you start your program from a different current directory.

CodePudding user response:

You are trying to import file available in the current directory.

So, please replace line from test_invoke.invoke import end_invoke with from invoke import end_invoke

  • Related