摘要: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 %}
<h2>{{ title }}.</h2>
<h3>{{ message }}</h3>
<table class="table">
<thead>
<tr>
<th>SN</th>
<th>NAME</th>
<th>SEX</th>
<th>INSERT_TIME</th>
</tr>
</thead>
<tbody>
{% for s in mydata %}
<tr>
<td><span class=flash>{{ s.SN }}</span></td>
<td><span class=flash>{{ s.NAME }}</span></td>
<td><span class=flash>{{ s.SEX }}</span></td>
<td><span class=flash>{{ s.INSERT_TIME | datetimeformat('%Y/%m/%d') }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}