flask

摘要:flask-sqlalchemy 设定与查询


1. install flask-sqlalchemy

2.app/__init__.py

from flask.ext.sqlalchemy  import SQLAlchemy
from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test'
db = SQLAlchemy(app)

3.app/Model/new_table.py


from app import db

class NewTable(db.Model):
    __tablename__ = 'new_table'

    SN = db.Column(db.Integer, primary_key=True)
    NAME = db.Column(db.String)
    SEX = db.Column(db.String)
    INSERT_TIME = db.Column(db.DateTime)

    def __init__(self,sn,name,sex,insert_time):
        self.SN=sn
        self.NAME=name
        self.SEX=sex
        self.INSERT_TIME=insert_time  


        def __repr__(self):
            return "NewTable('{0}','{1}','{2}','{3}')".format(self.sn,self.Name,self.SEX,self.INSERT_TIME)

4.app/views.py

@app.route('/MyHtml')
def MyHtml():  
    tabls= NewTable.query.limit(50) #只查询50笔
    return render_template(
        'MyHtml.html',
        title='Demo',
        mydata=tabls,
        year=datetime.now().year,
        message=''
    )

5.app/templates/MyHTML.html


{% extends "layout.html" %}
{% block content %}

{{ title }}.

{{ message }}

{% for s in mydata %} {% endfor %}
SN NAME SEX INSERT_TIME
{{ s.SN }} {{ s.NAME }} {{ s.SEX }} {{ s.INSERT_TIME | datetimeformat('%Y/%m/%d') }}
{% endblock %}