I use Flask for the first time. The following __init__.py
is working fine :
Python v3.10.6
#!/usr/bin/env python3
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/testurl')
def testurl():
return render_template('index.html')
@app.route('/from_client', methods=['POST'])
def from_client():
request_data = request.get_json()
return request_data
if __name__ == '__main__':
app.run()
I use the following folders :
flaskApp
---- flaskApp
---- __init__.py
---- modules
---- mymodules.py
---- static
---- css
---- img
---- js
---- templates
---- index.html
---- flaskapp.wsgi
But when I try to change __init__.py
to import mymodules from modules folder, I got "500 Internal Server Error".
The code used :
#!/usr/bin/env python3
from flask import Flask, render_template, request
from modules import mymodules
app = Flask(__name__)
@app.route('/testurl')
def testurl():
return render_template('index.html')
@app.route('/from_client', methods=['POST'])
def from_client():
request_data = request.get_json()
data_id = mymodules.somecode(request_data)
return data_id
if __name__ == '__main__':
app.run()
I feel that there is an issue from how import work. I tried to use
import sys
#sys.path.append('[pathoftheflaskfolder/flaskApp/flaskApp/modules')
But it doesn’t help either. My skill in Flask and Python are limited, so I turn around and don’t find solution. If use have an idea, be my guests !
2
Answers
To create module directories, the folder will need an
__init__.py
, so that Python can tell it is a module, and not just a folder with code in it.Change your file structure to the following:
It looks like your code is trying to import the module whilst being within a module itself. You should instead use a relative import to make it work correctly.