感觉经过DJANGO,CI,RAILS之类的WEB框架之后,FLASK的思路就比较顺畅了。。。

FLASKR.PY    

import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
    abort, render_template, flash
from contextlib import closing

DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'

app = Flask(__name__)
app.config.from_object(__name__)
#app.config.from_envvar('FLASKR_SETTINGS', silent=True)

def connect_db():
    return sqlite3.connect(app.config['DATABASE'])

def init_db():
    with closing(connect_db()) as db:
    with app.open_resource('schema.sql') as f:
        db.cursor().executescript(f.read())
    db.commit()

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    g.db.close()

@app.route('/')
def show_entries():
    cur = g.db.execute('select title, text from entries order by id desc')
    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    return render_template('show_entries.html', entries = entries)

@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
    abort(401)
    g.db.execute('insert into entries (title, text) values (?, ?)',
        [request.form['title'], request.form['text']])
    g.db.commit()
    flash('New entry was successfully posted.')
    return redirect(url_for('show_entries'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
    if request.form['username'] != app.config['USERNAME']:
        error = 'Invalid password'
    elif request.form['password'] != app.config['PASSWORD']:
        error = 'Invalid password'
    else:
        session['logged_in'] = True
        flash('You were logged in')
        return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

SCHEMA.SQL

drop table if exists entries;
create table entries (
    id integer primary key autoincrement,
    title string not null,
    text string not null
);

layout.html

<!doctype html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
  <h1>Flaskr</h1>
  <div class=metanav>
  {% if not session.logged_in %}
    <a href="{{ url_for('login') }}">log in</a>
  {% else %}
    <a href="{{ url_for('logout') }}">log out</a>
  {% endif %}
  </div>
  {% for message in get_flashed_messages() %}
    <div class=flash>{{ message }}</div>
  {% endfor %}
  {% block body %}{% endblock %}
</div>

login.html

{% extends "layout.html" %}
{% block body %}
  <h2>Login</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
  <form action="{{ url_for('login') }}" method=post>
    <dl>
      <dt>Username:
      <dd><input type=text name=username>
      <dt>Password:
      <dd><input type=password name=password>
      <dd><input type=submit value=Login>
    </dl>
  </form>
{% endblock %}

show_entries.html

{% extends "layout.html" %}
{% block body %}
  {% if session.logged_in %}
    <form action="{{ url_for('add_entry') }}" method=post class=add-entry>
      <dl>
        <dt>Title:
        <dd><input type=text size=30 name=title>
        <dt>Text:
        <dd><textarea name=text rows=5 cols=40></textarea>
        <dd><input type=submit value=Share>
      </dl>
    </form>
  {% endif %}
  <ul class=entries>
  {% for entry in entries %}
    <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
  {% else %}
    <li><em>Unbelievable.  No entries here so far</em>
  {% endfor %}
  </ul>
{% endblock %}

style.css

body            { font-family: sans-serif; background: #eee; }
a, h1, h2       { color: #377BA8; }
h1, h2          {; }
h1              { border-bottom: 2px solid #eee; }
h2              { font-size: 1.2em; }

.page           { margin: 2em auto; width: 35em; border: 5px solid #ccc;
                  padding: 0.8em; background: white; }
.entries        {;; }
.entries li     { margin: 0.8em 1.2em; }
.entries li h2  { margin-left: -1em; }
.add-entry      { font-size: 0.9em; border-bottom: 1px solid #ccc; }
.add-entry dl   { font-weight: bold; }
.metanav        { text-align: right; font-size: 0.8em; padding: 0.3em;
                  margin-bottom: 1em; background: #fafafa; }
.flash          { background: #CEE5F5; padding: 0.5em;
                  border: 1px solid #AACBE2; }
.error          { background: #F0D6D6; padding: 0.5em; }

FLASK初步实践的更多相关文章

  1. fabric 初步实践

    在集群部署时,我们经常用到堡垒机作为跳板,堡垒机和集群的其他的用户名.密码.端口号都是不同的,fabric如何进行配置不同的用户.端口号和密码. fabric作为一种强大的运维工具,可以让部署运维轻松 ...

  2. ELK初步实践

    ELK是一个日志分析和统计框架,是Elasticsearch.Logstash和Kibana三个核心开源组件的首字母缩写,实践中还需要filebeat.redis配合完成日志的搜集. 组件一览 名称 ...

  3. caffe初步实践---------使用训练好的模型完成语义分割任务

    caffe刚刚安装配置结束,乘热打铁! (一)环境准备 前面我有两篇文章写到caffe的搭建,第一篇cpu only ,第二篇是在服务器上搭建的,其中第二篇因为硬件环境更佳我们的步骤稍显复杂.其实,第 ...

  4. Flask最佳实践

    https://zhuanlan.zhihu.com/p/22774028?refer=python-cn

  5. Ganglia + Nagios 初步实践

    参考文档: http://www.bubuko.com/infodetail-715636.html http://www.linuxidc.com/Linux/2014-01/95804p2.htm ...

  6. SDN的初步实践--通过netconf协议控制交换机

    1.近期在做一个云服务项目,需要与物理交换机配合实现,通过python编程实现了对物理交换机的控制,完全不需要命令行手工配置交换机, 一定程度上实现了SDN的集中控制的思想. 2.架构图如下: 3.利 ...

  7. jest+vue-test-utils初步实践

    一.起步 1. jest Jest是 Facebook 的一套开源的 JavaScript 测试框架, 它自动集成了断言.JSDom.覆盖率报告等开发者所需要的所有测试工具,配置较少,对vue框架友好 ...

  8. Databus架构分析与初步实践

    简介 Databus是一个低延迟.可靠的.支持事务的.保持一致性的数据变更抓取系统.由LinkedIn于2013年开源.Databus通过挖掘数据库日志的方式,将数据库变更实时.可靠的从数据库拉取出来 ...

  9. 阿里Canal框架(数据同步中间件)初步实践

    最近在工作中需要处理一些大数据量同步的场景,正好运用到了canal这款数据库中间件,因此特意花了点时间来进行该中间件的的学习和总结. 背景介绍 早期,阿里巴巴B2B公司因为存在杭州和美国双机房部署,存 ...

随机推荐

  1. Linux(SLES)挂载NTFS移动硬盘实践

    问题描写叙述: 因为通过測试环境导出的dmp过大,但要求尽快导入至生产server,请网络室打通防火墙后发现測试网络为100M而生产网络贵为1000M却无法发挥不论什么作用即使通过networklin ...

  2. random.sample

    import random k = random.sample(xrange(0x41, 0x5b), 26) print k import random k = random.sample(xran ...

  3. Leetcode - Reverse Words

    比起POJ弱爆了一题,从后往前扫描一遍,O(n)时间,仅仅要注意各种极端情况就可以,不明确通过率为什么仅仅有13%. #include<iostream> #include<stri ...

  4. [Javascript] Logging Pretty-Printing Tabular Data to the Console

    Learn how to use console.table to render arrays and objects in a tabular format for easy scanning ov ...

  5. Eclipse debug经常使用基本技巧

    1.F5单步调试,步入,进入函数体内部 2.F6单步调试.步过.不进入函数体 3.F7返回 4.F8运行到最后 5.退出时.右键点击右上角Debug选择退出就可以 $(function () { $( ...

  6. JAVA复习2 JAVA开发环境配置

    我想写的东西主要是JAVA编程里的难点和易混淆点,所以在这里给大家提供一些经典的博客地址或网址.. W3C JAVA教程  JAVA开发环境配置篇: http://www.w3cschool.cc/j ...

  7. 如何判断MSSQL数据库磁盘出现了瓶颈

    问大神石沫:如何判断MSSQL数据库磁盘出现了瓶颈? 石沫(A1):您好,您的问题非常好,SQL SERVER提供了很多关于I/O压力的性能计数器,请选择性能计算器PhysicalDisk(Logic ...

  8. 解决XCode 4.x SVN无法连接的问题

    XCode升级到4.X版本后,确实好用了不少.但普通都存在SVN无法连接的问题.XCode4.x Source Control功能迁移到了File - Source Control目录下,也出现了一些 ...

  9. [转] Linux下查看文件和文件夹大小

    当磁盘大小超过标准时会有报警提示,这时如果掌握df和du命令是非常明智的选择. df可以查看一级文件夹大小.使用比例.档案系统及其挂入点,但对文件却无能为力.    du可以查看文件及文件夹的大小. ...

  10. maven 启动忽略test

    两种方法 1,--命令 mvn install -Dmaven.test.skip=true 2.pom.xml 文件 在tomcat 下面的pom.xml 文件里面加上如下 <!--  ski ...