【Flask】Flask快速玩框架

时间:2021-05-11 07:45:09
最近比较忙

快速玩Flask框架,为微博做些准备

part 1 python程序
  1. from flask importFlask, render_template, session, redirect, url_for, flash
  2. from flask_bootstrap importBootstrap
  3. from flask_moment importMoment
  4. from datetime import datetime
  5. from flask_wtf importForm
  6. from wtforms importStringField,SubmitField
  7. from wtforms.validators importRequired
  8. from flask_sqlalchemy importSQLAlchemy
  9. from flask_script importManager
  10. import os
  11. basedir = os.path.abspath(os.path.dirname(__file__))
  12. app =Flask(__name__)
  13. #wtf表单验证
  14. app.config['SECRET_KEY']='hard to guess string'
  15. #数据库URL
  16. app.config['SQLALCHEMY_DATABASE_URI']= \
  17. 'sqlite:///'+ os.path.join(basedir,'data.sqlite')
  18. #每次请求结束后自动提交数据变动
  19. app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
  20. bootstrap =Bootstrap(app)
  21. moment =Moment(app)
  22. db =SQLAlchemy(app)
  23. manager =Manager(app)
  24. #wtf表单类
  25. classNameForm(Form):
  26. name =StringField('What is your name?', validators=[Required()])
  27. submit =SubmitField('Submit')
  28. #数据库中的table类
  29. classRole(db.Model):
  30. __tablename__ ='roles'
  31. id = db.Column(db.Integer, primary_key=True)
  32. name = db.Column(db.String(64), unique=True)
  33. users = db.relationship('User', backref='role', lazy='dynamic')
  34. def __repr__(self):
  35. return'<Role %r>'% self.name
  36. classUser(db.Model):
  37. __tablename__ ='users'
  38. id = db.Column(db.Integer, primary_key=True)
  39. username = db.Column(db.String(64), unique=True, index=True)
  40. role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
  41. def __repr__(self):
  42. return'<User %r>'% self.username
  43. #主页
  44. @app.route('/', methods=['GET','POST'])
  45. def index():
  46. form =NameForm()
  47. if form.validate_on_submit():
  48. user =User.query.filter_by(username=form.name.data).first()
  49. if user isNone:
  50. user =User(username=form.name.data)
  51. db.session.add(user)
  52. session['known']=False
  53. else:
  54. session['known']=True
  55. session['name']= form.name.data
  56. form.name.data =''
  57. return redirect(url_for('index'))
  58. return render_template('user.html', form=form, name=session.get('name'), known=session.get('known',False),
  59. current_time=datetime.utcnow())
  60. #404页
  61. @app.errorhandler(404)
  62. def page_not_found(e):
  63. return render_template('404.html'),404
  64. #500页
  65. @app.errorhandler(500)
  66. def internal_server_error(e):
  67. return render_template('500.html'),500
  68. #manager.run() 用于是服务器在命令行运行
  69. if __name__ =='__main__':
  70. app.run(debug=True)
  71. # manager.run()
part 2 基模板
主页面:
  1. <!-- 基于bootstrap/base.html的基模板 默认有导航栏 page——content可重写-->
  2. {% extends "bootstrap/base.html" %}
  3. <!-- 导入moment.js -->
  4. {% block scripts %}
  5. {{ super() }}
  6. {{ moment.include_moment() }}
  7. {% endblock %}
  8. {% block title %}Flasky{% endblock %}
  9. {% block head %}
  10. {{ super() }}
  11. <linkrel="shortcut icon"href="{{ url_for('static', filename = 'favicon.ico') }}"
  12. type="image/x-icon">
  13. <linkrel="icon"href="{{ url_for('static', filename = 'favicon.ico') }}"
  14. type="image/x-icon">
  15. {% endblock %}
  16. {% block navbar %}
  17. <divclass="navbar navbar-inverse"role="navigation">
  18. <divclass="container">
  19. <divclass="navbar-header">
  20. <buttontype="button"class="navbar-toggle"
  21. data-toggle="collapse"data-target=".navbar-collapse">
  22. <spanclass="sr-only">Toggle navigation</span>
  23. <spanclass="icon-bar"></span>
  24. <spanclass="icon-bar"></span>
  25. <spanclass="icon-bar"></span>
  26. </button>
  27. <aclass="navbar-brand"href="/">Flasky</a>
  28. </div>
  29. <divclass="navbar-collapse collapse">
  30. <ulclass="nav navbar-nav">
  31. <li><ahref="/">Home</a></li>
  32. </ul>
  33. </div>
  34. </div>
  35. </div>
  36. {% endblock %}
  37. {% block content %}
  38. <!-- 弹出警告信息-->
  39. <divclass="container">
  40. {% for message in get_flashed_messages() %}
  41. <divclass="alert alert-warning">
  42. <buttontype="button"class="close"data-dismiss="alert">×</button>
  43. {{ message }}
  44. </div>
  45. {% endfor %}
  46. {% block page_content %}{% endblock %}
  47. </div>
  48. {% endblock %}
自定义错误页面:
  1. <!DOCTYPE html>
  2. {% extends "base.html" %}
  3. {% block title %}Flasky - Page Not Found{% endblock %}
  4. {% block page_content %}
  5. <divclass="page-header">
  6. <h1>Not Found</h1>
  7. </div>
  8. {% endblock %}