skip to Main Content

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


  1. 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:

    flaskApp
    ---- flaskApp
        ---- __init__.py
        ---- modules
            ---- __init__.py  <-- NEW
            ---- mymodules.py
        ---- static
            ---- css
            ---- img
            ---- js
        ---- templates
            ---- index.html
    ---- flaskapp.wsgi
    
    Login or Signup to reply.
  2. 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.

    from .modules import mymodules
    #    ^ this dot makes it relative to the current folder
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search