Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, how can I import modules that are in sub-directory?

Tags:

python

flask

I am using Python and Flask to build a project.

How can I import modules that are in sub-directory?

here is the directory structure.

/application
  /apis
    settings.py
index.py

and here is the index.py file.

from flask import Flask
import os
import sys
import random
from flask import render_template, request, jsonify, redirect, url_for, send_file, Response, make_response
from werkzeug import secure_filename

app = Flask(__name__)
app.debug = True

sys.path.append("apis")
import settings

here is the settings.py file in apis folder.

from flask import Flask
import pymongo
import datetime
import os
import sys
import random
from flask import render_template, request, jsonify, redirect, url_for, send_file, Response, make_response
from werkzeug import secure_filename

app = Flask(__name__)
app.debug = True

## About Us
@app.route('/apis/settings/aboutus')
def aboutus():
    return render_template('aboutus.html')

So, I tried to import settings module by using sys.path.append.

When all codes was in index.py, it worked fine.

If I hit this address http://domain.com:5000/apis/settings/aboutus, it supposed to show AboutUS page.

However, it says "404 Not Found" after I split modules.

Can you see the problem?

like image 423
Jake Avatar asked Sep 19 '25 09:09

Jake


1 Answers

You need to create a "package". Basically a directory that contains __init__.py.

usually you can (naively) do something like this:

$ mkdir foo
$ touch foo/__init__.py

"foo" must be in the sys.path however.

See: http://docs.python.org/2/tutorial/modules.html for more information.

like image 167
James Mills Avatar answered Sep 20 '25 22:09

James Mills