Damon
Damon

Reputation: 89

Having issue importing py file in Flask

I am having issues when importing py files in flask. Here are how my files are structured:

Flask: /var/www/html/flask_app/flask.py

Current location of python script: /var/www/html/flask_app/python/IP/ip.py

Desired location of python script: /scripts/python/IP/ip.py

I would like to move my script from www directory and create a new folder in /. I am having issues when after I move, i can't seem to import it and get 500 error message.

Please see below:

// flask.py   
@app.route('/ipcheck', methods=['POST'])
def ip_check():    
    from python.IP import ip
    return ip.check_ip_range()

// Above works when python folder is in same directory.  However when I move python folder to /scripts/, I get Error 500.

// Flask.py after folder move - should import from /scripts/pyton/IP/ip.py

@app.route('/ipcheck', methods=['POST'])
def ip_check():
    sys.path.append('/scripts/')     
    from python.IP import ip
    return ip.check_ip_range()

How do I import ip.py?

Upvotes: 0

Views: 424

Answers (1)

Arthur Dent
Arthur Dent

Reputation: 1952

It needs to be in your Python path. If you don't want it in www folder, then install in path where other Python libraries are installed on your system. Otherwise add that location to the path before importing like so:

import sys
sys.path.append("/scripts/python/")

Even so, you wouldn't import it from python unless that python folder has an __init__.py folder in it to make it a package (unless that is your system Python path). So in this case you'd just do:

from IP import ip

Assuming you appended it to system path dynamically as shown above.

Upvotes: 1

Related Questions