部署flask项目到heroku上时,出现psycopg2.errors.UndefinedTable: relation "question" does not exist问题,该怎么解决?

当我把flask项目部署到heroku上后,打开app时显示**Internal Server Error**. 报错为

psycopg2.errors.UndefinedTable: relation "question" does not exist

我google下,可能是由于migrations文件导致的,于是我就把该文件删掉了。但依然出现同样的问题。

求大神帮忙,现在踩在坑里有点出不去了。

这是我的config.py文件:

import os

DEBUG = True

SECRET_KEY = os.urandom(24)

MAX_CONTENT_LENGTH = 1 * 1024 * 1024

SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')

SQLALCHEMY_TRACK_MODIFICATIONS=False

下面是heroku 的logs:

2019-11-17T08:43:29.637889+00:00 app[web.1]: [2019-11-17 08:43:29 +0000] [11] [ERROR] Error handling request /
2019-11-17T08:43:29.637935+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T08:43:29.637940+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T08:43:29.637942+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T08:43:29.637945+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T08:43:29.637947+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T08:43:29.637949+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "question" does not exist
2019-11-17T08:43:29.637952+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T08:43:29.637955+00:00 app[web.1]: ^
2019-11-17T08:43:29.637956+00:00 app[web.1]:
2019-11-17T08:43:29.637958+00:00 app[web.1]:
2019-11-17T08:43:29.637960+00:00 app[web.1]: The above exception was the direct cause of the following exception:
2019-11-17T08:43:29.637962+00:00 app[web.1]:
2019-11-17T08:43:29.637964+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T08:43:29.637966+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 134, in handle
2019-11-17T08:43:29.637968+00:00 app[web.1]: self.handle_request(listener, req, client, addr)
2019-11-17T08:43:29.637970+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request
2019-11-17T08:43:29.637972+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2019-11-17T08:43:29.637984+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
2019-11-17T08:43:29.637986+00:00 app[web.1]: return self.wsgi_app(environ, start_response)
2019-11-17T08:43:29.637988+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
2019-11-17T08:43:29.637990+00:00 app[web.1]: response = self.handle_exception(e)
2019-11-17T08:43:29.637992+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
2019-11-17T08:43:29.637993+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T08:43:29.637995+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T08:43:29.637997+00:00 app[web.1]: raise value
2019-11-17T08:43:29.637999+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
2019-11-17T08:43:29.638000+00:00 app[web.1]: response = self.full_dispatch_request()
2019-11-17T08:43:29.638002+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
2019-11-17T08:43:29.638004+00:00 app[web.1]: rv = self.handle_user_exception(e)
2019-11-17T08:43:29.638006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
2019-11-17T08:43:29.638008+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T08:43:29.638010+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T08:43:29.638011+00:00 app[web.1]: raise value
2019-11-17T08:43:29.638013+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
2019-11-17T08:43:29.638015+00:00 app[web.1]: rv = self.dispatch_request()
2019-11-17T08:43:29.638017+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
2019-11-17T08:43:29.638019+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args)
2019-11-17T08:43:29.638021+00:00 app[web.1]: File "/app/project.py", line 27, in index
2019-11-17T08:43:29.638023+00:00 app[web.1]: 'questions': Questions.query.order_by(desc('create_time')).all()
2019-11-17T08:43:29.638025+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3186, in all
2019-11-17T08:43:29.638027+00:00 app[web.1]: return list(self)
2019-11-17T08:43:29.638029+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3342, in __iter__
2019-11-17T08:43:29.638031+00:00 app[web.1]: return self._execute_and_instances(context)
2019-11-17T08:43:29.638033+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3367, in _execute_and_instances
2019-11-17T08:43:29.638035+00:00 app[web.1]: result = conn.execute(querycontext.statement, self._params)
2019-11-17T08:43:29.638037+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
2019-11-17T08:43:29.638039+00:00 app[web.1]: return meth(self, multiparams, params)
2019-11-17T08:43:29.638041+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
2019-11-17T08:43:29.638043+00:00 app[web.1]: return connection._execute_clauseelement(self, multiparams, params)
2019-11-17T08:43:29.638045+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
2019-11-17T08:43:29.638047+00:00 app[web.1]: distilled_params,
2019-11-17T08:43:29.638049+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1253, in _execute_context
2019-11-17T08:43:29.638051+00:00 app[web.1]: e, statement, parameters, cursor, context
2019-11-17T08:43:29.638053+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
2019-11-17T08:43:29.638055+00:00 app[web.1]: util.raise_from_cause(sqlalchemy_exception, exc_info)
2019-11-17T08:43:29.638057+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
2019-11-17T08:43:29.638059+00:00 app[web.1]: reraise(type(exception), exception, tb=exc_tb, cause=cause)
2019-11-17T08:43:29.638061+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
2019-11-17T08:43:29.638063+00:00 app[web.1]: raise value.with_traceback(tb)
2019-11-17T08:43:29.638076+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T08:43:29.638079+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T08:43:29.638081+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T08:43:29.638083+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T08:43:29.638085+00:00 app[web.1]: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "question" does not exist
2019-11-17T08:43:29.638087+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T08:43:29.638089+00:00 app[web.1]: ^
2019-11-17T08:43:29.638091+00:00 app[web.1]:
2019-11-17T08:43:29.638095+00:00 app[web.1]: [SQL: SELECT question.id AS question_id, question.title AS question_title, question.content AS question_content, question.create_time AS question_create_time, question.author_id AS question_author_id
2019-11-17T08:43:29.638097+00:00 app[web.1]: FROM question ORDER BY question.create_time DESC]
2019-11-17T08:43:29.638099+00:00 app[web.1]: (Background on this error at: http://sqlalche.me/e/f405)
2019-11-17T08:43:29.638285+00:00 app[web.1]: 10.61.164.89 - - [17/Nov/2019:08:43:29 +0000] "GET / HTTP/1.1" 500 0 "-" "-"
2019-11-17T08:44:42.918911+00:00 app[web.1]: [2019-11-17 08:44:42 +0000] [11] [ERROR] Error handling request /
2019-11-17T08:44:42.918940+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T08:44:42.918944+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T08:44:42.918946+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T08:44:42.918948+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T08:44:42.918950+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T08:44:42.918952+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "question" does not exist
2019-11-17T08:44:42.918955+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T08:44:42.918957+00:00 app[web.1]: ^
2019-11-17T08:44:42.918959+00:00 app[web.1]:
2019-11-17T08:44:42.918961+00:00 app[web.1]:
2019-11-17T08:44:42.918963+00:00 app[web.1]: The above exception was the direct cause of the following exception:
2019-11-17T08:44:42.918965+00:00 app[web.1]:
2019-11-17T08:44:42.918967+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T08:44:42.918969+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 134, in handle
2019-11-17T08:44:42.918971+00:00 app[web.1]: self.handle_request(listener, req, client, addr)
2019-11-17T08:44:42.918973+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request
2019-11-17T08:44:42.918975+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2019-11-17T08:44:42.918977+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
2019-11-17T08:44:42.918979+00:00 app[web.1]: return self.wsgi_app(environ, start_response)
2019-11-17T08:44:42.918981+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
2019-11-17T08:44:42.918983+00:00 app[web.1]: response = self.handle_exception(e)
2019-11-17T08:44:42.918985+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
2019-11-17T08:44:42.918988+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T08:44:42.918989+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T08:44:42.918991+00:00 app[web.1]: raise value
2019-11-17T08:44:42.918994+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
2019-11-17T08:44:42.918996+00:00 app[web.1]: response = self.full_dispatch_request()
2019-11-17T08:44:42.918998+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
2019-11-17T08:44:42.919000+00:00 app[web.1]: rv = self.handle_user_exception(e)
2019-11-17T08:44:42.919002+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
2019-11-17T08:44:42.919004+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T08:44:42.919006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T08:44:42.919008+00:00 app[web.1]: raise value
2019-11-17T08:44:42.919010+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
2019-11-17T08:44:42.919012+00:00 app[web.1]: rv = self.dispatch_request()
2019-11-17T08:44:42.919014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
2019-11-17T08:44:42.919016+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args)
2019-11-17T08:44:42.919018+00:00 app[web.1]: File "/app/project.py", line 27, in index
2019-11-17T08:44:42.919020+00:00 app[web.1]: 'questions': Questions.query.order_by(desc('create_time')).all()
2019-11-17T08:44:42.919022+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3186, in all
2019-11-17T08:44:42.919025+00:00 app[web.1]: return list(self)
2019-11-17T08:44:42.919027+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3342, in __iter__
2019-11-17T08:44:42.919028+00:00 app[web.1]: return self._execute_and_instances(context)
2019-11-17T08:44:42.919031+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3367, in _execute_and_instances
2019-11-17T08:44:42.919033+00:00 app[web.1]: result = conn.execute(querycontext.statement, self._params)
2019-11-17T08:44:42.919035+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
2019-11-17T08:44:42.919037+00:00 app[web.1]: return meth(self, multiparams, params)
2019-11-17T08:44:42.919039+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
2019-11-17T08:44:42.919041+00:00 app[web.1]: return connection._execute_clauseelement(self, multiparams, params)
2019-11-17T08:44:42.919043+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
2019-11-17T08:44:42.919046+00:00 app[web.1]: distilled_params,
2019-11-17T08:44:42.919048+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1253, in _execute_context
2019-11-17T08:44:42.919050+00:00 app[web.1]: e, statement, parameters, cursor, context
2019-11-17T08:44:42.919052+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
2019-11-17T08:44:42.919054+00:00 app[web.1]: util.raise_from_cause(sqlalchemy_exception, exc_info)
2019-11-17T08:44:42.919056+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
2019-11-17T08:44:42.919058+00:00 app[web.1]: reraise(type(exception), exception, tb=exc_tb, cause=cause)
2019-11-17T08:44:42.919060+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
2019-11-17T08:44:42.919063+00:00 app[web.1]: raise value.with_traceback(tb)
2019-11-17T08:44:42.919074+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T08:44:42.919077+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T08:44:42.919079+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T08:44:42.919081+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T08:44:42.919083+00:00 app[web.1]: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "question" does not exist
2019-11-17T08:44:42.919085+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T08:44:42.919087+00:00 app[web.1]: ^
2019-11-17T08:44:42.919088+00:00 app[web.1]:
2019-11-17T08:44:42.919091+00:00 app[web.1]: [SQL: SELECT question.id AS question_id, question.title AS question_title, question.content AS question_content, question.create_time AS question_create_time, question.author_id AS question_author_id
2019-11-17T08:44:42.919094+00:00 app[web.1]: FROM question ORDER BY question.create_time DESC]
2019-11-17T08:44:42.919096+00:00 app[web.1]: (Background on this error at: http://sqlalche.me/e/f405)
2019-11-17T08:44:42.919234+00:00 app[web.1]: 10.5.225.117 - - [17/Nov/2019:08:44:42 +0000] "GET / HTTP/1.1" 500 0 "-" "-"
2019-11-17T08:44:42.918749+00:00 heroku[router]: at=info method=GET path="/" host=tianliang-flask-app.herokuapp.com request_id=c195162e-6529-4fb0-9aac-1d9dd9a450e8 fwd="58.182.174.147" dyno=web.1 connect=1ms service=7ms status=500 bytes=244 protocol=https
2019-11-17T09:02:25.748890+00:00 app[web.1]: [2019-11-17 09:02:25 +0000] [12] [ERROR] Error handling request /
2019-11-17T09:02:25.748917+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T09:02:25.748921+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T09:02:25.748923+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T09:02:25.748932+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T09:02:25.748934+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T09:02:25.748936+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "question" does not exist
2019-11-17T09:02:25.748939+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T09:02:25.748943+00:00 app[web.1]: ^
2019-11-17T09:02:25.748944+00:00 app[web.1]:
2019-11-17T09:02:25.748947+00:00 app[web.1]:
2019-11-17T09:02:25.748949+00:00 app[web.1]: The above exception was the direct cause of the following exception:
2019-11-17T09:02:25.748950+00:00 app[web.1]:
2019-11-17T09:02:25.748952+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T09:02:25.748953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 134, in handle
2019-11-17T09:02:25.748955+00:00 app[web.1]: self.handle_request(listener, req, client, addr)
2019-11-17T09:02:25.748956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request
2019-11-17T09:02:25.748958+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2019-11-17T09:02:25.748991+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
2019-11-17T09:02:25.748994+00:00 app[web.1]: return self.wsgi_app(environ, start_response)
2019-11-17T09:02:25.748996+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
2019-11-17T09:02:25.748998+00:00 app[web.1]: response = self.handle_exception(e)
2019-11-17T09:02:25.749000+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
2019-11-17T09:02:25.749002+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T09:02:25.749004+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T09:02:25.749006+00:00 app[web.1]: raise value
2019-11-17T09:02:25.749008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
2019-11-17T09:02:25.749010+00:00 app[web.1]: response = self.full_dispatch_request()
2019-11-17T09:02:25.749012+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
2019-11-17T09:02:25.749014+00:00 app[web.1]: rv = self.handle_user_exception(e)
2019-11-17T09:02:25.749016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
2019-11-17T09:02:25.749018+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T09:02:25.749020+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T09:02:25.749023+00:00 app[web.1]: raise value
2019-11-17T09:02:25.749024+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
2019-11-17T09:02:25.749026+00:00 app[web.1]: rv = self.dispatch_request()
2019-11-17T09:02:25.749027+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
2019-11-17T09:02:25.749029+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args)
2019-11-17T09:02:25.749030+00:00 app[web.1]: File "/app/project.py", line 27, in index
2019-11-17T09:02:25.749032+00:00 app[web.1]: 'questions': Questions.query.order_by(desc('create_time')).all()
2019-11-17T09:02:25.749033+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3186, in all
2019-11-17T09:02:25.749036+00:00 app[web.1]: return list(self)
2019-11-17T09:02:25.749038+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3342, in __iter__
2019-11-17T09:02:25.749039+00:00 app[web.1]: return self._execute_and_instances(context)
2019-11-17T09:02:25.749041+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3367, in _execute_and_instances
2019-11-17T09:02:25.749042+00:00 app[web.1]: result = conn.execute(querycontext.statement, self._params)
2019-11-17T09:02:25.749044+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
2019-11-17T09:02:25.749045+00:00 app[web.1]: return meth(self, multiparams, params)
2019-11-17T09:02:25.749047+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
2019-11-17T09:02:25.749048+00:00 app[web.1]: return connection._execute_clauseelement(self, multiparams, params)
2019-11-17T09:02:25.749050+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
2019-11-17T09:02:25.749051+00:00 app[web.1]: distilled_params,
2019-11-17T09:02:25.749053+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1253, in _execute_context
2019-11-17T09:02:25.749054+00:00 app[web.1]: e, statement, parameters, cursor, context
2019-11-17T09:02:25.749056+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
2019-11-17T09:02:25.749057+00:00 app[web.1]: util.raise_from_cause(sqlalchemy_exception, exc_info)
2019-11-17T09:02:25.749059+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
2019-11-17T09:02:25.749060+00:00 app[web.1]: reraise(type(exception), exception, tb=exc_tb, cause=cause)
2019-11-17T09:02:25.749062+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
2019-11-17T09:02:25.749063+00:00 app[web.1]: raise value.with_traceback(tb)
2019-11-17T09:02:25.749074+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T09:02:25.749076+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T09:02:25.749078+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T09:02:25.749080+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T09:02:25.749082+00:00 app[web.1]: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "question" does not exist
2019-11-17T09:02:25.749084+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T09:02:25.749087+00:00 app[web.1]: ^
2019-11-17T09:02:25.749089+00:00 app[web.1]:
2019-11-17T09:02:25.749092+00:00 app[web.1]: [SQL: SELECT question.id AS question_id, question.title AS question_title, question.content AS question_content, question.create_time AS question_create_time, question.author_id AS question_author_id
2019-11-17T09:02:25.749094+00:00 app[web.1]: FROM question ORDER BY question.create_time DESC]
2019-11-17T09:02:25.749096+00:00 app[web.1]: (Background on this error at: http://sqlalche.me/e/f405)
2019-11-17T09:02:25.749271+00:00 app[web.1]: 10.69.244.94 - - [17/Nov/2019:09:02:25 +0000] "GET / HTTP/1.1" 500 0 "-" "-"
2019-11-17T09:02:25.755053+00:00 heroku[router]: at=info method=GET path="/" host=tianliang-flask-app.herokuapp.com request_id=181975e4-7c78-4f7f-b131-4b1ddb544e02 fwd="58.182.174.147" dyno=web.1 connect=0ms service=92ms status=500 bytes=244 protocol=https
2019-11-17T09:06:00.663577+00:00 heroku[router]: at=info method=GET path="/" host=tianliang-flask-app.herokuapp.com request_id=571550f7-554b-42d0-b127-0a4837f6aae9 fwd="58.182.174.147" dyno=web.1 connect=1ms service=17ms status=500 bytes=244 protocol=https
2019-11-17T09:06:00.661593+00:00 app[web.1]: [2019-11-17 09:06:00 +0000] [11] [ERROR] Error handling request /
2019-11-17T09:06:00.661619+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T09:06:00.662439+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T09:06:00.662443+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T09:06:00.662447+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T09:06:00.662449+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T09:06:00.662452+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "question" does not exist
2019-11-17T09:06:00.662455+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T09:06:00.662457+00:00 app[web.1]: ^
2019-11-17T09:06:00.662459+00:00 app[web.1]:
2019-11-17T09:06:00.662461+00:00 app[web.1]:
2019-11-17T09:06:00.662464+00:00 app[web.1]: The above exception was the direct cause of the following exception:
2019-11-17T09:06:00.662466+00:00 app[web.1]:
2019-11-17T09:06:00.662471+00:00 app[web.1]: Traceback (most recent call last):
2019-11-17T09:06:00.662473+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 134, in handle
2019-11-17T09:06:00.662476+00:00 app[web.1]: self.handle_request(listener, req, client, addr)
2019-11-17T09:06:00.662478+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request
2019-11-17T09:06:00.662480+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2019-11-17T09:06:00.662483+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
2019-11-17T09:06:00.662486+00:00 app[web.1]: return self.wsgi_app(environ, start_response)
2019-11-17T09:06:00.662488+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
2019-11-17T09:06:00.662491+00:00 app[web.1]: response = self.handle_exception(e)
2019-11-17T09:06:00.662493+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
2019-11-17T09:06:00.662495+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T09:06:00.662498+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T09:06:00.662500+00:00 app[web.1]: raise value
2019-11-17T09:06:00.662502+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
2019-11-17T09:06:00.662505+00:00 app[web.1]: response = self.full_dispatch_request()
2019-11-17T09:06:00.662507+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
2019-11-17T09:06:00.662509+00:00 app[web.1]: rv = self.handle_user_exception(e)
2019-11-17T09:06:00.662511+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
2019-11-17T09:06:00.662513+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2019-11-17T09:06:00.662515+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2019-11-17T09:06:00.662517+00:00 app[web.1]: raise value
2019-11-17T09:06:00.662519+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
2019-11-17T09:06:00.662521+00:00 app[web.1]: rv = self.dispatch_request()
2019-11-17T09:06:00.662523+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
2019-11-17T09:06:00.662526+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args)
2019-11-17T09:06:00.662528+00:00 app[web.1]: File "/app/project.py", line 27, in index
2019-11-17T09:06:00.662530+00:00 app[web.1]: 'questions': Questions.query.order_by(desc('create_time')).all()
2019-11-17T09:06:00.662532+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3186, in all
2019-11-17T09:06:00.662535+00:00 app[web.1]: return list(self)
2019-11-17T09:06:00.662537+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3342, in __iter__
2019-11-17T09:06:00.662539+00:00 app[web.1]: return self._execute_and_instances(context)
2019-11-17T09:06:00.662541+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3367, in _execute_and_instances
2019-11-17T09:06:00.662544+00:00 app[web.1]: result = conn.execute(querycontext.statement, self._params)
2019-11-17T09:06:00.662546+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
2019-11-17T09:06:00.662548+00:00 app[web.1]: return meth(self, multiparams, params)
2019-11-17T09:06:00.662550+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
2019-11-17T09:06:00.662552+00:00 app[web.1]: return connection._execute_clauseelement(self, multiparams, params)
2019-11-17T09:06:00.662555+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
2019-11-17T09:06:00.662557+00:00 app[web.1]: distilled_params,
2019-11-17T09:06:00.662559+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1253, in _execute_context
2019-11-17T09:06:00.662562+00:00 app[web.1]: e, statement, parameters, cursor, context
2019-11-17T09:06:00.662564+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
2019-11-17T09:06:00.662566+00:00 app[web.1]: util.raise_from_cause(sqlalchemy_exception, exc_info)
2019-11-17T09:06:00.662568+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
2019-11-17T09:06:00.662570+00:00 app[web.1]: reraise(type(exception), exception, tb=exc_tb, cause=cause)
2019-11-17T09:06:00.662573+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
2019-11-17T09:06:00.662575+00:00 app[web.1]: raise value.with_traceback(tb)
2019-11-17T09:06:00.662587+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
2019-11-17T09:06:00.662590+00:00 app[web.1]: cursor, statement, parameters, context
2019-11-17T09:06:00.662592+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
2019-11-17T09:06:00.662594+00:00 app[web.1]: cursor.execute(statement, parameters)
2019-11-17T09:06:00.662596+00:00 app[web.1]: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "question" does not exist
2019-11-17T09:06:00.662599+00:00 app[web.1]: LINE 2: FROM question ORDER BY question.create_time DESC
2019-11-17T09:06:00.662601+00:00 app[web.1]: ^
2019-11-17T09:06:00.662603+00:00 app[web.1]:
2019-11-17T09:06:00.662607+00:00 app[web.1]: [SQL: SELECT question.id AS question_id, question.title AS question_title, question.content AS question_content, question.create_time AS question_create_time, question.author_id AS question_author_id
2019-11-17T09:06:00.662609+00:00 app[web.1]: FROM question ORDER BY question.create_time DESC]

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
ubuntu16.04+nginx+uwsgi部署flask项目
ubuntu+nginx+uwsgi部署flask项目 启动uwsgi时报错 ![图片说明](https://img-ask.csdn.net/upload/201909/10/1568120498_466197.png) 这是uwsgi配置文件 ![图片说明](https://img-ask.csdn.net/upload/201909/10/1568120570_631163.jpg) 这是nginx配置文件 ![图片说明](https://img-ask.csdn.net/upload/201909/10/1568120618_22683.jpg) 这是目录结构
CentOS 7部署Flask项目
CentOS 7部署Flask项目后外网无法访问 使用uwsgi部署: ``` [uwsgi] # 外部访问地址,可以指定多种协议,现在用http便于调试,之后用socket http = 0.0.0.0:5000 # 指向项目目录 chdir = /root/python/ # flask启动程序文件 wsgi-file = app.py # flask在manage.py文件中的app名 callable = app # 处理器数 processes = 4 # 线程数 threads = 2 #状态检测地址 stats = 127.0.0.1:5001 ``` ![端口](https://img-ask.csdn.net/upload/201901/16/1547639721_156540.png) 已允许5000端口
为什么我的pyecharts柱形图表部署在flask后,横坐标由原来的文字标签变成数字了?
求助各位大佬!我是一个pyecharts小白,下面是我用flask部署pyecharts的代码。 ``` import pandas as pd from flask import Flask, render_template from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.charts import Timeline from pyecharts.charts import Pie app = Flask(__name__, static_folder="templates") data总=pd.read_csv('datazong.csv',encoding='utf-8') zuojia = pd.read_csv('zuojia.csv',encoding='gbk') X轴=[str(x) for x in zuojia.loc[:,'网络作家']] Y轴=[str(x) for x in zuojia.loc[:,'版税收入(万元)']] def bar_datazoom_inside() -> Timeline: tl = Timeline() for i in range(2014, 2020): c = ( Bar() .add_xaxis(list(zip(list(data总.index)))) .add_yaxis("显示",list(data总["{}".format(i)])) .set_global_opts( title_opts=opts.TitleOpts(title="纵横小说月票榜"), datazoom_opts=opts.DataZoomOpts(type_="inside"), visualmap_opts=opts.VisualMapOpts(type_="color", max_=250000, min_=200,pos_right='20',pos_top='middle'), toolbox_opts=opts.ToolboxOpts(), ) .set_series_opts( label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts( data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ] ), ) ) tl.add(c, "{}年".format(i)) return tl def pie_rosetype() -> Pie: c = ( Pie() .add( "", [list(z) for z in zip(X轴, Y轴)], radius=["30%", "60%"], center=["50%", "60%"], rosetype="area", ) .set_global_opts(title_opts=opts.TitleOpts(title="2018作家版税收入榜单",pos_top = 'middle')) .set_series_opts( label_opts=opts.TextStyleOpts(font_style='oblique') ) ) return c @app.route("/") def index(): return render_template("index.html") @app.route("/barChart") def get_bar_chart(): tl = bar_datazoom_inside() return tl.dump_options_with_quotes() @app.route("/2") def index2(): return render_template("index2.html") @app.route("/barChart2") def get_bar_chart2(): c = pie_rosetype() return c.dump_options_with_quotes() if __name__ == "__main__": app.run() ``` 代码没问题,也能够将网站部署出来,如下图: ![flask](https://img-ask.csdn.net/upload/201912/29/1577606001_509738.png) 但是!我的横坐标变成数字了,原来在jupyter简单的render后产生的可视化横坐标是正常的如: ![图片说明](https://img-ask.csdn.net/upload/201912/29/1577606183_550451.png) 请各位大佬帮帮忙,我实在搞不明白哪里出错了。 下面是我的index.html代码。 ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Awesome-pyecharts</title> <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script> <script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script> </head> <body> <div id="bar" style="width:1000px; height:600px;"></div> <script> $( function () { var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'}); $.ajax({ type: "GET", url: "http://127.0.0.1:5000/barChart", dataType: 'json', success: function (result) { chart.setOption(result); } }); } ) </script> </body> </html> ```
Flask使用不了服务器80端口
................![整个代码](https://img-ask.csdn.net/upload/202001/07/1578364356_859201.png) ............... ![在本地运行无误](https://img-ask.csdn.net/upload/202001/07/1578364392_153955.png) ...........................![服务器上报错](https://img-ask.csdn.net/upload/202001/07/1578364421_438709.png) 本地测试是没有毛病 但是在服务器上就打不开80口 不知道是哪方面的毛病 80口打不开 ,但是修改成5000就能打开 但是我需要的是80端口
flask蓝图模式下,怎么使用pymongo
``` from flask import Flask from flask-pymongo import PyMongo app = Flask(__name__) app.config.update( MONGO_HOST='localhost', MONGO_PORT=27017, MONGO_USERNAME='bjhee', MONGO_PASSWORD='111111', MONGO_DBNAME='flask' ) mongo = PyMongo(app) ``` 这是直接在入口文件里写的方法 现在加入里蓝图 home.py ``` from flask import Blueprint import mysql.connector, logging from flask_pymongo import PyMongo import app home = Blueprint('home', __name__, url_prefix='/home') mongo = PyMongo(app) // 这里应该怎么写 因为不存在app @home.route('/test') def move_tickets_to_mongo(): res = mongo.db.acct_data_logs.find({}) ``` 这里会报错, 因为找不到app
python flask_sqlalchemy如何维护一个全局查询结果
在我的webapp中,每个页面都要用到同一个一般不会变化的查询结果,为避免每次访问都需查询一次这个变量,我在views.py中弄了一个全局变量ADMIN_NOTES ``` ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() ``` 而当ADMIN_NOTE会发生变化时,如此时管理员又写入了一个新note,则重新查询数据库获得最新的ADMIN_NOTE的值,尽量减少访问数据库的次数 我本想这么实现的(中间部分不重要的代码省略了) ``` #全局变量 ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() #写入新note的函数1 @app.route('/new_note',methods=['GET','POST']) def new_note(): global ADMIN_NOTES data=json.loads(request.get_data()) note=Note(title=data['note_title'],upload_time=datetime.utcnow()) db.session.add(note) db.session.commit() #若是管理员写入新note,则重新查询并修改全局变量ADMIN_NOTES if note.author.nickname=='ADMIN': ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() KAFENUT_NOTES[0].author.nickname #能正确访问ADMIN_NOTES print(len(ADMIN_NOTES)) #正确访问ADMIN_NOTES resp['success']=True resp['text']='Upload successfully!' resp['url']=url_for('note',note_id=note.id,nickname=note.author.nickname) #浏览器接受到服务器的json之后跳转到,resp[url]所指示的页面,即下面这个页面 return json.dumps(resp) #返回note页面的函数2 @app.route('/<nickname>/note/<note_id>',methods=['GET','POST']) def note(nickname,note_id): global ADMIN_NOTES user=User.query.filter_by(nickname=nickname).first() note=Note.query.filter_by(id=note_id).first() if request.method=='GET': note.view_num+=1 db.session.add(note) db.session.commit() for nnote in ADMIN_NOTES: print(nnote.author.nickname) #出错位置 return render_template('note_page.html',note=note,admin_notes=ADMIN_NOTES) ``` 然而问题也正出在这里,当管理员写入新的note之后(即ADMIN_NOTES这个全局变量发生变化之后)重新查询的语句虽然在函数1中执行了(print出的note数量是写入新note之后的数量,)。但当用户根据函数1返回的json跳转到函数2的时候,函数2内就无法正确访问ADMIN_NOTES,准确来说无法访问nnote.author.nickname,其中author是note表用author_id这个外键连接到user表得到的,错误栈如下 ``` Traceback (most recent call last): File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "E:\vs\python\AwesomeWebApp\AwesomeWebApp\app\views.py", line 232, in note print(nnote.author.nickname) #let author.id be preloaded File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\attributes.py", line 282, in __get__ return self.impl.get(instance_state(instance), dict_) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\attributes.py", line 710, in get value = self.callable_(state, passive) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\strategies.py", line 688, in _load_for_state % (orm_util.state_str(state), self.key) sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Note at 0x26de5f41198> is not bound to a Session; lazy load operation of attribute 'author' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) ``` sqlalchemy报出detached错误 sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Note at 0x26de5f41198> is not bound to a Session; lazy load operation of attribute 'author' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) 这该怎么解决?或者还有什么其他方法实现:在我的webapp中,每个页面都要用到同一个一般不会变化的查询结果,为避免每次访问都需查询一次这个一般不会变量,我在views.py中弄了一个全局变量ADMIN_NOTES。而当ADMIN_NOTE会发生变化时,如此时管理员又写入了一个新note,则重新查询数据库获得最新的ADMIN_NOTE的值,尽量减少访问数据库的次数
Python中用flask怎么将HTML中模拟的数据替换为自己MySQL中的数据。
1.在做Python连接hive时已将数据库表中的数据查出来,去百度开源软件——ECharts中下载了一个html的模板,怎么将模板中模拟的数据替换为自己数据库表中的数据? Python代码: ``` from flask import Flask,render_template app = Flask(__name__) # 实例化app对象 @app.route('/') def yufun(): conn = connect(host="yue1", port=10000, user='root', password="123", database="db_zlf_15", auth_mechanism="PLAIN") cur = conn.cursor() cur.execute('select * from tb_zlf_15') # fetchall返回多个元组,即返回多条记录(rows),如果没有结果,则返回 () for result in cur.fetchall(): print(result) conn.close() return render_template('candlestick-sh.html') if __name__ == '__main__': app.run() ``` ## Python查出数据库表中的数据如下: ![图片说明](https://img-ask.csdn.net/upload/201912/22/1576981251_458475.jpg) ## html模板中模拟的数据: ![图片说明](https://img-ask.csdn.net/upload/201912/22/1576981374_655799.jpg) ## html模板运行的效果: ![图片说明](https://img-ask.csdn.net/upload/201912/22/1576981856_705289.jpg)
利用flask+celery+flask_mail扩展异步发送邮件时,celery会出现上下文问题,有人能解决吗?网上找了很多,都感觉很模糊
``` import random from flask import Flask, request, jsonify, render_template, current_app from celery import Celery from flask_mail import Message, Mail import settings app = Flask(__name__) app.config.from_object(settings.BaseConfig) mail = Mail(app) celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) @celery.task def send_async_email(subject, to, expire_minute): app = current_app._get_current_object() msg = Message(subject=subject, sender=app.config['MAIL_DEFAULT_SENDER'], recipients=[to]) msg.body = 'This is a test email sent from a background Celery task.' vcode = ''.join([str(i) for i in random.sample(range(0, 10), 4)]) context = { 'subject': subject, 'expire_minute': expire_minute, 'vcode': vcode, # 'debug': get_config_partial('DEBUG'), # 'debug': True, } msg.html = render_template(app.config['EMAIL_TEMPLATE'] + '.html', **context) # with app.app_context(): mail.send(msg) @app.route('/send_email', methods=['POST']) def send_email(): try: subject = request.form.get("subject") to = request.form.get("to") expire_minute = request.form.get("expire_minute") except: return jsonify({'msg': '参数有误'}) # send_async_email.delay(app, msg) send_async_email.apply_async(args=[subject, to, expire_minute]) message = '邮件发送成功' return jsonify(message=message) if __name__ == '__main__': app.run() ``` 这是我的settings文件 ``` class BaseConfig(object): CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' BACKEND = None RABBITMQ_QUEUE = 'hello' MAIL_SERVER = 'smtp.163.com ' MAIL_PORT = 25 MAIL_USE_TLS = True MAIL_USERNAME = 'mini@ 163.com' MAIL_PASSWORD = '1314AC' MAIL_DEFAULT_SENDER = 'mini @ 163.com' DEFAULT_FROM_EMAIL = 'mini @ 163.com' EMAIL_TEMPLATE = 'email' ```
关于跨域发送post请求
1.接口用Python Flask RestFul开发的接口,初始化App的时候添加了cors的设置 ,然后再微信开发者工具(就是小程序开发工具)中调试可以跨域请求回结果来, 问题是:将连接发送到手机端打开就请求不到数据 2.代码如下 后端接口的cors配置如下 ``` app = Flask(__name__) CORS(app, supports_credentials=True) api = Api(app) ``` 前端请求如下 ``` var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var jsonString = xmlhttp.responseText; var objc = JSON.parse(jsonString); var json_objc1 = objc['Data'] document.getElementById("showNumber").innerHTML = "号码:" + json_objc1['name_id'] + "<br/>" + "姓名:" +json_objc1['name']; document.getElementById("button").innerHTML = "修改简介"; suessFlag = 1; } else { alert(xmlhttp.status) } //就是这里的端口和本身网站的IP是一样的,端口不同,这种跨域 var url_3 = 'https://域名:端口/getInfo xmlhttp.open("POST", url_3, true); xmlhttp.setRequestHeader('Access-Control-Allow-Origin', '*') xmlhttp.setRequestHeader("access-control-allow-credentials", "true") xmlhttp.setRequestHeader("Content-type", "application/json") xmlhttp.send(JSON.stringify(temp)); ``` **然后把xmlhttp.status的状态码打印出来,发现状态码是0,百度出来0代表还未初始化,初始化失败** **所以想问下这是什么原因哪里的参数不对**
python编码问题UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb7 in position 0: invalid start byte。
python编码问题UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb7 in position 0: invalid start byte。在写程序的时候,提示utf8编码问题,然后各种尝试都解决不了,代码不长也就不到10行,在朋友电脑上运行可以运行没问题,可能是我电脑编码问题,但是改编码之后,各种尝试都不行,恳请大佬帮忙解决。 ``` from flask import Flask # 实例化flask app = Flask(__name__) # 注册路由 @app.route("/") def index(): return "Hell" if __name__ == '__main__': # 启动flask app.run(debug = True,host="0.0.0.0",port=80)![图片说明](https://img-ask.csdn.net/upload/202001/02/1577975401_521380.png ``` 已经解决了,经过一番折腾最终发现是因为计算机名称是中文导致的问题,改过之后就好了
flask-sqlalchemy一对多的问题
``` class CmfUser(db.Model): id = db.Column(db.Integer, primary_key=True) user_nickname = db.Column(db.String(80), unique=True) user_email = db.Column(db.String(120)) favorites = db.relationship('CmfUserFavorite', backref='user', lazy='dynamic') class CmfUserFavorite(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) user_id = db.Column(db.Integer, db.ForeignKey('cmf_user.id')) ``` ``` u = CmfUserFavorite.query.filter(CmfUserFavorite.title == '222').first() # ✅ u.user返回正确 ``` 就是用户的爱好查询用户可以,但是查询用户再查询关联的爱好列表,就不不对。。 返回的一条语句 ``` f = CmfUser.query.filter(CmfUser.user_nickname == 'eddy').first() # ❌ f.favorites 返回错误 ``` ``` SELECT cmf_user_favorite.id AS cmf_user_favorite_id, cmf_user_favorite.title AS cmf_user_favorite_title, cmf_user_favorite.user_id AS cmf_user_favorite_user_id FROM cmf_user_favorite WHERE %(param_1)s = cmf_user_favorite.user_id ```
作为后端,优化才是价值所在!已尽最大能力优化,只求进一步!
视图再进一步优化! 最近遇到sql优化瓶颈 这是一个插入艺术家数据到es的sql查询, ``` SELECT a.id, a.`name`, a.pinyin, a.first_letter, a.gender, a.follow_num, a.art_num, a.audit_status, a.create_time, a.user_id, a.certificate_status, b.exhibition_id, c.avatar, c.birthday, d.academy, d.major, d.edu_degree, e.my FROM artist_artist a LEFT JOIN (SELECT t2.artist_id,GROUP_CONCAT(t1.exhibition_id SEPARATOR ' ') as exhibition_id FROM exhibition_artwork t1 LEFT JOIN artwork_artwork t2 on t1.artwork_id=t2.id and t2.removed=FALSE WHERE t1.removed=FALSE and t1.selected=TRUE GROUP BY t2.artist_id) as b on a.id=b.artist_id LEFT JOIN account_user c on a.user_id=c.id LEFT JOIN (SELECT artist_id,GROUP_CONCAT(academy SEPARATOR ',') as academy,GROUP_CONCAT(major SEPARATOR ',') as major,GROUP_CONCAT(edu_degree SEPARATOR ',') as edu_degree from artist_education WHERE removed=FALSE GROUP BY artist_id) as d on a.id=d.artist_id LEFT JOIN (select t3.artist_id,GROUP_CONCAT(CONCAT_WS(',',t3.id,t3.title,t3.category,t3.creation_age,t3.size_l,t3.size_w,t3.size_h,t3.certificate_status,t4.filename) SEPARATOR ';') as my FROM (select s.artist_id,s.id,s.title,s.category,s.creation_age,s.size_l,s.size_w,s.size_h,s.picture_id,s.create_time,s.certificate_status from artwork_artwork s where (select count(*) from artwork_artwork where artist_id = s.artist_id and create_time > s.create_time and removed=FALSE and audit_status=1)<3 and s.removed=FALSE and s.audit_status=1 order by s.create_time desc) as t3 LEFT join artwork_picture t4 on t3.picture_id=t4.id GROUP BY t3.artist_id ) as e on a.id=e.artist_id WHERE a.removed=FALSE and a.audit_status=1 and a.switch_status=TRUE ``` 这是explain的结果,优化了已经不知何处优化了 ![图片说明](https://img-ask.csdn.net/upload/202001/02/1577957090_253221.jpg) 因为需要处理的数据太过,所以子查询多,涉及的表也多,左关联的第一张表数据量在七八万,管理以后筛选只要三万,但是取数据的速度太慢了,求各位大神帮看看怎么优化?
flask连接数据库时,与pymysql插件不兼容,可以解决一下吗?
![图片说明](https://img-ask.csdn.net/upload/201911/26/1574737822_881106.png) ![图片说明](https://img-ask.csdn.net/upload/201911/26/1574737838_850335.png) 希望大佬们帮忙解决一下,谢谢!
python3.8用pyinstaller3.5导不出exe提示TypeError: an integer is required (got type bytes)
我开始以为是我代码出问题, 后来发先即使我的代码是 print ("Hello World!") 都会出现相同的问题 import requests url="https://ar.**d.cn/users/20000" headers = {"Authorization": "Basic NDM1NzY1OTU6ckgyNzdadXpaZi96VUh4b1g3bVZNQkpNMmtUZm5XUjF2ZEdwNWhlVDlDRVlzMjMvV2VBeUJaQWtyR0h2NHcvb1FTTFJjeWNxc1h******UlsS0ZpVEh5TVM5WW96cjR1SURoNkhqSFhLRkNvUWMyZ0kyNUNZTzRXYnM5aUFKRklEMjJXM3lGOE5MeklTYnF0b2g2SXB5QWo0b2FvOUR6KzRHYTlwRGNjamw2S2k3Umw2SUdKZi9Od2ZXSkFsRmJOUnliRzh3T0tZNFEySGpkbHFTSnIxc0pZa0h3TEY4enE4OEt1U3V4TzJzU29j"} r = requests.get(url, headers=headers) print (r.json()) 上面是我之前的代码,测试运行都是没问题的,但是打包exe就出错了 ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573062806_777820.jpg)
python flask在主app.py文件中定义了一个工厂函数create_app(),并且创建列一个app实例,为什么还是会报Failed to find application in module "app"的错误。
python flask在主app.py文件中定义了一个工厂函数create_app(),并且创建列一个app实例,为什么还是会报Failed to find application in module "app"的错误。 工厂函数以及main方法 ``` # --app.py def create_app(): app = Flask(__name__) app.config.from_object(config) return app if __name__ == '__main__': app = create_app() app.run() ``` 为什么还是报错: Error: Failed to find application in module "app". Are you sure it contains a Flask application? Maybe you wrapped it in a WSGI middleware or you are using a factory function.
flask import request,使用不了request.args.get
pycharm社区版 python 3.7.4 flask-1.1.1 from flask import request request下没有args ![图片说明](https://img-ask.csdn.net/upload/201910/17/1571290456_663104.png) 强行使用print出来也是None ![图片说明](https://img-ask.csdn.net/upload/201910/17/1571291695_860192.png)
flask+mysql实现的web应用,在注册页面点击注册后提示 Instance '<User at 0x5486a10>' has been deleted?
##问题描述 从github(https://github.com/num10/transfile)上下载的一个用flask+mysql实现的转pdf成word的web应用,其中 涉及到新用户的注册: ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573098094_252858.png) 可是在注册页面填完信息点击注册后前端报错如下: ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573098203_905955.png) ``` sqlalchemy.orm.exc.ObjectDeletedError: Instance '<User at 0x58072f0>' has been deleted, or its row is otherwise not present. ``` 根据traceback的信息,定位到出错的位置应该是下图中的models.py和views.py文件 ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573100399_404211.jpg) 后台关于这两个文件的报错信息为: ```ruby File "C:\Users\26808\transfile-master\app\auth\views.py", line 68, in register token = user.generate_confirmation_token() File "C:\Users\26808\transfile-master\app\models.py", line 142, in generate_confirmation_token return s.dumps({'confirm': self.id}).decode('utf-8') ``` 对应文件中: views.py: ```ruby @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, '认证您的账户', 'auth/email/confirm', user=user, token=token) flash('认证信息已发送至您的邮箱') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form) ``` models.py: ``` def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') ``` ##补充 1.按照requirements文件的要求,flask都安装了正确的包 2.正如register函数中所写的那样,点击注册后用户信息会被加入mysql数据库中但是会被重复加入,即多次运行每次都出错,并且相同的用户被反复加入mysql数据库中 3.网上大多数都是通过app.run()来启动文件的,但是这个项目里面先要设置 ```set FLASK_APP = manage.py``` 在```flask run```才能运行 能解释一下为什么吗? manage.py代码如下: ```ruby #!/usr/bin/ python # -*- coding: UTF-8 -*- import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() import sys import click from flask_migrate import Migrate,upgrade from app import create_app, db from app.models import User, Follow, Role, Permission, Post, Comment from flask_uploads import configure_uploads from app.auth.forms import pdfs,photos,words app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) configure_uploads(app, pdfs) configure_uploads(app, photos) configure_uploads(app, words) @app.shell_context_processor def make_shell_context(): return dict(db=db, User=User, Follow=Follow, Role=Role, Permission=Permission, Post=Post, Comment=Comment) @app.cli.command() @click.option('--coverage/--no-coverage', default=False, help='Run tests under code coverage.') def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import subprocess os.environ['FLASK_COVERAGE'] = '1' sys.exit(subprocess.call(sys.argv)) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() @app.cli.command() @click.option('--length', default=25, help='Number of functions to include in the profiler report.') @click.option('--profile-dir', default=None, help='Directory where profiler data files are saved.') def profile(length=25, profile_dir=None): """Start the application under the code profiler.""" from werkzeug.contrib.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) app.run(debug=False) @app.cli.command() def deploy(): """Run deployment tasks.""" # migrate database to latest revision upgrade() # create or update user roles Role.insert_roles() # ensure all users are following themselves User.add_self_follows() if __name__ == '__main__': deploy() ``` 数据模型models.py: ``` #!/usr/bin/ python # -*- coding: UTF-8 -*- from datetime import datetime import hashlib from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from markdown import markdown import bleach from flask import current_app, request,url_for from flask_login import UserMixin, AnonymousUserMixin from . import db, login_manager class Permission: FOLLOW = 1 COMMENT = 2 WRITE = 4 MODERATE = 8 ADMIN = 16 class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) default = db.Column(db.Boolean, default=False, index=True) permissions = db.Column(db.Integer) users = db.relationship('User', backref='role', lazy='dynamic') def __init__(self, **kwargs): super(Role, self).__init__(**kwargs) if self.permissions is None: self.permissions = 0 @staticmethod def insert_roles(): roles = { 'User': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE], 'Moderator': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE, Permission.MODERATE], 'Administrator': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE, Permission.MODERATE, Permission.ADMIN], } default_role = 'User' for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.reset_permissions() for perm in roles[r]: role.add_permission(perm) role.default = (role.name == default_role) db.session.add(role) db.session.commit() def add_permission(self, perm): if not self.has_permission(perm): self.permissions += perm def remove_permission(self, perm): if self.has_permission(perm): self.permissions -= perm def reset_permissions(self): self.permissions = 0 def has_permission(self, perm): return self.permissions & perm == perm def __repr__(self): return '<Role %r>' % self.name class Follow(db.Model): __tablename__ = 'follows' follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) timestamp = db.Column(db.DateTime, default=datetime.utcnow) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') @staticmethod def add_self_follows(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FLASKY_ADMIN']: self.role = Role.query.filter_by(name='Administrator').first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = self.gravatar_hash() self.follow(self) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}).decode('utf-8') @staticmethod def reset_password(token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False user = User.query.get(data.get('reset')) if user is None: return False user.password = new_password db.session.add(user) return True def can(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.can(Permission.ADMIN) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def gravatar_hash(self): return hashlib.md5(self.email.lower().encode('utf-8')).hexdigest() def gravatar(self, size=100, default='identicon', rating='g'): url = 'https://secure.gravatar.com/avatar' hash = self.avatar_hash or self.gravatar_hash() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating) def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): if user.id is None: return False return self.followed.filter_by( followed_id=user.id).first() is not None def is_followed_by(self, user): if user.id is None: return False return self.followers.filter_by( follower_id=user.id).first() is not None @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id)\ .filter(Follow.follower_id == self.id) def to_json(self): json_user = { 'url': url_for('api.get_user', id=self.id), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts_url': url_for('api.get_user_posts', id=self.id), 'followed_posts_url': url_for('api.get_user_followed_posts', id=self.id), 'post_count': self.posts.count() } return json_user def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('utf-8') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None return User.query.get(data['id']) def __repr__(self): return '<User %r>' % self.username class AnonymousUser(AnonymousUserMixin): def can(self, permissions): return False def is_administrator(self): return False login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) comments = db.relationship('Comment', backref='post', lazy='dynamic') @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): json_post = { 'url': url_for('api.get_post', id=self.id), 'body': self.body, 'body_html': self.body_html, 'timestamp': self.timestamp, 'author_url': url_for('api.get_user', id=self.author_id), 'comments_url': url_for('api.get_post_comments', id=self.id), 'comment_count': self.comments.count() } return json_post @staticmethod def from_json(json_post): body = json_post.get('body') if body is None or body == '': raise ValidationError('post does not have a body') return Post(body=body) db.event.listen(Post.body, 'set', Post.on_changed_body) class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) disabled = db.Column(db.Boolean) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) post_id = db.Column(db.Integer, db.ForeignKey('posts.id')) @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) db.event.listen(Comment.body, 'set', Comment.on_changed_body) ```
jinja2.exceptions.TemplateNotFound: bootstrap/base.html的错误wen'ti
app.py文件 ``` from flask import Flask from flask_bootstrap import Bootstrap app = Flask(__name__) bootstrap = Bootstrap(app) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/user/<name>') def user(name): return render_template('user.html', name=name) if __name__ == '__main__': app.run() ``` 在user.html文件中有高亮提示,并且有Unresolved template reference提示 ![在user.html中的高亮显示](https://img-ask.csdn.net/upload/201910/17/1571274868_305707.png) Unresolved template reference提示如下图 ![图片说明](https://img-ask.csdn.net/upload/201910/17/1571275616_173510.jpg) 文件结构如下,templates文件夹与app.py文件同级,所以不是这个问题 ![文件结构如图显示](https://img-ask.csdn.net/upload/201910/17/1571273197_582788.png) 程序能正常运行,当访问127.0.0.1:5000/user/<name>时就会出现 Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. 并且报错:jinja2.exceptions.TemplateNotFound: bootstrap/base.html 我在网上找了很多解决方案都没有用,希望有哪位大侠能帮忙解决
相见恨晚的超实用网站
搞学习 知乎:www.zhihu.com 简答题:http://www.jiandati.com/ 网易公开课:https://open.163.com/ted/ 网易云课堂:https://study.163.com/ 中国大学MOOC:www.icourse163.org 网易云课堂:study.163.com 哔哩哔哩弹幕网:www.bilibili.com 我要自学网:www.51zxw
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
引言 本文主要是记录一下面试字节跳动的经历。 三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体
源码阅读(19):Java中主要的Map结构——HashMap容器(下1)
(接上文《源码阅读(18):Java中主要的Map结构——HashMap容器(中)》) 3.4.4、HashMap添加K-V键值对(红黑树方式) 上文我们介绍了在HashMap中table数组的某个索引位上,基于单向链表添加新的K-V键值对对象(HashMap.Node&lt;K, V&gt;类的实例),但是我们同时知道在某些的场景下,HashMap中table数据的某个索引位上,数据是按照红黑树
c++制作的植物大战僵尸,开源,一代二代结合游戏
    此游戏全部由本人自己制作完成。游戏大部分的素材来源于原版游戏素材,少部分搜集于网络,以及自己制作。 此游戏为同人游戏而且仅供学习交流使用,任何人未经授权,不得对本游戏进行更改、盗用等,否则后果自负。 目前有六种僵尸和六种植物,植物和僵尸的动画都是本人做的。qq:2117610943 开源代码下载 提取码:3vzm 点击下载--&gt; 11月28日 新增四种植物 统一植物画风,全部修
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成喔~) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
深度学习图像算法在内容安全领域的应用
互联网给人们生活带来便利的同时也隐含了大量不良信息,防范互联网平台有害内容传播引起了多方面的高度关注。本次演讲从技术层面分享网易易盾在内容安全领域的算法实践经验,包括深度学习图
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程实用技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法,并会持续更新。
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
"狗屁不通文章生成器"登顶GitHub热榜,分分钟写出万字形式主义大作
GitHub 被誉为全球最大的同性交友网站,……,陪伴我们已经走过 10+ 年时间,它托管了大量的软件代码,同时也承载了程序员无尽的欢乐。 万字申请,废话报告,魔幻形式主义大作怎么写?兄dei,狗屁不通文章生成器了解一下。这个富有灵魂的项目名吸引了众人的目光。项目仅仅诞生一周,便冲上了GitHub趋势榜榜首(Js中文网 -前端进阶资源教程)、是榜首哦
推荐几款比较实用的工具,网站
1.盘百度PanDownload 这个云盘工具是免费的,可以进行资源搜索,提速(偶尔会抽风????) 不要去某站买付费的???? PanDownload下载地址 2.BeJSON 这是一款拥有各种在线工具的网站,推荐它的主要原因是网站简洁,功能齐全,广告相比其他广告好太多了 bejson网站 3.二维码美化 这个网站的二维码美化很好看,网站界面也很...
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
相关热词 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件 c#注册dll文件 c#安装.net
立即提问