#!/usr/bin/python
# -*- coding: UTF-8 -*- from flask import Flask, url_for
from flask import request
from flask_script import Manager
from flask import render_template
from threading import Thread
import requests
import json
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required, DataRequired
from flask import session
from flask import redirect
from flask import flash
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import os
basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__)
manager = Manager(app)
Bootstrap(app)
Moment(app)
########################################DB config start################################################################
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
########################################DB config end################################################################
app.config['SECRET_KEY'] = 'hard to guess string' @app.route("/", methods=["GET"])
def index():
return '<h1>Hello World!</h1>' # 动态路由
@app.route("/user/<username>")
def get_username(username):
return '<h1>Hello, %s</h1>' % username # 获得请求参数:
@app.route("/getrequest")
def get_request_arg():
headers = request.headers
user_agent = request.headers.get('User-Agent')
return '<h1>geted request args is : %s </h1>' % user_agent @app.route("/getpostdata", methods=['GET', 'POST','GET'])
def get_post_data():
post_data = request.json
# post_data = request.form
return "<h1>post data is :%s</h1>" % post_data # get index.html
@app.route("/get_index_html")
def get_index():
return render_template("index.html") # get user.html and argument 动态路由并获取参数给模板
@app.route("/get_user_html/<user>")
def get_user(user):
return render_template("user.html", name=user) @app.route("/get_list_html")
def get_list():
item_list = ["python","java","c++","c#","django","flask"]
return render_template("list.html", lists=item_list) @app.route("/get_dict_html")
def get_dict():
dict = {"name":"panxueyan", "age":30,"address":"beijing"}
# f = client_for_flask.post_data
return render_template("dict.html", dicts=dict) def test_mehod():
# r = requests.get("http://127.0.0.1:9000/getrequest")
# print(r.text)
# print("call done")
# return "donee" url = "http://127.0.0.1:9000/getpostdata" data = {"result": "ok"}
data = json.dumps(data)
r = requests.post(url, json=data)
print(r.text)
print("hello call method") # 利用多线程 把函数方法传入模板执行
@app.route("/call_method_html")
def call_method():
t = Thread(target=test_mehod)
method = t.start
return render_template("call_method.html", methods=method) # 过滤器在模板中的使用
@app.route("/filter_useage")
def filter_use():
my_dict = {"name":"panxueya\n","age":30,"address":"<h1>beijing</h1>","daxieshouzimu":"this is xiaoxie","quandaxie":"DONE","qukongge":" hha "}
return render_template("filter.html", dicts=my_dict) # 宏在模板中的使用宏类似于 Python 代码中的函数
@app.route("/hong_useage")
def hong_use():
item_list = ["python", "java", "c++", "c#", "django", "flask"]
return render_template("hong.html", comments=item_list) #把宏保存为html模板,然后在其他模板中导入使用
@app.route("/hone_template_useage")
def hone_template_use():
item_list = ["python", "java", "c++", "c#", "django", "flask"]
return render_template("test_macros_template.html", comments=item_list) #测试模板继承 base是母模板 son是继承base.html
@app.route("/son_use_father_template")
def son_use_father():
return render_template("son.html") @app.route("/test_bootstrap/<name>")
def get_bootstrap(name):
return render_template("test_bootstrap.html", name=name) @app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404 @app.route("/get_some_url")
def get_soome_url():
url = url_for("son_use_father", _external=True)
print(url)
return render_template("get_url_template.html",urls=url) @app.route("/get_datetime")
def get_datetime(): return render_template("test_datetime.html", current_time=datetime.utcnow()) ####################################table model start#################################################
class NameForm(Form):
name = StringField('What is your name?', validators=[DataRequired()])
submit = SubmitField('Submit') 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')
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 #######################################table model end############################################## @app.route("/test_form",methods=["GET","POST"])
def use_form():
name = None
form = NameForm()
if form.validate_on_submit():
# # name = form.name.data
# session['name'] = form.name.data
# # form.name.data = ''
# return redirect(url_for('use_form')) old_name = session.get('name')
if old_name is not None and old_name != form.name.data:
flash('Looks like you have changed your name!')
session['name'] = form.name.data
return redirect(url_for('use_form'))
return render_template('form.html', form=form, name=session.get('name')) if __name__ == "__main__":
app.debug = True
# app.run(host="0.0.0.0", port=8080)
manager.run()

最新文章

  1. d3-画雷达图-圆形弧线
  2. 笔记(一):ES6所改良的javascript“缺陷”
  3. 25款顶级的jQuery表格插件
  4. bash: sqlplus: command not found 解决方法
  5. mapreduce (二) MapReduce实现倒排索引(一) combiner是把同一个机器上的多个map的结果先聚合一次
  6. 巧用Dictionary&lt;TKey,TValue&gt;,完成客户需求
  7. C++删除文件末尾字符
  8. Exception in thread &quot;main&quot; org.I0Itec.zkclient.exception.ZkAuthFailedException: Authentication failure is thrown while creating kafka topic
  9. mysql更改数据存储目录
  10. 1062.Talent and Virtue
  11. NOIP2018旅游记
  12. Linux安装模式AppImage,Flatpak,Snap整理
  13. [转]LRU缓存实现(Java)
  14. SharePoint 2010、2013多个域之间互信(Domain Trust)的设计与实施
  15. select查询
  16. ZLYZD团队第四周项目总结
  17. create index 与 alter table add index 区别
  18. java--由一道选择题研究数值越界
  19. MongoDB数据库进阶 --- 增删查改...
  20. em px 换算在线工具

热门文章

  1. 在一个form表单中根据不同按钮实现多个action事件
  2. dancing link 精确覆盖 重复覆盖 (DLX)
  3. 多线程之:volatile变量的一次写操作的过程
  4. 「LuoguP1341」 无序字母对(欧拉回路
  5. 最短路——Dijkstra和Floyd
  6. PHP开发api接口 -- 安全验证 生成签名
  7. C#控件刷新
  8. Linux系统如何查看版本信息?
  9. 2.13 Hive中自带Function使用及自定义UDF编程
  10. 【网络爬虫】【python】网络爬虫(四):scrapy爬虫框架(架构、win/linux安装、文件结构)