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

flask 怎么调用 sqlite

  •  
  •   honmaple · 2015-10-30 20:49:12 +08:00 · 2713 次点击
    这是一个创建于 3108 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需要将 db 里的数据输出到网页,不知道为什么一直不对

    下面是部分源码

    books = get_db()
    cur = books.execute('select * from BOOKS')
    id = []
    for row in cur:
    id.append(row[0])
    ID = id
    return render_template("index.html",ID=ID)

    函数

    DATABASE = 'books.db'
    def init_db():
        with closing(connect_db()) as db:
            with app.open_resource('schema.sql', mode='r') as f:
                db.cursor().executescript(f.read())
            db.commit()
    
    def connect_db():
        return sqlite3.connect(DATABASE)
    def get_db():
        db = getattr(g, '_database', None)
        if db is None:
            db = g._database = connect_db()
        return db
    

    模板

    {% for i in ID %}
        <div>{{i}}</div>
        {% endfor %}
    

    确定 books.db 里有数据,但结果什么都不显示

    4 条回复    2015-10-31 11:17:40 +08:00
    SErHo
        1
    SErHo  
       2015-10-30 21:11:01 +08:00
    DATABASE 用绝对路径试试?
    honmaple
        2
    honmaple  
    OP
       2015-10-30 21:25:41 +08:00
    @SErHo 试过了,出现 can't open database 还是什么的又换回来了
    ericls
        3
    ericls  
       2015-10-31 04:29:22 +08:00
    flask 调用 sqlite 的方式和 python  调用 sqlite 的方式一样

    你可以先不用渲染模板 直接在 shell 里面试一试
    honmaple
        4
    honmaple  
    OP
       2015-10-31 11:17:40 +08:00
    @ericls @SErHo 多谢回答,已经解决了,使用
    g.db = sqlite3.connect(database)
    cur = g.db.execute('SELECT * from BOOKS')
    Recipes = [dict(ID=row[0],
    TYPE=row[1],
    CONTENT=row[2]) for row in cur.fetchall()]
    g.db.close()
    return render_template("index.html",ID=ID)
    database 使用绝对路径
    就这几句就行,没用什么函数,也不知道官方文档为什么讲的那么复杂,还不明不白
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2261 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 03:36 · PVG 11:36 · LAX 20:36 · JFK 23:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.