(flask 0.11)web 新手求助,在官网上下载其 DEMOflaskr 运行出错 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dengqianyi

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

  •  
  •   dengqianyi 2014 年 8 月 22 日 8857 次点击
    这是一个创建于 4265 天前的主题,其中的信息可能已经有所发展或是发生改变。
    这个是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 successflly 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'))
    3 条回复    2014-08-29 11:11:01 +08:00
    dengqianyi
        1
    dengqianyi  
    OP
       2014 年 8 月 22 日
    问题解决了,我把g对象全关了以后就可以过了。很奇怪g为啥会导致RuntimeError: Working outside of application context.这种错误
    tolbkni
        2
    tolbkni  
       2014 年 8 月 22 日
    因为你尝试在 application context 外调用 g
    dengqianyi
        3
    dengqianyi  
    OP
       2014 年 8 月 29 日
    @tolbkni 我觉得是我没理解好flask的g对象。
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     2739 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 34ms UTC 09:50 PVG 17:50 LAX 02:50 JFK 05:50
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86