flask 学习app代码备份

Posted Halo3224

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask 学习app代码备份相关的知识,希望对你有一定的参考价值。

#!/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代码备份的主要内容,如果未能解决你的问题,请参考以下文章

python学习笔记-flask学习

Flask学习-Flask app启动过程

Python库源码学习1:Flask之app.run

Flask 学习-16.项目设计与蓝图的使用

flask学习:使用配置文件

Flask框架