Forums

Error:ModuleNotFoundError: No module named 'wsgi' when trying to configure a new website?

I tried to have a new website. Here is the relevant structure of files:

microblog / wsgi.py
microblog / app / main

wsgi.py:

import os

from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)

from app.main import bp

/var/www_my_domian_com_wsgi.py configuration as follows:

import sys

path = '/home/my_username/microblog'
if path not in sys.path:
    sys.path.append(path)

from wsgi import bp as application

but I tried to visit the website domain after all step is completed, an error happend:

error.log

2023-11-19 07:54:16,271: Error running WSGI application
2023-11-19 07:54:16,273: ModuleNotFoundError: No module named 'wsgi'
2023-11-19 07:54:16,273:   File "/var/www/my_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-19 07:54:16,273:     from wsgi import bp as application
2023-11-19 07:54:16,273: ***************************************************
2023-11-19 07:54:16,273: If you're seeing an import error and don't know why,
2023-11-19 07:54:16,274: we have a dedicated help page to help you debug: 
2023-11-19 07:54:16,274: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-19 07:54:16,274: ***************************************************
2023-11-19 08:08:27,926: Error running WSGI application
2023-11-19 08:08:27,927: TypeError: 'Blueprint' object is not callable
2023-11-19 08:08:54,589: Error running WSGI application
2023-11-19 08:08:54,590: TypeError: 'Blueprint' object is not callable

I have tried to debug using some way. For example, I runned python wsgi.py on command line, as a result, no error reports. I used python -i /var/www_my_domain_com_wsgi.py, no error reports likewise. And Everything is running successfully on local host . Can anyone give a favor?

Did you follow https://help.pythonanywhere.com/pages/DebuggingImportError/ If so, what was the result?

Indeed, I have followed the debugging instruction in such above link, but nothing reports, I have adjusted the markdown format to be readable. By the way, I do not know why the intial markdown format created by html tags like <pre><code> was in a mess.

My question is that I have wsgi.py in microblog working directory, but the error still send such message.

I don't think that the error "ModuleNotFoundError: No module named 'wsgi'" is the problem here -- if you check out the timestamps in the log file, you were getting that at 07:54 server time, but then later, at 08:08 (which is 48 minute before you posted here in the forums) it changed to this:

2023-11-19 08:08:27,926: Error running WSGI application
2023-11-19 08:08:27,927: TypeError: 'Blueprint' object is not callable

That means that by that later point, the issue with the wsgi module must have been resolved. Instead, it's complaining that you have some code that is trying to call an object of type "Blueprint", which is presumably happening in your "main" module. Do you have code that's catching and printing exceptions? Normally I'd expect an error like that to be accompanied by a stack trace so that you can see where it's happening.

Indeed, I have called blueprint in api submodule, The code are similar:

from flask import Blueprint

bp = Blueprint('api', __name__)

from app.api import users, errors, tokens

It runs successfully on flask local host, Just before a few seconds, It gave me more info when web url was entered

error.log

2023-11-19 07:54:16,271: Error running WSGI application
2023-11-19 07:54:16,273: ModuleNotFoundError: No module named 'wsgi'
2023-11-19 07:54:16,273:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-19 07:54:16,273:     from wsgi import bp as application
2023-11-19 07:54:16,273: ***************************************************
2023-11-19 07:54:16,273: If you're seeing an import error and don't know why,
2023-11-19 07:54:16,274: we have a dedicated help page to help you debug: 
2023-11-19 07:54:16,274: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-19 07:54:16,274: ***************************************************
2023-11-19 08:08:27,926: Error running WSGI application
2023-11-19 08:08:27,927: TypeError: 'Blueprint' object is not callable
2023-11-19 08:08:54,589: Error running WSGI application
2023-11-19 08:08:54,590: TypeError: 'Blueprint' object is not callable
2023-11-19 08:19:54,446: Error running WSGI application
2023-11-19 08:19:54,448: ModuleNotFoundError: No module named 'dotenv'
2023-11-19 08:19:54,448:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-19 08:19:54,450: we have a dedicated help page to help you debug: 
2023-11-19 08:19:54,450: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-20 11:11:09,496: Error running WSGI application
2023-11-20 11:11:09,502: ModuleNotFoundError: No module named 'dotenv'
2023-11-20 11:11:09,502:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-20 11:11:09,502:     from wsgi import bp as application
2023-11-20 11:11:09,503: 
2023-11-20 11:11:09,503:   File "/home/JTPing/microblog/./wsgi.py", line 3, in <module>
2023-11-20 11:11:09,503:     from dotenv import load_dotenv
2023-11-20 11:11:09,503: ***************************************************
2023-11-20 11:11:09,503: If you're seeing an import error and don't know why,
2023-11-20 11:11:09,504: we have a dedicated help page to help you debug: 
2023-11-20 11:11:09,504: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-20 11:11:09,504: ***************************************************
2023-11-20 11:11:10,446: Error running WSGI application
2023-11-20 11:11:10,447: ModuleNotFoundError: No module named 'dotenv'
2023-11-20 11:11:10,447:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-20 11:11:10,447:     from wsgi import bp as application
2023-11-20 11:11:10,447: 
2023-11-20 11:11:10,447:   File "/home/JTPing/microblog/./wsgi.py", line 3, in <module>
2023-11-20 11:11:10,447:     from dotenv import load_dotenv
2023-11-20 11:11:10,448: ***************************************************
2023-11-20 11:11:10,448: If you're seeing an import error and don't know why,
2023-11-20 11:11:10,448: we have a dedicated help page to help you debug: 
2023-11-20 11:11:10,448: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-20 11:11:10,448: ***************************************************
2023-11-21 11:01:33,951: Error running WSGI application
2023-11-21 11:01:33,955: ModuleNotFoundError: No module named 'dotenv'
2023-11-21 11:01:33,955:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-21 11:01:33,955:     from wsgi import bp as application
2023-11-21 11:01:33,955: 
2023-11-21 11:01:33,955:   File "/home/JTPing/microblog/./wsgi.py", line 3, in <module>
2023-11-21 11:01:33,955:     from dotenv import load_dotenv
2023-11-21 11:01:33,955: ***************************************************
2023-11-21 11:01:33,956: If you're seeing an import error and don't know why,
2023-11-21 11:01:33,956: we have a dedicated help page to help you debug: 
2023-11-21 11:01:33,956: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-21 11:01:33,956: ***************************************************
2023-11-21 11:01:38,492: Error running WSGI application
2023-11-21 11:01:38,493: ModuleNotFoundError: No module named 'dotenv'
2023-11-21 11:01:38,493:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-21 11:01:38,493:     from wsgi import bp as application
2023-11-21 11:01:38,493: 
2023-11-21 11:01:38,493:   File "/home/JTPing/microblog/./wsgi.py", line 3, in <module>
2023-11-21 11:01:38,493:     from dotenv import load_dotenv
2023-11-21 11:01:38,494: ***************************************************
2023-11-21 11:01:38,494: If you're seeing an import error and don't know why,
2023-11-21 11:01:38,494: we have a dedicated help page to help you debug: 
2023-11-21 11:01:38,494: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-21 11:01:38,494: ***************************************************
2023-11-21 11:01:53,633: Error running WSGI application
2023-11-21 11:01:53,634: ModuleNotFoundError: No module named 'dotenv'
2023-11-21 11:01:53,634:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-21 11:01:53,635:     from wsgi import bp as application
2023-11-21 11:01:53,635: 
2023-11-21 11:01:53,635:   File "/home/JTPing/microblog/./wsgi.py", line 3, in <module>
2023-11-21 11:01:53,635:     from dotenv import load_dotenv
2023-11-21 11:01:53,635: ***************************************************
2023-11-21 11:01:53,636: If you're seeing an import error and don't know why,
2023-11-21 11:01:53,636: we have a dedicated help page to help you debug: 
2023-11-21 11:01:53,636: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-21 11:01:53,636: ***************************************************
2023-11-21 11:02:21,901: Error running WSGI application
2023-11-21 11:02:21,902: ModuleNotFoundError: No module named 'dotenv'
2023-11-21 11:02:21,902:   File "/var/www/jtping_pythonanywhere_com_wsgi.py", line 44, in <module>
2023-11-21 11:02:21,902:     from wsgi import bp as application
2023-11-21 11:02:21,902: 
2023-11-21 11:02:21,902:   File "/home/JTPing/microblog/./wsgi.py", line 3, in <module>
2023-11-21 11:02:21,903:     from dotenv import load_dotenv
2023-11-21 11:02:21,903: ***************************************************
2023-11-21 11:02:21,903: If you're seeing an import error and don't know why,
2023-11-21 11:02:21,903: we have a dedicated help page to help you debug: 
2023-11-21 11:02:21,903: https://help.pythonanywhere.com/pages/DebuggingImportError/
2023-11-21 11:02:21,903: ***************************************************

I have tried this on base console, the code from dotenv import load_dotenv works as follows:

>>> from dotenv import load_dotenv
>>> import os

Looks like you are running your app in the environment where python-dotenv is not installed

I had python-dotenv installed, to confirm this, pip show python-dotenv shows exact package messages.

And I dout the statement from app.main import bp is true or not in wsgi.py, or it should be from app import app where app is returned by create_app function in app / __init__.py rather than blueprint?

It's possible that it is installed with a different version of python than the one you're using in your web app.

Yes, you are right, I have python version 3.9 in my own web app, and happen to find bash consle using python 3.10.5, what should I do?

I'd use virtualenvs for all your projects if you arent already - https://help.pythonanywhere.com/pages/Virtualenvs/

Sorry, I have already used virtualenv on my web app

Then make sure you have installed the packages that you need into the virtualenv that you are using to run your web app and, in the console, activate the virtualenv.

I have activated virtualenv in bash console, I'm sure each package including python-dotenv was installed. but i do not understand why such above error stiil reports.

Are you checking the bottom of your error log? It's possible that your app has more issues than a missing import. If so, new errors are appended at the end of the error log.

Yes, it reported that TypeError: Blueprint is not callable , Meanwhile no such error reports on my local host, I am confused.

Do you have a file called "Blueprint.py", or perhaps "flask.py"?

No, the only thing associated with blueprint in the whole directory is like that:

from flask import Blueprint

bp = Blueprint('api', __name__)

from app.api import users, errors, tokens

from app.main import bp
those code are listed above at the top of question.

Can we take a look at your files? We can see them from our admin interface, but we always ask for permission first.

Yes, you can, actually it is public and crude, Actually I can visit my logging page now, but a predefined error message reports: "The administrator has been notified. Sorry for the inconvenience!

So I then tried to use flask db upgrade, but the following error comes:

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade dc96d9b0d0bf -> e949960c17e9, let user be able to follow and unfollow
Traceback (most recent call last):
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: table user already exists

It sounds like your migrations have got out of sync somehow. Do you have anything important in your app.db database right now? If not, it might be easiest to just delete it and then run the migration again.

Is there only this way to solve it? I had some posts on it, I do not want to delete those data

I found that new register is also not working, same error "The administrator has been notified. Sorry for the inconvenience!

I think I’m having a pretty similar issue

Error running WSGI application 2023-11-28 06:25:58,676: ModuleNotFoundError: No module named 'openai' 2023-11-28 06:25:58,676: File "/var/www/buzzy2427_pythonanywhere_com_wsgi.py", line 16, in <module> 2023-11-28 06:25:58,676: from flask_app import app as application # noqa 2023-11-28 06:25:58,676: 2023-11-28 06:25:58,677: File "/home/Buzzy2427/ai/flask_app.py", line 8, in <module> 2023-11-28 06:25:58,677: from openai import OpenAI

I def have openAI installed

@JTPing Are you getting the same error on a fresh database? @Buzzy2427 I believe we already answered you in a different thread, please keep the conversation in one place.

What should I do for deleting app.db database? delete all files of migrations and all data in app.db?

You'd just need to delete the file app.db itself -- or perhaps, for safety, just move it to a different location. Something like this would work:

mv app.db app.db.OLD

I runned command mv app.db app.db.OLD on bash console, but I am still getting same error

One puzzle for me is that I don't know why it runs smoothly on my local host but fail to work online

The most likely difference is that different migrations were applied to the different databases and the one on PythonAnywhere is not consistent.

I have only used one database flask-sqlalchemy on it and also installed celey, redis, rq.

You can use sqlite3 command line tool to inspect your database, compare it to the migrations and figure out what is going on there.

It seems difficult for me

After you moved the database file to one side with the command above, did you run the flask db upgrade command? If so, did it generate any errors?

It produced same error :

Traceback (most recent call last):
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: table user already exists

Then the file that you moved was not the file where your database is. What is the path to the database file that you are trying to use and how are you referring to it when you connect to it with sqlalchemy?

You mean app.db is not my database? but when i run flask shell in bash console, it has the following result:

(venv) 11:11 ~/microblog (main)$ flask shell
Python 3.10.5 (main, Jul 22 2022, 17:09:35) [GCC 9.4.0] on linux
App: app
Instance: /home/JTPing/microblog/instance
>>> db
<SQLAlchemy sqlite:////home/JTPing/microblog/app.db>

Here is some parts in config.py

class Config():
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False

What is basedir set to when that code is run?

The basedir path is set to be:

basedir = os.path.abspath(os.path.dirname(__file__))

And the environment variables are in .env file:

SECRET_KEY=random_string_from_uuid
DATABASE_FILE=data-prod.db

You can add some logging to show the basedir in the logs, so you're sure that it represents the right path. Also, just to avoid confusion (a recap of previous conversation) -- you moved app.db to app.db.OLD and then immediately ran flask db upgrade, is that correct?

The basedir is the root directory:

(venv) 12:36 ~/microblog (main)$ flask shell
fPython 3.10.5 (main, Jul 22 2022, 17:09:35) [GCC 9.4.0] on linux
App: app
Instance: /home/JTPing/microblog/instance
>>> from config import basdir
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: cannot import name 'basdir' from 'config' (/home/JTPing/microblog/config.py)
>>> from config import basedir
>>> print(basedir)
/home/JTPing/microblog

OK, that sounds good. Assuming that it's being calculated using something like os.path and the __file__ magic variable, you should be getting the same app.db in each case.

In that case, I think there must be an error in your migrations. Earlier on you moved the app.db file to one side, and then ran the migrations with flask db upgrade. It generated an error saying "table user already exists". The only way that could happen -- at least that I can see -- is if one migration created the table "user", and then another one tried to create it again. What was the full output of the migration command?

The full output maybe is long:

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade dc96d9b0d0bf -> e949960c17e9, let user be able to follow and unfollow
Traceback (most recent call last):
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: table user already exists

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/JTPing/microblog/venv/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/flask/cli.py", line 1047, in main
    cli.main()
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/decorators.py", line 26, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/flask/cli.py", line 357, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/flask_migrate/cli.py", line 149, in upgrade
    _upgrade(directory, revision, sql, tag, x_arg)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/flask_migrate/__init__.py", line 111, in wrapped
    f(*args, **kwargs)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/flask_migrate/__init__.py", line 200, in upgrade
    command.upgrade(config, revision, sql=sql, tag=tag)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/command.py", line 322, in upgrade
    script.run_env()
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/script/base.py", line 569, in run_env
    util.load_python_file(self.dir, "env.py")
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/util/pyfiles.py", line 94, in load_python_file
    module = load_module_py(module_id, path)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/util/pyfiles.py", line 110, in load_module_py
    spec.loader.exec_module(module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/JTPing/microblog/migrations/env.py", line 97, in <module>
    run_migrations_online()
 File "/home/JTPing/microblog/migrations/env.py", line 91, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/runtime/environment.py", line 853, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/runtime/migration.py", line 623, in run_migrations
    step.migration_fn(**kw)
  File "/home/JTPing/microblog/migrations/versions/e949960c17e9_let_user_be_able_to_follow_and_unfollow.py", line 21, in upgrade
    op.create_table('user',
  File "<string>", line 8, in create_table
  File "<string>", line 3, in create_table
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/operations/ops.py", line 1254, in create_table
    return operations.invoke(op)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/operations/base.py", line 399, in invoke
    return fn(self, operation)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/operations/toimpl.py", line 114, in create_table
    operations.impl.create_table(table)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/ddl/impl.py", line 354, in create_table
    self._exec(schema.CreateTable(table))
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/alembic/ddl/impl.py", line 195, in _exec
    return conn.execute(construct, multiparams)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1380, in execute
    return meth(self, multiparams, params, _EMPTY_EXECUTION_OPTS)
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/sql/ddl.py", line 80, in _execute_on_connection
    return connection._execute_ddl(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1472, in _execute_ddl
    ret = self._execute_context(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1943, in _execute_context
    self._handle_dbapi_exception(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2124, in _handle_dbapi_exception
    util.raise_(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 210, in raise_
    raise exception
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/JTPing/microblog/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table user already exists
[SQL: 
CREATE TABLE user (
        id INTEGER NOT NULL, 
        username VARCHAR(64), 
        email VARCHAR(120), 
password_hash VARCHAR(128), 
        about_me VARCHAR(140), 
        last_seen DATETIME, 
        PRIMARY KEY (id)
)
]
(Background on this error at: https://sqlalche.me/e/14/e3q8)

By the way, the flask db migrate outputs:

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
ERROR [flask_migrate] Error: Target database is not up to date.

I guess the problem is current migration edition is not consistent with head mirgation edition, so i did this although i don't know why two different editions happened:

>>>flask db heads
ceca8f22389c (head)
>>>flask db current
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
dc96d9b0d0bf

I then use flask db stamp heads to mark the migration edition:

flask db stamp heads
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running stamp_revision dc96d9b0d0bf -> ceca8f22389c

And check it:

flask db current
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
ceca8f22389c (head)

then run:

flask db upgrade
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.

but it seems still not work, so i run command again:

 flask db migrate
    INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
    INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
    INFO  [alembic.autogenerate.compare] Detected added table 'message'
    INFO  [alembic.autogenerate.compare] Detected added index 'ix_message_timestamp' on '['timestamp']'
    INFO  [alembic.autogenerate.compare] Detected added table 'notification'
    INFO  [alembic.autogenerate.compare] Detected added index 'ix_notification_name' on '['name']'
    INFO  [alembic.autogenerate.compare] Detected added index 'ix_notification_timestamp' on '['timestamp']'
    INFO  [alembic.autogenerate.compare] Detected added table 'comment'
    INFO  [alembic.autogenerate.compare] Detected added index 'ix_comment_timestamp' on '['timestamp']'
    INFO  [alembic.autogenerate.compare] Detected added column 'post.language'
    INFO  [alembic.autogenerate.compare] Detected added column 'post.body_html'
    INFO  [alembic.autogenerate.compare] Detected type change from VARCHAR(length=140) to Text() on 'post.body'
    INFO  [alembic.autogenerate.compare] Detected added column 'user.token'
    INFO  [alembic.autogenerate.compare] Detected added column 'user.token_expiration'
    INFO  [alembic.autogenerate.compare] Detected added column 'user.last_message_read_time'
    INFO  [alembic.autogenerate.compare] Detected added index 'ix_user_token' on '['token']'
      Generating /home/JTPing/microblog/migrations/versions/e6990a7ae19f_.py ...  done
    (venv) 01:50 ~/microblog (main)$ flask db upgrade
    INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
    INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
    INFO  [alembic.runtime.migration] Running upgrade 9d026987d6f2 -> e6990a7ae19f, empty message

It works and i can log in now, but unexpected things occurs: all previous user data is gone , so i registered again, but i find that i can't not comment and the error is same as the above "The administrator has been notified. Sorry for the inconvenience!" Also, i clicked the file(文件 in chinese) tag, the error was same. i do not know why.

Maybe you can have a look at this crude website because it is accessible now if you like. Thank you.

what should I do?

I used cd migrations/versions and ls to list all subfile:

05eba44a406a_notifications.py             b07ebb5fe6e0_fix_markdown_rendering_of_comments.py
14ba2865cec3_add_comments.py              ceca8f22389c_user_tokens.py
3d95c0a8c088_users_table.py               dc96d9b0d0bf_followers.py
6ee987d26551_posts_table.py               e6990a7ae19f_.py
92a7096214ea_new_fields_in_user_model.py  e949960c17e9_let_user_be_able_to_follow_and_unfollow.py
9389414e987c_enable_markdown_editor.py    f3cff53a2dcf_add_language_to_posts.py
9d026987d6f2_.py                          fd8a7d4f9bd4_private_messages.py
__pycache__

Compare the above with my local file, I found two extra file e6990a7ae19f_.py and 9d026987d6f2_.py, and the latter is the last version which produced logging problems, the former is now database stand on.

I guess the problem lies in the last generated migrations file: e6990a7ae19f_.py , so I cat it.

"""empty message
Revision ID: e6990a7ae19f
Revises: 9d026987d6f2
Create Date: 2023-12-09 01:50:25.406017
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e6990a7ae19f'
down_revision = '9d026987d6f2'
branch_labels = None
depends_on = None
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('message',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('sender_id', sa.Integer(), nullable=True),
    sa.Column('recipient_id', sa.Integer(), nullable=True),
    sa.Column('body', sa.String(length=140), nullable=True),
    sa.Column('timestamp', sa.DateTime(), nullable=True),
    sa.ForeignKeyConstraint(['recipient_id'], ['user.id'], ),
    sa.ForeignKeyConstraint(['sender_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    with op.batch_alter_table('message', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_message_timestamp'), ['timestamp'], unique=False)
    op.create_table('notification',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=128), nullable=True),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('timestamp', sa.Float(), nullable=True),
    sa.Column('payload_json', sa.Text(), nullable=True),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    with op.batch_alter_table('notification', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_notification_name'), ['name'], unique=False)
        batch_op.create_index(batch_op.f('ix_notification_timestamp'), ['timestamp'], unique=False)
    op.create_table('comment',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('body', sa.String(length=140), nullable=True),
    sa.Column('timestamp', sa.DateTime(), nullable=True),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('post_id', sa.Integer(), nullable=True),
    sa.Column('body_html', sa.Text(), nullable=True),
    sa.ForeignKeyConstraint(['post_id'], ['post.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    with op.batch_alter_table('comment', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_comment_timestamp'), ['timestamp'], unique=False)
    with op.batch_alter_table('post', schema=None) as batch_op:
        batch_op.add_column(sa.Column('language', sa.String(length=5), nullable=True))
        batch_op.add_column(sa.Column('body_html', sa.Text(), nullable=True))
        batch_op.alter_column('body',
               existing_type=sa.VARCHAR(length=140),
               type_=sa.Text(),
               existing_nullable=True)
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.add_column(sa.Column('token', sa.String(length=32), nullable=True))
        batch_op.add_column(sa.Column('token_expiration', sa.DateTime(), nullable=True))
        batch_op.add_column(sa.Column('last_message_read_time', sa.DateTime(), nullable=True))
        batch_op.create_index(batch_op.f('ix_user_token'), ['token'], unique=True)
       # ### end Alembic commands ###
def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_user_token'))
        batch_op.drop_column('last_message_read_time')
        batch_op.drop_column('token_expiration')
        batch_op.drop_column('token')
    with op.batch_alter_table('post', schema=None) as batch_op:
        batch_op.alter_column('body',
               existing_type=sa.Text(),
               type_=sa.VARCHAR(length=140),
               existing_nullable=True)
        batch_op.drop_column('body_html')
        batch_op.drop_column('language')
    with op.batch_alter_table('comment', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_comment_timestamp'))
    op.drop_table('comment')
    with op.batch_alter_table('notification', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_notification_timestamp'))
        batch_op.drop_index(batch_op.f('ix_notification_name'))
    op.drop_table('notification')
    with op.batch_alter_table('message', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_message_timestamp'))
    op.drop_table('message')
    # ### end Alembic commands ###

You mention local files; are you doing development on PythonAnywhere, so that the code that you have locally differs from the code on here? Or would you expect the same code in both places? Normally you would keep code and migrations together, so you'd expect the same migrations with the same code.

No, all codes has been completed locally and then deploymented on PythonAnywhere, so the code is same. Because the local runs smoothly, I then try to compare it with online code to figure out why it fails to work properly online.

No, all codes has been completed locally and then deploymented on PythonAnywhere, so the code is same. Because the local runs smoothly, I then try to compare it with online code to figure out why it fails to work properly online.

But you said earlier:

Compare the above with my local file, I found two extra file e6990a7ae19f_.py and 9d026987d6f2_.py, and the latter is the last version which produced logging problems, the former is now database stand on.

Do you mean that you have migration files on PythonAnywhere that you don't have locally?

Yes, I mean these two files is migration version file that local file does not contain. The content in them is listed above

I think, from your previous messages, that you may have created extra migrations on PythonAnywhere that were based on a different starting point in the database. I don't think we know enough about alembic to help you further. Perhaps you can find a forum dedicated to alembic where people that are familiar with it can help you.

Thank you so much, I really apperciate your help!