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
V2EX  ›  Python

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

  •  
  •   dengqianyi · 2014-08-22 10:32:03 +08:00 · 8052 次点击
    这是一个创建于 3747 天前的主题,其中的信息可能已经有所发展或是发生改变。
    这个是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'))
    3 条回复    2014-08-29 11:11:01 +08:00
    dengqianyi
        1
    dengqianyi  
    OP
       2014-08-22 11:30:47 +08:00
    问题解决了,我把g对象全关了以后就可以过了。很奇怪g为啥会导致RuntimeError: Working outside of application context.这种错误
    tolbkni
        2
    tolbkni  
       2014-08-22 11:48:17 +08:00
    因为你尝试在 application context 外调用 g
    dengqianyi
        3
    dengqianyi  
    OP
       2014-08-29 11:11:01 +08:00
    @tolbkni 我觉得是我没理解好flask的g对象。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   901 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:01 · PVG 06:01 · LAX 14:01 · JFK 17:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.