最近比较忙
快速玩Flask框架,为微博做些准备
part 1 python程序
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
#wtf表单验证
app.config[‘SECRET_KEY‘] = ‘hard to guess string‘
#数据库URL
app.config[‘SQLALCHEMY_DATABASE_URI‘] = \
‘sqlite:///‘ + os.path.join(basedir, ‘data.sqlite‘)
#每次请求结束后自动提交数据变动
app.config[‘SQLALCHEMY_COMMIT_ON_TEARDOWN‘] = True
bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)
manager = Manager(app)
#wtf表单类
class NameForm(Form):
name = StringField(‘What is your name?‘, validators=[Required()])
submit = SubmitField(‘Submit‘)
#数据库中的table类
class Role(db.Model):
__tablename__ = ‘roles‘
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship(‘User‘, backref=‘role‘, lazy=‘dynamic‘)
def __repr__(self):
return ‘<Role %r>‘ % self.name
class User(db.Model):
__tablename__ = ‘users‘
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey(‘roles.id‘))
def __repr__(self):
return ‘<User %r>‘ % self.username
#主页
@app.route(‘/‘, methods=[‘GET‘, ‘POST‘])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session[‘known‘] = False
else:
session[‘known‘] = True
session[‘name‘] = form.name.data
form.name.data = ‘‘
return redirect(url_for(‘index‘))
return render_template(‘user.html‘, form=form, name=session.get(‘name‘), known=session.get(‘known‘, False),
current_time=datetime.utcnow())
#404页
@app.errorhandler(404)
def page_not_found(e):
return render_template(‘404.html‘), 404
#500页
@app.errorhandler(500)
def internal_server_error(e):
return render_template(‘500.html‘), 500
#manager.run() 用于是服务器在命令行运行
if __name__ == ‘__main__‘:
app.run(debug=True)
# manager.run()
part 2 基模板
主页面:
<!-- 基于bootstrap/base.html的基模板 默认有导航栏 page——content可重写-->
{% extends "bootstrap/base.html" %}
<!-- 导入moment.js -->
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
{% block title %}Flasky{% endblock %}
{% block head %}
{{ super() }}
<link rel="shortcut icon" href="{{ url_for(‘static‘, filename = ‘favicon.ico‘) }}"
type="image/x-icon">
<link rel="icon" href="{{ url_for(‘static‘, filename = ‘favicon.ico‘) }}"
type="image/x-icon">
{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle"
data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<!-- 弹出警告信息-->
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endblock %}
</div>
{% endblock %}
自定义错误页面:
<!DOCTYPE html>
{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Not Found</h1>
</div>
{% endblock %}
时间: 2024-10-26 14:37:04