zoukankan      html  css  js  c++  java
  • flasksqlalchemy 初步

      先创建数据库依赖文件如 flask-sqlalchemy.py

    from flask_sqlalchemy import SQLAlchemy 
    
    db = SQLAlchemy()

    然后,创建数据库表单,database.py

    from database_extention import db 
    
    class User(db.Model):
        id = db.Column( db.Integer, primary_key=True)
        name = db.Column( db.String( 50 ), unique = True )
        email = db.Column( db.String( 120 ), unique = True )
        password = db.Column( db.String( 120 ) )

    __tablename__ = 'users'
    def __init__( self, name, email, password ): self.name = name self.email = email self.password = password def __repr( self ): return '<User %r>' % (self.name)

    最后,在应用中引用数据库:

    from flask import Flask, session, g, render_template
    
    from database_extention import db 
    
    from database import User
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
    db.init_app( app )
    db.create_all(app =app) @app.route(
    '/') def show_home(): return "ok" @app.route('/add') def add_user(): user = User('liuchao', 'liuchao@hotmail.com', 'liu') db.session.add(user) db.session.commit() return 'save ok' @app.route('/showrecord') def show_record(): users = User.query.all() records = [ dict( username=user.name, email=user.email ) for user in users ] return render_template('showrecord.html', records = records ) if __name__ == "__main__": app.run(debug=True)

    需要注意的是,直接return records会导致TypeError: 'list' object is not callable错误。需要render_template模板来处理。

  • 相关阅读:
    hibernate之初学复合主键
    hibernate之初学增删改查
    hibernate之配置文件帮助文档
    hibernate之初学项目搭建
    Python调用OpenCV读显写
    C++写入txt
    C++逐词读取txt
    C++逐行读取txt
    C#调用C++系列二:传结构体
    C#调用C++系列一:简单传值
  • 原文地址:https://www.cnblogs.com/bracken/p/2891248.html
Copyright © 2011-2022 走看看