from flask import Flask,session,render_template,redirect,url_for,flash
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import Required,Email
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
from sql_learn import User
import pymysql,os
from flask.ext.mail import Mail,Message
from threading import Thread
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:19931218@localhost/test'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['MAIL_SERVER'] = 'smtp.163.com'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '[email protected]'#input('Your Email account')
app.config['MAIL_PASSWORD'] = 'XXXXXXX'#input('your Email password')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <[email protected]>'
app.config['FLASKY_ADMIN'] = '[email protected]'
mail = Mail(app)
db = SQLAlchemy(app)
boots = Bootstrap(app)
def send_async_email(app, msg):#异步发送邮件
with app.app_context():#创建程序上下文. (push/pop),其实就是让current_app指向当前的app
mail.send(msg)
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])#创建一个线程,目标函数是异步发送的邮件
thr.start()#开启线程
return thr
#*********名字表单*****************#
class NameForm(Form):
name = StringField('What is your name?', validators=[Required()])#文本框
submit = SubmitField('Submit')#提交表单,大都作为POST方法来提交
@app.route('/',methods = ['GET','POST'])#在URL注册的时候将这个这个视图函数注册为GET和POST,如果没有指定,就ishi只有GET
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,email = '')
print(user)
#db.session.add(user)
session['known'] = False
if app.config['FLASKY_ADMIN']:
#send_email(app.config['FLASKY_ADMIN'], 'New User','mail/new_user', user=user)
print('sucess send email')
else:
session['known'] = True
session['name'] = form.name.data#获取表单中name字段的数据并且保存在会话里面,注意如果传入form.name就会变成一个输入框..
form.name.data = ''#把表单数据清空
return redirect(url_for('index'))#使用重定向,把post请求的响应指向一个url,这样就会产生一个get请求
return render_template('index.html',form = NameForm(),name = session.get('name'),known = session.get('known'))
@app.route('/user/<name>')
def user(name):
return render_template('user.html',name = name)
if __name__ == '__main__':
app.run()#直接运行在5000端口上面
****base.html*
{% extends "bootstrap/base.html" %} {% block title %}Flasky{% 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 %}
index.html****
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} <div class="page-header"> <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}! {%if not known%} <p>Pleased to meet you!</p> {%else%} <p>Happy to see you again!</p> {%endif%} </h1> </div> {{ wtf.quick_form(form) }} {% endblock %}