(flask 0.11)web 新手求助,在官网上下载其 DEMO——flaskr 运行出错

2014-08-22 10:32:03 +08:00
 dengqianyi
这个是log
Traceback (most recent call last):
File "/Users/manyou/myweb/flask-master/bin/flask", line 9, in <module>
load_entry_point('Flask==0.11-dev-20140822', 'console_scripts', 'flask')()
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/Flask-0.11_dev_20140822-py2.7.egg/flask/cli.py", line 444, in main
cli.main(args=args, prog_name=name)
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/Flask-0.11_dev_20140822-py2.7.egg/flask/cli.py", line 303, in main
return click.Group.main(self, *args, **kwargs)
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/click-3.1-py2.7.egg/click/core.py", line 552, in main
rv = self.invoke(ctx)
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/click-3.1-py2.7.egg/click/core.py", line 893, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/click-3.1-py2.7.egg/click/core.py", line 744, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/click-3.1-py2.7.egg/click/core.py", line 388, in invoke
return callback(*args, **kwargs)
File "/Users/manyou/myweb/flask-master/app/flaskr/flaskr.py", line 53, in initdb_command
init_db()
File "/Users/manyou/myweb/flask-master/app/flaskr/flaskr.py", line 44, in init_db
db = get_db()
File "/Users/manyou/myweb/flask-master/app/flaskr/flaskr.py", line 64, in get_db
g.sqlite_db = _result
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/Werkzeug-0.9.6-py2.7.egg/werkzeug/local.py", line 355, in <lambda>
__setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/Werkzeug-0.9.6-py2.7.egg/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/manyou/myweb/flask-master/lib/python2.7/site-packages/Flask-0.11_dev_20140822-py2.7.egg/flask/globals.py", line 44, in _lookup_app_object
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.

其DEMO代码如下:
# -*- coding: utf-8 -*-
"""
Flaskr
~~~~~~

A microblog example application written as Flask tutorial with
Flask and sqlite3.

:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""

import os
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash


# create our little application :)
app = Flask(__name__)

# Load default config and override config from an environment variable
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'flaskr.db'),
DEBUG=True,
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
# app.config.from_envvar('FLASKR_SETTINGS', silent=True)


def connect_db():
"""Connects to the specific database."""
_dataBasePath = app.config['DATABASE']
print '_dataBasePath',_dataBasePath
rv = sqlite3.connect(_dataBasePath)
rv.row_factory = sqlite3.Row
return rv


def init_db():
"""Initializes the database."""
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()


@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
init_db()
print('Initialized the database.')


def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
_result = connect_db()
print '_result',_result
g.sqlite_db = _result
return g.sqlite_db


@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()


@app.route('/')
def show_entries():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)


@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute('insert into entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']])
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))


@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)


@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
8076 次点击
所在节点    Python
3 条回复
dengqianyi
2014-08-22 11:30:47 +08:00
问题解决了,我把g对象全关了以后就可以过了。很奇怪g为啥会导致RuntimeError: Working outside of application context.这种错误
tolbkni
2014-08-22 11:48:17 +08:00
因为你尝试在 application context 外调用 g
dengqianyi
2014-08-29 11:11:01 +08:00
@tolbkni 我觉得是我没理解好flask的g对象。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/129273

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX