码迷,mamicode.com
首页 > 其他好文 > 详细

FLASK初步实践

时间:2015-04-22 00:24:10      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

感觉经过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          { font-family: ‘Georgia‘, serif; margin: 0; }
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        { list-style: none; margin: 0; padding: 0; }
.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初步实践

标签:

原文地址:http://www.cnblogs.com/aguncn/p/4445670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!