#!/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()

flask 学习app代码备份的更多相关文章

  1. Flask学习-Flask app启动过程

    因为0.1版本整体代码大概只有350行,比较简单.所以本篇文章会以Flask 0.1版本源码为基础进行剖析Flask应用的启动过程. Flask参考资料flask,官网有一个最简单app: from ...

  2. [ZHUAN]Flask学习记录之Flask-SQLAlchemy

    From: http://www.cnblogs.com/agmcs/p/4445583.html 各种查询方式:http://www.360doc.com/content/12/0608/11/93 ...

  3. 二.Flask 学习模板

    Flask 为你配置 Jinja2 模板引擎.使用 render_template() 方法可以渲染模板,只需提供模板名称和需要作为参数传递给模板的变量就可简单执行. 至于模板渲染? 简单来说,就是将 ...

  4. Python Flask学习笔记之模板

    Python Flask学习笔记之模板 Jinja2模板引擎 默认情况下,Flask在程序文件夹中的templates子文件夹中寻找模板.Flask提供的render_template函数把Jinja ...

  5. Python Flask学习笔记之Hello World

    Python Flask学习笔记之Hello World 安装virtualenv,配置Flask开发环境 virtualenv 虚拟环境是Python解释器的一个私有副本,在这个环境中可以安装私有包 ...

  6. python 全栈开发,Day142(flask标准目录结构, flask使用SQLAlchemy,flask离线脚本,flask多app应用,flask-script,flask-migrate,pipreqs)

    昨日内容回顾 1. 简述flask上下文管理 - threading.local - 偏函数 - 栈 2. 原生SQL和ORM有什么优缺点? 开发效率: ORM > 原生SQL 执行效率: 原生 ...

  7. Flask学习-Wsgiref库

    一.前言 前面在Flask学习-Flask基础之WSGI中提到了WerkZeug,我们知道,WerkZeug是一个支持WSGI协议的Server,其实还有很多其他支持WSGI协议的Server.htt ...

  8. Flask 学习篇二:学习Flask过程中的记录

    Flask学习笔记: GitHub上面的Flask实践项目 https://github.com/SilentCC/FlaskWeb 1.Application and Request Context ...

  9. Flask 学习(三)模板

    Flask 学习(三)模板 Flask 为你配置 Jinja2 模板引擎.使用 render_template() 方法可以渲染模板,只需提供模板名称和需要作为参数传递给模板的变量就可简单执行. 至于 ...

随机推荐

  1. Mybatis一二级缓存的理解

        频繁的数据库操作是非常耗费性能的(主要是因为对于DB而言,数据是持久化在磁盘中的,因此查询操作需要通过IO,IO操作速度相比内存操作速度慢了好几个量级),尤其是对于一些相同的查询语句,完全可以 ...

  2. webpack安装后package-lock.json 的作用

    这个文件主要功能是确定当前安装的包的依赖,以便后续重新安装的时候生成相同的依赖,而忽略项目开发过程中有些依赖已经发生的更新. 避免了依赖升级和当前项目不兼容!

  3. JNI——C调用JAVA

    步骤: 1. 创建虚拟机 2. 获得class 3. 实例化对象:获得构造方法(方法名为“<init>”),构造参数,调用方法 4. 调用方法:又分为获得方法,构造方法,调用方法 操作方法 ...

  4. wampServer 设置

    设置端口 打开 C:\wamp\bin\apache\apache2.4.9\conf\httpd.conf 文件 找到“Listen 80”和“ServerName localhost:80”,紧接 ...

  5. Acyclic Organic Compounds

    题意: 给一以1为根的字符树,给出每个节点的字符与权值,记 $diff_{x}$ 为从 $x$ 出发向下走,能走到多少不同的字符串,求问最大的$diff_{x} + c_{x}$,并求有多少个 $di ...

  6. python GUI尝鲜(但当涉猎,见往事耳)

    第一步:简单的窗口和内容 import tkinter as tk window = tk.Tk() # 窗口obj对象 window.title('my TK') # 窗口名字 window.geo ...

  7. xml的的特殊字符转义&

    &amp   ampersand   连接符   & &quot   quotation     双引号    “ &apos  apostrophe   单引号   ...

  8. PHP实用小程序(七)

    <? //用COOKIE保存投票人的投票记录 if($vote && !$already_voted) SetCookie("already_voted",& ...

  9. 各大牛逼讲师的经典Jquery精品视频教程,大放送啦!!!(包括手机移动端JqueryWeb开发)!!!

    各大牛逼讲师的经典Jquery精品视频教程,大放送啦!!!(包括手机移动端JqueryWbd开发)!!! [1]jQuery手机端开发视频教程篇 [10]扬中科JQuery基础教程.zip [15]J ...

  10. iOS代码封装成.a文件(封装SDK)

    在众多开源的大神的博客里经整理如下:(已测试ok) 一.描述一下 Build ActiveArchitecture Only设置成YES: Architectures按Xcode默认配置,arm64向 ...